4.6 Dropout

When an overparameterized network trains for many epochs on scarce or noisy data, it eventually memorizes training quirks and corrupted labels (Section 4.5). Where weight decay (Section 2.7) penalizes large weights and early stopping (Section 4.5.4) halts training before late-stage memorization, dropout (Hinton et al., 2012; Srivastava et al., 2014) regularizes a network by injecting multiplicative noise directly into its hidden layers during training: on every forward pass, each hidden unit is independently zeroed out with probability pp, forcing every unit to learn features that work reliably without counting on specific partner units (co-adaptation). At test time, dropout is disabled and the full network runs deterministically.

In this section, we formulate inverted dropout masking and rescaling, implement it from scratch and concisely in a two-hidden-layer MLP on Fashion-MNIST, and demonstrate on a heavily corrupted label-noise experiment how dropout slows memorization and how much validation accuracy that saves.

4.6.1 Noise in Hidden Layers#

4.6.1.1 Masking and Rescaling (Inverted Dropout)#

Injecting random noise into inputs during training encourages smooth, perturbation-resilient functions (Bishop, 1995); in fact, for a linear model w⊤x+b\mathbf{w}^\top\mathbf{x} + b under squared error, adding zero-mean independent noise of variance s2s^2 to the inputs adds s2∥w∥22s^2\|\mathbf{w}\|_2^2 to the expected loss, which is ℓ2\ell_2 weight decay. Dropout extends noise injection to hidden layers via random binary masking.

For a hidden activation hjh_j and dropout probability p∈[0,1)p \in [0, 1), on each training step we draw an independent Bernoulli mask ξj∈{0,1}\xi_j \in \{0, 1\} with P(ξj=0)=pP(\xi_j = 0) = p and P(ξj=1)=1−pP(\xi_j = 1) = 1 - p, and replace hjh_j with

hj′=ξjhj1−p={0with probability p,hj1−pwith probability 1−p.(4.6.1)h_j' = \frac{\xi_j h_j}{1 - p} = \begin{cases} 0 & \textrm{with probability } p,\\ \dfrac{h_j}{1 - p} & \textrm{with probability } 1 - p. \end{cases} \tag{4.6.1}

Dividing the surviving activations by 1−p1 - p during training (inverted dropout) keeps the expectation unbiased:

E[hj′]=p⋅0+(1−p) hj1−p=hj,Var[hj′]=p1−p hj2.\mathbb{E}[h_j'] = p \cdot 0 + (1 - p)\,\frac{h_j}{1 - p} = h_j, \qquad \mathrm{Var}[h_j'] = \frac{p}{1 - p}\,h_j^2.

Because E[hj′]=hj\mathbb{E}[h_j'] = h_j is preserved during training, at inference time we simply turn dropout off (hj′=hjh_j' = h_j) without any weight rescaling. (Note that for a linear regression model with input dropout, the variance formula Var[xj′]=p1−pxj2\mathrm{Var}[x_j'] = \frac{p}{1-p}x_j^2 adds an adaptive ridge penalty E[(w⊤x′+b−y)2]=(w⊤x+b−y)2+p1−p∑jxj2wj2\mathbb{E}[(\mathbf{w}^\top\mathbf{x}' + b - y)^2] = (\mathbf{w}^\top\mathbf{x} + b - y)^2 + \frac{p}{1-p}\sum_j x_j^2 w_j^2 to the squared loss; in a deep nonlinear network, because E[ReLU(z)]≠ReLU(E[z])\mathbb{E}[\mathrm{ReLU}(z)] \neq \mathrm{ReLU}(\mathbb{E}[z]), the deterministic test-time network is an effective approximation to the ensemble of 2h2^h thinned subnetworks—see Exercises 3 and 5.)

4.6.2 Implementation#

4.6.2.1 The Dropout Layer#

Our from-scratch dropout_layer(X, dropout) draws a uniform tensor in [0,1)[0, 1), keeps entries ≥\geq dropout, and divides by 1.0 - dropout (returning zeros when dropout == 1):

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)

Let us test dropout_layer on a 2×82 \times 8 tensor with dropout probabilities 00, 0.50.5, and 11. We also apply p=0.2p = 0.2 to a vector of one million ones and verify that its empirical mean and variance match the theoretical values 11 and p/(1−p)=0.25p/(1 - p) = 0.25.

X = d2l.reshape(d2l.arange(16, dtype=d2l.float32), (2, 8))
for p in (0, 0.5, 1):
    print(f'p = {p}:', dropout_layer(X, p))
Y = dropout_layer(d2l.ones(10**6), 0.2)
print(f'mean {float(d2l.reduce_mean(Y)):.3f}, '
      f'variance {float(d2l.reduce_mean((Y - 1) ** 2)):.3f}')
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

