def dropout_layer(X, dropout):
assert 0 <= dropout <= 1
if dropout == 1: return torch.zeros_like(X)
mask = torch.rand_like(X) >= dropout
return mask.to(X.dtype) * X / (1.0 - dropout)Dive into Deep Learning · §4.6
暂退法:通过隐藏层乘性噪声实现正则化
共适应 · 反向暂退法 1/(1-p) · 训练与测试语义 · 减缓噪声标签记忆
动机与共适应
以噪声作正则化
\mathbb{E}_{\boldsymbol{\epsilon}}\!\left[\bigl(\mathbf{w}^\top(\mathbf{x} + \boldsymbol{\epsilon}) + b - y\bigr)^2\right] = (\mathbf{w}^\top\mathbf{x} + b - y)^2 + s^2\|\mathbf{w}\|_2^2
数学形式
h_j' = \frac{\xi_j\, h_j}{1 - p}, \qquad \xi_j \sim \mathrm{Bernoulli}(1 - p)
二阶矩缩放
\mathbb{E}\bigl[(h_j')^2\bigr] = \frac{h_j^2}{1 - p}, \qquad \mathrm{Var}[h_j'] = \frac{p}{1 - p}\,h_j^2
线性精确性与 ReLU 近似
确定性测试网络(h_j' = h_j)与训练期采样的 2^h 个随机子网络有何联系?
1. 线性层上的精确自适应岭惩罚:
\mathbb{E}_{\boldsymbol{\xi}}\!\left[(\mathbf{w}^\top\mathbf{x}' + b - y)^2\right] = (\mathbf{w}^\top\mathbf{x} + b - y)^2 + \frac{p}{1 - p}\sum_{j=1}^d x_j^2 w_j^2
2. 非线性期望失配(\mathbb{E}[\mathrm{ReLU}(z)] \neq \mathrm{ReLU}(\mathbb{E}[z])):
| p = 0.5 时的 (h_1', h_2') | (0, 0) | (2, 0) | (0, 2) | (2, 2) |
|---|---|---|---|---|
| 预激活值 z = h_1' - h_2' | 0 | +2 | -2 | 0 |
| \mathrm{ReLU}(z) = \max(z, 0) | 0 | 2 | 0 | 0 |
从零实现暂退层
dropout_layer(X, dropout) 在 [0, 1) 抽取均匀随机数,保留 \ge p 的元素并按 1 / (1 - p) 缩放:
p = 0: tensor([[ 0., 1., 2., 3., 4., 5., 6., 7.],
[ 8., 9., 10., 11., 12., 13., 14., 15.]])
p = 0.5: tensor([[ 0., 2., 4., 6., 8., 10., 12., 14.],
[ 0., 18., 0., 22., 24., 26., 0., 30.]])
p = 1: tensor([[0., 0., 0., 0., 0., 0., 0., 0.],
[0., 0., 0., 0., 0., 0., 0., 0.]])
mean 1.000, variance 0.250
架构与模式切换
将暂退法紧接在各隐藏层 ReLU 激活之后——仅在训练时启用,验证与推理时跳过:
dropout_1 = 0.2)以保留原始特征,深层设较高概率(dropout_2 = 0.5)以抑制共适应。从零实现模型
在 DropoutMLPScratch 中,用框架的训练模式标志保护每次 dropout_layer 调用:
class DropoutMLPScratch(d2l.Classifier):
def __init__(self, num_outputs, num_hiddens_1, num_hiddens_2,
dropout_1, dropout_2, lr, num_inputs=784):
super().__init__()
self.save_hyperparameters()
he = lambda n_in, n_out: nn.Parameter( # Variance 2 / n_in
d2l.normal(0, (2 / n_in) ** 0.5, (n_in, n_out)))
self.W1 = he(num_inputs, num_hiddens_1)
self.W2 = he(num_hiddens_1, num_hiddens_2)
self.W3 = he(num_hiddens_2, num_outputs)
self.b1 = nn.Parameter(d2l.zeros(num_hiddens_1))
self.b2 = nn.Parameter(d2l.zeros(num_hiddens_2))
self.b3 = nn.Parameter(d2l.zeros(num_outputs))
def forward(self, X):
X = X.reshape(-1, self.num_inputs)
H1 = torch.relu(X @ self.W1 + self.b1)
if self.training:
H1 = dropout_layer(H1, self.dropout_1)
H2 = torch.relu(H1 @ self.W2 + self.b2)
if self.training:
H2 = dropout_layer(H2, self.dropout_2)
return H2 @ self.W3 + self.b3完整数据集基准
在全部 60{,}000 张图像上训练 DropoutMLPScratch 共 20 轮,验证准确率可达 \sim 87\%:
train_loss 在含噪稀疏网络(p_1 = 0.2, p_2 = 0.5)上计算,而 val_loss 使用干净的完整集成近似。高级 API
框架的 Sequential 容器在每个 ReLU 后插入 Dropout(p) 模块,Trainer 会在 train 与 eval 模式间自动切换掩码:
class DropoutMLP(d2l.Classifier):
def __init__(self, num_outputs, num_hiddens_1, num_hiddens_2,
dropout_1, dropout_2, lr):
super().__init__()
self.save_hyperparameters()
self.net = nn.Sequential(
nn.Flatten(), nn.LazyLinear(num_hiddens_1), nn.ReLU(),
nn.Dropout(dropout_1), nn.LazyLinear(num_hiddens_2), nn.ReLU(),
nn.Dropout(dropout_2), nn.LazyLinear(num_outputs))
def weight_init(self, module):
if isinstance(module, nn.Linear):
nn.init.kaiming_normal_(module.weight, nonlinearity='relu')
nn.init.zeros_(module.bias)标签噪声压力测试
在随机重抽 40\% 标签(约 \sim 36\% 错标)的 1{,}000 张图像基准上,对比 p = 0 与 p = 0.5 训练 DropoutMLP 共 200 轮:
C0--),验证准确率(C0-)较峰值下降约 \sim 10 个百分点。C1--,第 200 轮仅复现 70~85\% 且仍在上升),最终验证准确率(C1-)高出 3 到 6 个百分点。dropout 0: wrong labels reproduced 1.00, validation accuracy over the last 10 epochs 0.595
dropout 0.5: wrong labels reproduced 0.80, validation accuracy over the last 10 epochs 0.654
理论视角
现代工程指南
自测
检验你对暂退法数学原理与系统行为的掌握:
答案:
核心要点