Level 3 In-Depth AI · Deep Learning
Dropout and Regularizing Neural Networks
Neural networks are big enough to memorise their training data. Dropout switches off random neurons during training so no neuron can rely on another; weight decay, data augmentation and early stopping attack overfitting from other directions. And a puzzle remains: why do huge networks generalise at all?
- Level
- ●●●●● Easy
- Reading
- 14 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 17 concepts →
- Quiz
- 5 questions ↓
This leads to
Training Neural Networks in PracticeThe full path from zero — 17 concepts before this one
- What Is AI?
- Derivatives and Slopes
- Vectors
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Supervised Learning
- Training, Validation and Test Sets
- Linear Regression
- The Perceptron
- Overfitting and the Bias–Variance Tradeoff
- Logistic Regression
- Regularization: L1 and L2
- Neural Networks
- Dropout and Regularizing Neural Networks
Read them roughly in this order. See it on the concept map →
Why it matters
A modern neural network usually has far more parameters than it has training examples. The small digit network in this chapter has 300,000 weights and sees only 100 images. A network that size can simply memorise its training set, answering every training example perfectly while learning nothing that transfers to new data. That is Overfitting and the Bias–Variance Tradeoff, and the general cure, making a model prefer simpler explanations, is Regularization: L1 and L2.
Neural networks have their own toolkit for this. Dropout, which randomly switches off neurons during training, was one of the tricks that made AlexNet work in 2012, and it is still in most Transformer fine-tuning recipes. Weight decay, data augmentation and early stopping are just as common. Knowing what each one does, and when it matters, is part of every practical training run (see Training Neural Networks in Practice).
There is also a deeper puzzle. Huge networks can memorise random noise, yet when trained on real data they usually generalise well, often better as they get bigger. Classical statistics says that shouldn't happen. The last part of this chapter explains what is known about why.
The intuition
Imagine a team project where one member is brilliant and everyone else lets them do all the work. The team performs well until that member is off sick, and then it collapses. A manager who wants a robust team might send random members home each day, so everyone has to learn to contribute and nobody can lean on a single colleague.
That is dropout. During training, each hidden neuron is switched off at random, typically half of them or one in ten, on every training step. A neuron can't count on any particular other neuron being there, so it can't learn a fragile pattern that only works in combination with a specific partner. Each neuron has to be useful on its own, in many different company. This tendency of neurons to rely on each other is called co-adaptation, and dropout breaks it.
There's a second way to see it. Each random pattern of switched-off neurons defines a different, thinner network. A layer of 100 neurons can be thinned in ways, so training with dropout trains an astronomical number of thinned networks at once, all sharing the same weights. At evaluation time, using the full network acts like averaging all of them. Averaging many models, an ensemble, is one of the most reliable ways to improve predictions, and dropout gets something like it almost for free.
Key idea Dropout zeroes each hidden activation with probability during training and scales the survivors by ; at evaluation it does nothing. It stops neurons relying on each other and acts like averaging many thinned networks. Combine it with weight decay, data augmentation and early stopping, and always watch the validation loss.
How it works
The dropout operation
During training, for each activation in a layer, draw a random number. With probability (the dropout rate), set the activation to zero. Otherwise keep it, multiplied by :
The random 0-or-1 numbers form the mask, a fresh one for every example on every step. At evaluation time there is no mask and no scaling: .
Why scale by ? Because the next layer should see the same average input in training as in evaluation. Each value survives with probability , so its average after masking is . Dividing by brings the average back to . This is called inverted dropout, and it's what every modern library does. (The original paper instead scaled the weights down at test time; the effect is the same.)
A worked example
Take a layer's activations and a dropout rate . The survivors are multiplied by . Suppose the random mask comes out as : the third and fifth values are dropped.
On the next step a different mask drops different values. Averaged over 100,000 random masks, the output comes back to , the original values, as intended. At evaluation the layer just passes straight through.
During Backpropagation, dropped neurons pass back no gradient, so their incoming weights aren't updated on that step. Every neuron still gets trained, just on a random subset of steps.
Choosing the rate
- was the classic choice for large fully connected layers, as in AlexNet.
- is common in Transformers. The original 2017 Transformer used 0.1.
- Input layers, if dropped at all, use small rates such as 0.1–0.2. Dropping half the pixels of an image throws away too much.
- Many large language models are pretrained with little or no dropout. They see each training example only about once, so there is little chance to memorise, and dropout would just slow learning. It often returns when Fine-Tuning on small datasets.
Dropout is usually placed after the activation function in fully connected layers. In convolutional networks it's used less, partly because BatchNorm already adds noise and regularises. Variants drop larger units: spatial dropout drops whole channels of an image, and stochastic depth randomly skips whole residual blocks during training.
The rest of the toolkit
Dropout is one of several regularisers, and in practice they are combined.
Weight decay shrinks every weight a little towards zero at each step, which discourages the network from relying on a few very large weights. It is the neural-network form of L2 Regularization: L1 and L2. With Adam, use AdamW so the decay is applied correctly (see Optimizers: SGD, Momentum and Adam). Typical values are 0.01 to 0.1 for AdamW.
Data augmentation creates new training examples from old ones by applying changes that shouldn't change the answer: flipping, cropping, rotating or recolouring images, adding noise to audio, or paraphrasing text. The network can't memorise examples that are slightly different each time it sees them, and it learns that the answer doesn't depend on those changes. For images this is often the single most effective regulariser. See Data Augmentation.
Early stopping watches the loss on a held-out validation set and keeps the model from the epoch where it was lowest. The training loss keeps falling as the network memorises, but the validation loss eventually starts rising. Stopping at its minimum is simple and nearly free. A patience setting, such as "stop after 10 epochs without improvement", avoids reacting to noise.
Label smoothing trains a classifier on slightly softened targets, for example 0.9 for the correct class and the remaining 0.1 spread over the others, instead of a hard 1 and 0s. It stops the network from pushing its outputs towards infinite confidence.
A real experiment
To see these effects, train a deliberately oversized network (two hidden layers of 512 neurons, about 300,000 weights) on only 100 images from the digits dataset, testing on the remaining 1,697, for 300 epochs.
| Regularisation | Validation loss at end | Test accuracy at end | Epoch with lowest validation loss |
|---|---|---|---|
| None | 0.391 | 92.3% | 19 |
| Dropout 0.5 | 0.375 | 92.0% | 40 |
| Random 1-pixel shifts | 0.270 | 91.8% | 187 |
| Dropout + weight decay 0.1 + shifts | 0.218 | 92.1% | 289 |
Read the table honestly. On this easy dataset, the test accuracy hardly changes: every version gets about 92% of digits right. What changes is the validation loss, which measures how confident the predictions are when they're wrong as well as right. Without regularisation, the network becomes extremely confident about everything, including its mistakes, and its validation loss rises after epoch 19. Regularised, it stays better calibrated, and its validation loss ends 44% lower. On larger and harder problems the accuracy gains are larger too. The AlexNet paper reported that without dropout their network overfitted substantially.
Notice the last column. Without regularisation the best moment to stop was epoch 19; with all three regularisers, the network kept improving until nearly the end. That's a useful sign in practice: regularisation lets you train longer before overfitting starts.
Why do huge networks generalise at all?
Classical statistics teaches the bias–variance tradeoff: a model with too many parameters for its data will fit the noise and generalise badly. By that logic, a network with millions of parameters and thousands of examples should be hopeless. Yet such networks are trained every day and work well. Three findings help explain this, though as of late 2026 the full theory is still incomplete.
Networks can memorise, but don't have to. In 2017, Chiyuan Zhang and colleagues trained standard image networks on CIFAR-10 with the labels replaced by random ones. The networks reached 100% training accuracy anyway, which shows they have the capacity to memorise pure noise. The same networks trained on real labels generalise well. So capacity alone can't explain generalisation; something about the training process and the data matters.
Gradient descent has its own preferences. Training with SGD from small random weights doesn't find an arbitrary solution that fits the data. Among the many solutions that fit, it tends to find simple, smooth ones. This built-in preference, which comes from the optimisation method rather than an explicit penalty, is called implicit regularization. The noise of mini-batch training seems to add to it.
Bigger can be better: double descent. As you increase a model's size, test error often first falls, then rises as the model becomes just big enough to fit the training data exactly, and then falls again as the model grows further. This double descent curve was described by Mikhail Belkin and colleagues in 2019 and shown in deep networks by Preetum Nakkiran and colleagues the same year. Very large models, past the peak, can be better than mid-sized ones. See Overfitting and the Bias–Variance Tradeoff for the curve.
Add the inductive biases built into architectures such as convolutional networks, and the huge amounts of data used by modern models, and the picture is consistent: explicit regularisers like dropout help, but they are only part of why deep learning generalises.
In code
Inverted dropout in NumPy, including the check that its average is unchanged:
import numpy as np
def dropout(h, p, training, rng):
if not training or p == 0:
return h # evaluation: do nothing
mask = rng.random(h.shape) >= p # keep each value with probability 1 - p
return h * mask / (1 - p) # scale survivors up ("inverted dropout")
rng = np.random.default_rng(1)
h = np.array([2.0, 1.0, 3.0, 0.5, 4.0])
print("one training pass:", dropout(h, 0.4, True, rng).round(3))
print("evaluation: ", dropout(h, 0.4, False, rng))
avg = np.mean([dropout(h, 0.4, True, rng) for _ in range(100_000)], axis=0)
print("average of 100,000 training passes:", avg.round(2))
# one training pass: [3.333 1.667 0. 0.833 0. ]
# evaluation: [2. 1. 3. 0.5 4. ]
# average of 100,000 training passes: [1.99 1. 2.99 0.5 4. ]
The regularisation experiment in PyTorch. nn.Dropout is active after model.train() and does nothing after model.eval():
import torch
from torch import nn
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
digits = load_digits()
X = torch.tensor(digits.data, dtype=torch.float32) / 16
y = torch.tensor(digits.target)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, train_size=100, random_state=0) # only 100 training images
def shift(xb): # augmentation: move the images by up to 1 pixel
dx, dy = torch.randint(-1, 2, (2,))
return torch.roll(xb.view(-1, 8, 8), shifts=(int(dy), int(dx)), dims=(1, 2)).reshape(-1, 64)
def run(p_drop=0.0, wd=0.0, aug=False, epochs=300):
torch.manual_seed(0)
model = nn.Sequential(nn.Linear(64, 512), nn.ReLU(), nn.Dropout(p_drop),
nn.Linear(512, 512), nn.ReLU(), nn.Dropout(p_drop), nn.Linear(512, 10))
opt = torch.optim.AdamW(model.parameters(), lr=1e-3, weight_decay=wd)
val_losses = []
for epoch in range(epochs):
model.train() # dropout on
for i in range(0, 100, 20):
xb = shift(X_tr[i:i+20]) if aug else X_tr[i:i+20]
loss = nn.functional.cross_entropy(model(xb), y_tr[i:i+20])
opt.zero_grad(); loss.backward(); opt.step()
model.eval() # dropout off
with torch.no_grad():
val_losses.append(nn.functional.cross_entropy(model(X_te), y_te).item())
acc = (model(X_te).argmax(1) == y_te).float().mean().item()
best = min(range(epochs), key=val_losses.__getitem__)
return val_losses[-1], acc, best + 1
for name, kw in [("nothing", {}), ("dropout 0.5", dict(p_drop=0.5)), ("shifts", dict(aug=True)),
("dropout + decay + shifts", dict(p_drop=0.5, wd=0.1, aug=True))]:
vl, acc, best = run(**kw)
print(f"{name:25s} final val loss {vl:.3f} test acc {acc:.3f} best epoch {best}")
# nothing final val loss 0.391 test acc 0.923 best epoch 19
# dropout 0.5 final val loss 0.375 test acc 0.920 best epoch 40
# shifts final val loss 0.270 test acc 0.918 best epoch 187
# dropout + decay + shifts final val loss 0.218 test acc 0.921 best epoch 289
To use early stopping, save a copy of the model's state_dict() whenever the validation loss reaches a new low, and load it back at the end.
Common pitfalls
- Forgetting
model.eval(). Dropout stays active in training mode, so predictions become random and worse. Evaluate in eval mode, and switch back withmodel.train()afterwards. - Dropout before BatchNorm. Dropout changes the variance of activations between training and evaluation, which upsets BatchNorm's running statistics. If you use both, put dropout after the last normalisation layer, or skip it.
- Too much dropout on a small network. Dropout reduces effective capacity. If the training loss stays high, the model is underfitting, so lower or remove dropout.
- Judging by training loss. Regularisation makes the training loss higher, by design. Compare models on validation loss and validation metrics.
- Choosing the stopping epoch with the test set. If you pick the best epoch by test-set performance, the test set is no longer an honest estimate. Use a separate validation set. See Training, Validation and Test Sets.
Watch out A training loss near zero and a validation loss that has started climbing is the classic signature of overfitting. Don't keep training in the hope that it will turn around. Add regularisation, add data or augmentation, or stop at the validation minimum.
Where it leads
- Regularization: L1 and L2: the general idea, including L1 and L2 penalties, for all kinds of models.
- Overfitting and the Bias–Variance Tradeoff: bias, variance, learning curves and double descent.
- Data Augmentation: the most powerful regulariser for images.
- Normalization Layers: BatchNorm and LayerNorm: another layer with different training and evaluation behaviour, and a mild regulariser itself.
- Training Neural Networks in Practice: putting regularisation into a full training recipe.
- Transfer Learning: starting from a pretrained network is one of the best defences against overfitting a small dataset.
A bit of history
Geoffrey Hinton and colleagues introduced dropout in a 2012 preprint, describing it as a way to prevent the "co-adaptation of feature detectors". The same year, Alex Krizhevsky, Ilya Sutskever and Hinton used it in the fully connected layers of AlexNet, which won the ImageNet competition by a wide margin. Nitish Srivastava and colleagues published the full study in the Journal of Machine Learning Research in 2014. Yarin Gal and Zoubin Ghahramani showed in 2016 that keeping dropout on at test time and averaging several predictions gives an estimate of the model's uncertainty, a technique called Monte Carlo dropout.
Weight decay and early stopping are much older and were standard tools in the neural-network work of the 1980s and 1990s. The modern questions about generalisation came later: the random-label experiments of Zhang and colleagues in 2017, and the double descent results of Belkin and colleagues and Nakkiran and colleagues in 2019, reshaped how researchers think about overfitting in very large models.
Try it
- In the PyTorch experiment, try
p_drop=0.2andp_drop=0.8. Which gives the lowest final validation loss? What happens to the training loss with 0.8?- Add early stopping to
run: keep a copy of the model with the lowest validation loss and report its test accuracy. Does it beat the final model for "nothing"?- Change
train_size=100totrain_size=1000. How much do the regularisers matter now?Hint for 2:
import copyand savebest_state = copy.deepcopy(model.state_dict())whenever the validation loss improves.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Dropout: A Simple Way to Prevent Neural Networks from Overfitting
The dropout paper: randomly switching off neurons during training.
Dive into Deep Learning
An interactive book with maths, figures and runnable PyTorch code for every chapter. Many universities use it.
Understanding Deep Learning
A modern, beautifully illustrated textbook covering everything from basics to Transformers and diffusion, with notebooks.
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
Understanding deep learning requires rethinking generalization
Shows that standard image networks can perfectly fit random labels, so classical capacity arguments cannot explain why they generalise on real data.
Deep Double Descent: Where Bigger Models and More Data Hurt
Shows double descent in modern deep networks as a function of model size, training time and data size.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/dl/dropout.md