4.6.2.2 Defining and Training the Model from Scratch#

We apply dropout to the outputs of each hidden layer right after its ReLU activation (Figure 4.6.1)—active only during training. Below we define our He-initialized two-hidden-layer classifier DropoutMLPScratch (784→256→256→10784 \to 256 \to 256 \to 10) with separate dropout probabilities dropout_1 and dropout_2:

Figure 4.6.1:

Dropout silences a random subset of hidden units (h2h_2 and h5h_5 shown) and their incident connections on each training step.

The layers test self.training, which the trainer's model.eval() sets to False.

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

We now instantiate DropoutMLPScratch with dropout_1 = 0.2 after the first hidden layer, dropout_2 = 0.5 after the second, and learning rate lr = 0.1 (packing the hyperparameters into hparams for reuse below), and train it for 2020 epochs on Fashion-MNIST:

hparams = {'num_outputs': 10, 'num_hiddens_1': 256, 'num_hiddens_2': 256,
           'dropout_1': 0.2, 'dropout_2': 0.5, 'lr': 0.1}
model = DropoutMLPScratch(**hparams)
data = d2l.FashionMNIST(batch_size=256)
trainer = d2l.Trainer(max_epochs=20, num_gpus=1)
trainer.fit(model, data)

Notice that during the opening epochs, training loss sits above validation loss because training loss is evaluated with noisy dropout masks active while validation loss runs the full deterministic network.

4.6.2.3 Concise Implementation#

Using framework Dropout layers inside Sequential, we can express the exact same two-hidden-layer architecture in a few lines:

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)

4.6.3 Effects of Dropout under Label Noise#

On the full 60,00060{,}000-image Fashion-MNIST dataset over 20 epochs, an unregularized MLP barely overfits, leaving little room for dropout to shine. To watch dropout combat severe memorization, we return to the 1,0001{,}000-image noisy-label benchmark from Section 4.5.4, corrupting 40%40\% of the training labels at random via d2l.corrupt (∼36%\sim 36\% wrong labels, indexed by the Boolean mask wrong = labels != y):

images = d2l.FashionMNIST(batch_size=2000)
X, y = (d2l.numpy(a) for a in next(iter(images.train_dataloader())))
X_val, y_val = (d2l.numpy(a) for a in next(iter(images.val_dataloader())))
X, y, X_val = X[:1000].reshape(1000, -1), y[:1000], X_val.reshape(2000, -1)
labels = d2l.corrupt(y, 0.4, np.random.default_rng())
wrong = labels != y  # The training labels that are now wrong

We now train DropoutMLP for 200200 epochs on (X, labels) with dropout probability p = 0 (no dropout) versus p = 0.5 in both hidden layers, using d2l.Tracker to record accuracy on the corrupted training subset X[wrong] alongside held-out validation accuracy on X_val:

acc = {}
for p in (0, 0.5):
    trainer = d2l.Tracker(max_epochs=200, datasets={
        'wrong labels': d2l.ArrayData(X[wrong], labels[wrong], 1000),
        'validation': d2l.ArrayData(X_val, y_val, 1000)})
    trainer.fit(DropoutMLP(**{**hparams, 'dropout_1': p, 'dropout_2': p}),
                d2l.ArrayData(X, labels))
    acc[p] = trainer.accuracy
    print(f'dropout {p}: wrong labels reproduced '
          f'{acc[p]["wrong labels"][-1]:.2f}, validation accuracy over the '
          f'last 10 epochs {np.mean(acc[p]["validation"][-10:]):.3f}')
d2l.plot(list(range(1, 201)), [acc[0]['wrong labels'], acc[0.5]['wrong labels'],
                               acc[0]['validation'], acc[0.5]['validation']],
         'epoch', 'accuracy', fmts=('C0--', 'C1--', 'C0-', 'C1-'),
         legend=['wrong labels, p = 0', 'wrong labels, p = 0.5',
                 'validation, p = 0', 'validation, p = 0.5'],
         legend_loc='outside', figsize=(4.5, 3))
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

Look at the two trajectories:

  • Without dropout (p=0p = 0): By epoch 100, the MLP memorizes 100%100\% of the corrupted training labels, and validation accuracy degrades by ∼10\sim 10 percentage points from its early peak.
  • With dropout (p=0.5p = 0.5): Memorization of wrong labels slows down. At epoch 200 the MLP reproduces roughly 7070–85%85\% of them instead of all, and validation accuracy over the final 10 epochs is 3 to 6 percentage points higher than for the unregularized network. The wrong-label curve is still rising, though: dropout delays the damage rather than removing it, which is why it is combined with early stopping.

