AI Logic

Regularization

Dropout

Updated:

Dropout at training time vs. inference time. At training time (left), some units in the input and hidden layers are removed at random, and computation runs on a network with those units and their connections gone. At inference time (right), all units are used and the weights are scaled by the keep probability p

Background and overview

Dropout is a regularization method that curbs overfitting by randomly selecting units (nodes) and temporarily removing them during training. It was introduced by Hinton et al. in 2012 and described in detail by Srivastava et al. in 2014 (JMLR 15).

Networks with many parameters end up memorizing complex relationships that hold only for the training data. The paper attributes part of this to units relying on assumptions that "other units will output such-and-such" (co-adaptation). With Dropout, any unit may disappear at the next moment, so each unit learns features that are useful on their own, without relying on other units. It is like training each team member to do their own job so that the work goes on no matter who is absent.

Another view is ensembling (averaging multiple models). With nn units there are 2n2^n ways to remove them, and Dropout trains a different "thinned network" each time while sharing weights. At inference, a single network approximates the average of all of them.

Dropout is used in many models, starting with the fully connected layers of an MLP. The Transformer also applies Dropout to the output of each sublayer, among other places.

Theory (training and inference)

Following the equations in Section 4 of the paper, here is the computation in a fully connected layer. pp is the probability of keeping a unit.

  1. During training, for each unit jj of layer ll, decide whether to keep it with probability pp. rj(l)∼Bernoulli(p)r_j^{(l)} \sim \mathrm{Bernoulli}(p)
  2. Multiply the output y(l)\boldsymbol{y}^{(l)} element-wise by the 0/1 vector r(l)\boldsymbol{r}^{(l)} (∗* is the element-wise product). Removed units output 0. y~(l)=r(l)∗y(l)\tilde{\boldsymbol{y}}^{(l)} = \boldsymbol{r}^{(l)} * \boldsymbol{y}^{(l)}
  3. Compute the next layer from the thinned output. zi(l+1)=wi(l+1)y~(l)+bi(l+1),yi(l+1)=f ⁣(zi(l+1))z_i^{(l+1)} = \boldsymbol{w}_i^{(l+1)} \tilde{\boldsymbol{y}}^{(l)} + b_i^{(l+1)}, \qquad y_i^{(l+1)} = f\!\left(z_i^{(l+1)}\right)
  4. Repeat steps 1–3 for each training example (each example in the mini-batch), reselecting the units to remove.
  5. At inference, use all units and scale the weights by pp. Wtest(l)=p W(l)W_{\text{test}}^{(l)} = p\, W^{(l)}

The weights are scaled by pp in step 5 so that the output magnitude matches the training-time average. For example, suppose p=0.5p = 0.5 and a unit outputs 2. During training, the value reaching the next layer is either 0 or 2, averaging 1. If nothing is done at inference, 2 arrives every time, twice the training value. Scaling the weights by 0.5 gives 1, matching the training-time average.

Difference from PyTorch's Dropout

The p in PyTorch's nn.Dropout(p) is the probability of dropping a unit. It is the opposite of the paper's pp (keep probability), so the paper's p=0.8p = 0.8 corresponds to nn.Dropout(0.2) in PyTorch.

PyTorch, unlike the paper, scales the outputs of the kept units by 1/(1−p)1/(1-p) during training and does nothing at inference (a method called inverted dropout). The goal of matching the output mean between training and inference is the same, and there is no need to rewrite weights at inference.

This switch is determined by the model's mode.

  • model.train(): Dropout is active (random zeros, the rest scaled by 1/(1−p)1/(1-p)).
  • model.eval(): Dropout does nothing. Always call it before evaluation or inference. If forgotten, predictions change randomly each time and accuracy drops.

Choosing the keep probability and practical tips

Appendix A of the paper summarizes practical guidelines as follows (pp is the keep probability).

  • Hidden layers: p=0.5p = 0.5–0.80.8: The smaller pp (the more units dropped), the stronger the regularization. If it is too small, the model no longer fits even the training data (underfitting), so compensate by adding units.
  • Input layer: about p=0.8p = 0.8 for real-valued inputs such as image patches or speech frames: Dropping too much input loses the information itself.
  • Make the network larger: Since units are reduced by the factor pp, provide more units than without Dropout.
  • Use a larger learning rate and higher momentum: Dropout increases the variance of the gradients. The paper recommends a learning rate 10–100 times that without Dropout and a momentum of 0.95–0.99. It also recommends combining it with max-norm regularization, which caps the norm of the weights.

