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
Dropout: Regularization via Multiplicative Hidden Noise
co-adaptation · inverted dropout 1/(1-p) · train vs. test semantics · slowing noisy-label memorization
Motivation & Co-Adaptation
Noise as Regularization
\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
Mathematical Formulation
h_j' = \frac{\xi_j\, h_j}{1 - p}, \qquad \xi_j \sim \mathrm{Bernoulli}(1 - p)
Second-Moment Scaling
\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
Linear Exactness vs. ReLU Approximation
How does the deterministic test-time network (h_j' = h_j) relate to the 2^h random subnetworks sampled during training?
1. Exact adaptive ridge on a linear layer:
\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. Nonlinear expectation mismatch (\mathbb{E}[\mathrm{ReLU}(z)] \neq \mathrm{ReLU}(\mathbb{E}[z])):
| (h_1', h_2') at p = 0.5 | (0, 0) | (2, 0) | (0, 2) | (2, 2) |
|---|---|---|---|---|
| Pre-activation z = h_1' - h_2' | 0 | +2 | -2 | 0 |
| \mathrm{ReLU}(z) = \max(z, 0) | 0 | 2 | 0 | 0 |
From-Scratch Layer
Our dropout_layer(X, dropout) draws uniform random numbers in [0, 1), keeps entries \ge p, and rescales by 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
Architecture & Mode Switching
We insert dropout immediately after each hidden layer’s ReLU activation—active only during training and bypassed during validation/inference:
dropout_1 = 0.2) to preserve raw feature signal; stronger dropout deeper (dropout_2 = 0.5) where co-adaptation risk is highest.From-Scratch Model
In DropoutMLPScratch, we guard each dropout_layer call with the framework’s training-mode flag:
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.b3Full-Dataset Benchmark
Training DropoutMLPScratch for 20 epochs on all 60{,}000 images reaches \sim 87\% validation accuracy:
train_loss is evaluated on noisy, thinned networks (p_1 = 0.2, p_2 = 0.5), whereas val_loss uses the clean unmasked ensemble approximation.High-Level API
Framework Sequential containers interleave Dropout(p) modules after each ReLU, automatically toggling masks between train and eval modes inside Trainer:
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)Label-Noise Stress Test
On the 1{,}000-image benchmark with 40\% of labels redrawn (\sim 36\% wrong), we train DropoutMLP for 200 epochs with p = 0 vs. p = 0.5:
C0--), dragging validation accuracy (C0-) down by \sim 10 points from its early peak.C1--, 70–85\% reproduced at epoch 200 and still rising) and finishes 3 to 6 percentage points higher in validation accuracy (C1-).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
Theoretical Perspectives
Modern Engineering Guidelines
Check
Test your command of dropout mathematics and systems behavior:
Answers:
Key Takeaways