In practice, dropout is most valuable precisely when parameter count dwarfs dataset size and training runs for many epochs (as in early-2010s vision classifiers like AlexNet in Section 7.1); in single-pass foundation-model pretraining or directly before batch normalization layers (Section 7.3, where dropout's 1/(1−p)1/(1-p) training variance inflation creates a train--test variance shift (Li et al., 2019)), dropout is typically reduced or omitted.

4.6.4 Summary#

Inverted dropout zeroes out each hidden activation independently with probability pp and rescales surviving activations by 1/(1−p)1/(1 - p) during training. Because this rescaling preserves E[hj′]=hj\mathbb{E}[h_j'] = h_j while injecting variance p1−phj2\frac{p}{1 - p}h_j^2, the full unmasked network runs deterministically at test time without any weight rescaling. On small or noisy datasets where parameter count far exceeds sample size, dropout discourages fragile co-adaptation across hidden units, slows the memorization of corrupted labels, and lifts held-out accuracy by several percentage points. Because it delays rather than prevents eventual memorization, dropout works best alongside early stopping and weight decay.

4.6.5 Exercises#

  1. [code] Dropout probabilities. The model of this section drops units with probability 0.2 after the first hidden layer and 0.5 after the second.

    1. Train it with the two probabilities swapped, with both set to 0.5, and with both set to 0.8. For each run, report the best validation accuracy. Which layer tolerates the higher probability?
    2. The Trainer computes the training loss that it plots with the masks switched on. After training, evaluate the loss on the training images with the masks switched off, and compare the gap between training and validation loss for the networks trained with and without dropout.
  2. Dropout and He initialization. The He initialization of Section 4.4.2.2 chooses the variance of the weights so that the mean square of the pre-activations stays the same from layer to layer.

    1. During training, by what factor does dropout with probability pp change the mean square of the pre-activations of the next layer? Give the factor for each of the two dropout layers of this section's model.
    2. In a network with K−1K - 1 hidden layers, each followed by dropout with probability pp, how does the factor grow with KK? Should the initialization correct for it, given that the network runs without dropout at test time? Relate your answer to the mismatch between training and test that dropout causes before a batch normalization layer.
  3. [code] Monte Carlo dropout. Instead of switching dropout off at test time, keep it on in the trained DropoutMLPScratch and run T=20T = 20 forward passes per validation image, then average the softmax outputs (Gal and Ghahramani, 2016). Compare the accuracy and the calibration (the mean of the largest softmax probability against the accuracy) with those of the single pass of the full network. How does the accuracy change as TT grows from 1 to 20?

  4. [code] Dropout and weight decay. Weight decay and dropout both regularize the model of this section, by different mechanisms. Measure each run by its best validation accuracy and by the gap between training and validation loss, with both losses evaluated with the masks switched off.

    1. With both dropout probabilities set to zero, add weight decay as in Section 2.7 at strengths λ∈{10−4,10−3,10−2}\lambda \in \{10^{-4}, 10^{-3}, 10^{-2}\}. Compare these runs with the runs with and without dropout of this section.
    2. Keep the dropout probabilities at 0.2 and 0.5, and add weight decay at the same strengths. Are the effects of the two regularizers additive, do they show diminishing returns, or do they cancel each other out?
  5. Dropout at test time. ● Set dropout_1 to zero, so that only the second hidden layer is masked, and let ξ\boldsymbol{\xi} range over its masks. Let o(ξ)\mathbf{o}(\boldsymbol{\xi}) and y^(ξ)\hat{\mathbf{y}}(\boldsymbol{\xi}) be the logits and the softmax output under mask ξ\boldsymbol{\xi}, which occurs with probability P(ξ)P(\boldsymbol{\xi}). Show that the logits of the full network equal ∑ξP(ξ) o(ξ)\sum_{\boldsymbol{\xi}} P(\boldsymbol{\xi})\, \mathbf{o}(\boldsymbol{\xi}). Show further that its softmax output equals the normalized weighted geometric mean

y~j=∏ξy^j(ξ)P(ξ)∑k∏ξy^k(ξ)P(ξ).(4.6.2)\tilde{y}_j = \frac{\prod_{\boldsymbol{\xi}} \hat{y}_j(\boldsymbol{\xi})^{P(\boldsymbol{\xi})}}{\sum_k \prod_{\boldsymbol{\xi}} \hat{y}_k(\boldsymbol{\xi})^{P(\boldsymbol{\xi})}}. \tag{4.6.2}

Explain why neither equality holds in general once dropout_1 is nonzero.

Discussions