Dropout makes training take longer. The paper says 2–3 times as long as a standard network with the same architecture, because a different network is trained at every update, which increases the variance of the gradients.

Comparison with derived methods

Methods based on Dropout, arranged by what they remove.

MethodWhat is removedTypical use
DropoutUnits (output elements), one at a timeFully connected layers, Transformers
DropConnectWeights (connections) one at a time instead of unitsFully connected layers
Spatial DropoutWhole feature-map channelsConvolutional layers (neighboring pixels are similar, so dropping single pixels is less effective)
DropBlockContiguous square regions of feature mapsConvolutional layers
Stochastic DepthWhole residual blocksDeep residual networks, Vision Transformers

In convolutional layers, neighboring pixels have similar values, so dropping single pixels lets the information be recovered from the surroundings and Dropout becomes less effective. For this reason, Spatial Dropout and DropBlock, which drop larger units, are used.

PyTorch example

Show code
python
import torch
import torch.nn as nn

# PyTorch's p is the drop probability (the paper's keep probability 0.5 is p=0.5, 0.8 is p=0.2)
drop = nn.Dropout(p=0.5)
x = torch.ones(8)

drop.train()
print(drop(x))   # Each element becomes 0 or 2.0 (= 1 / (1 − 0.5)); which ones are 0 changes every time
drop.eval()
print(drop(x))   # Does nothing at inference: all 1.0


# Fully connected network with Dropout, assuming MNIST
class DropoutMLP(nn.Module):
    def __init__(self, in_dim=28 * 28, hidden_dim=1024, num_classes=10):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Flatten(),
            nn.Dropout(p=0.2),          # Input layer: keep probability 0.8
            nn.Linear(in_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(p=0.5),          # Hidden layer: keep probability 0.5
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(p=0.5),
            nn.Linear(hidden_dim, num_classes),
        )

    def forward(self, x):
        return self.layers(x)


model = DropoutMLP()
optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.95)
criterion = nn.CrossEntropyLoss()

# Training: model.train() enables Dropout
model.train()
images = torch.randn(64, 1, 28, 28)    # Dummy mini-batch
labels = torch.randint(0, 10, (64,))
optimizer.zero_grad()
loss = criterion(model(images), labels)
loss.backward()
optimizer.step()

# Evaluation: model.eval() disables Dropout (if forgotten, predictions change every time)
model.eval()
with torch.no_grad():
    predicted = model(images).argmax(dim=1)

FAQ

Q. How should the dropout rate be chosen?
A.

The paper's guideline in terms of keep probability is 0.5–0.8 for hidden layers and about 0.8 for the input layer (in PyTorch's p, 0.2–0.5 for hidden layers and 0.2 for the input layer). If overfitting appears on validation data, raise the drop probability; if training accuracy is not improving either, lower it. Transformers commonly use 0.1.

Q. Is Dropout ever enabled at inference?
A.

Yes. Keeping Dropout enabled at inference, predicting many times, and using the spread of the results as the prediction uncertainty is called MC Dropout (Gal and Ghahramani, 2016). In normal inference, Dropout is disabled with model.eval().

Q. Which layers should Dropout be applied to?
A.

The basic choice is after fully connected layers with many parameters. It is less effective in convolutional layers, so either omit it there or use Spatial Dropout or DropBlock. Do not apply it right after the output layer (the logits).

References

  1. N. Srivastava, G. Hinton, A. Krizhevsky, I. Sutskever, and R. Salakhutdinov, "Dropout: A Simple Way to Prevent Neural Networks from Overfitting," Journal of Machine Learning Research, 15(56), 1929–1958, 2014.
  2. G. E. Hinton, N. Srivastava, A. Krizhevsky, I. Sutskever, and R. R. Salakhutdinov, "Improving neural networks by preventing co-adaptation of feature detectors," arXiv:1207.0580, 2012.
  3. Y. Gal and Z. Ghahramani, "Dropout as a Bayesian Approximation: Representing Model Uncertainty in Deep Learning," ICML, 2016.
  4. PyTorch Documentation, "torch.nn.Dropout."