A network with 64 hidden units and 60 training examples has far more knobs than facts to learn. Give it labels where a fifth are wrong and it will learn the wrong ones too. Its training accuracy reaches nearly , and on new data its loss can be worse than that of a coin flip. Part 3 named this problem overfitting (P3.A3), and showed that the gap between training and validation results is how you see it (P3.A4, P3.A5). Networks are especially prone to it, because they are so flexible (P4.11).
Regularization means anything that gives up a little training fit to do better on new data. P3.A6 did it for linear models with a penalty. This lesson covers the four tools that networks use most: weight decay, dropout, early stopping and label smoothing.
A network that memorizes noise
Here is a small made-up task. Ten inputs are random numbers, but only the first two matter: the true class is when . Then of the labels are flipped at random (in this training set, of ), so the best possible accuracy on fresh data with the same noise is about (on the test set used below, the true rule scores because of sampling). The network has ReLU hidden units, and it is trained by gradient descent on the mean cross-entropy (P4.6, P4.8).
The cell below trains it four ways, five times each with different random starting weights, and reports the average. Weight decay, dropout and early stopping are explained in the sections that follow. For now, read the first row: none means plain training for steps.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
Running the code gives this table (on the machine used for this lesson; the cell takes about a second):
mean of 5 runs train test test
acc acc loss
none 0.997 0.690 1.082
weight decay 0.823 0.703 0.586
dropout 0.5 0.983 0.702 0.842
early stopping 0.810 0.662 0.635
Read it row by row.
- None. The network gets of the training labels right. That includes the flipped ones, so it has memorized the noise. On the test set its accuracy is only , and its test loss is . A model that always answers “50 percent” has loss , so this network is worse than not knowing anything: it is confidently wrong on many new points.
- The other three all have a training accuracy that is lower, or a little lower, and a much smaller test loss. That is what regularization looks like. Their test accuracies are closer together ( to ). Over the five runs, one method’s test accuracy varies by up to about three percentage points (for example to for plain training), so a difference of one or two points between methods here is not reliable. The differences in loss are large and the same in every run.
- Early stopping is not a win on accuracy here. It stopped very early, when the network had only started to learn, and its mean test accuracy is the lowest of the four (; its runs overlap with plain training, so treat the gap as small). A good loss and a good accuracy are different things, and a regularizer can help one and not the other.
This is one made-up task. It shows the pattern, not a ranking of the methods.
In the plain run, training loss falls steadily while validation loss falls, reaches a minimum and then rises, as the network starts to fit noise. The regularizers flatten that rise.
Weight decay
The oldest idea is the one from P3.A6: add a penalty for large weights. For the weights of a network the penalized loss is
Its gradient adds , so one step of gradient descent is
Every step first shrinks every weight by the factor and then takes the usual step. This is weight decay. In the cell above, and , so each step multiplies the weights by . That is a tiny pull per step, but it acts on every one of the steps and the data must keep pushing back for a weight to stay large. Small weights give a smoother function, which is harder to bend around single noisy points. In the table, weight decay cut the training accuracy to and the test loss to .
Three points that cause confusion:
- With Adam it is not the same as the penalty. For plain SGD, the penalty’s gradient and the shrink-by-a-factor form are one update. For Adam they are not, which is why the decoupled form AdamW exists. P4.13 explained this with numbers; here, “weight decay” in a large model usually means AdamW’s version. In PyTorch it is the
weight_decayargument of the optimizer. The two optimizers use different defaults ( forAdam, forAdamW). - Which parameters. The penalty is usually put on the weight matrices. Biases and the scale and shift parameters of normalization layers (P4.19) are often left out. One reason often given is that there are few of them and they do not drive overfitting much. It is a common convention and not a law, and some recipes decay everything. The PyTorch block below shows how to make the two groups. The cell above also leaves the biases alone.
- The size of needs tuning. Too small does nothing, and too large stops the network from fitting even the real pattern. Values such as and are common starting points for AdamW, but the best value depends on the model, the learning rate and the length of training (P4.23).
Dropout
Dropout takes a different route. At every training step, each hidden unit is switched off with probability . A switched-off unit sends to the next layer for this step, and its incoming and outgoing edges might as well not exist. The next step draws a completely new random set. No unit can count on a particular partner being present, so units are pushed to learn features that are useful on their own. (The 2012 arXiv paper by Hinton and co-authors called what is prevented “co-adaptation” of feature detectors. The long version is Srivastava et al., JMLR 2014.)
The mask
Write the output of a layer as . Draw a mask , with one entry per unit, where each is (kept) with probability and (dropped) with probability . The entries are independent of one another, which is the Bernoulli variable of P1.D3 repeated once per unit. In inverted dropout the kept outputs are also scaled up:
where multiplies entry by entry. Press the buttons below. With about half of the 16 hidden units are dropped at each step, but which ones changes every time.
Things to try, and what to notice:
- Next step a few times. The count of kept units jumps around (for ) but is not always . Each unit is its own coin flip, so units are not split exactly in half.
- +100 steps, then again. The average fraction kept moves toward . A fresh mask every step is Monte Carlo sampling (P1.D9), and the average of many masks is steady even though one mask is not.
- Look at unit A. At it sends when kept, never . Its average over many steps comes close to , its unscaled output. That is the reason for the factor .
- Set and look at the label under the hidden layers: kept outputs are multiplied by .
- Turn on Evaluation mode. Every unit is back, nothing is scaled, and unit A sends exactly .
Why the scale
If a unit’s output is and it is kept with probability , then without scaling the expected output is , smaller than . At test time, with every unit present, the next layer would suddenly receive larger inputs than it ever saw in training. Dividing the kept outputs by fixes the average: by linearity of expectation (P1.D4),
The expected value is unchanged. The variance is not: it becomes , which is the noise that dropout adds. For and that is , the same example as in P1.D4. The cell below checks both numbers by simulation, and a layer of eight units.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
fraction kept: 0.75
mean, no scale: 2.251
mean, scaled: 3.001
variance, scaled: 2.997
formula x^2 p/(1-p): 3.0
layer output, mean over steps:
1.00 1.99 3.00 4.00 5.00 6.00 7.01 8.01
units dropped per step: mean 2.0
The unscaled version has mean and the scaled one , as predicted. The variance, , matches . The layer’s mean outputs come back to through , with about of the units dropped per step ().
Train mode and eval mode
Dropout is on only while training. When you use the model to predict, all units are used and nothing is scaled: the layer is the identity function. That works only because the scaling was done during training, which is why this version is called inverted. The original paper kept the training step plain and, at test time, multiplied the weights by the keep probability instead. Both have the same effect on the average, and the inverted form leaves the test-time model unchanged, which is simpler. It is the form PyTorch uses.
In PyTorch the switch is model.train() and model.eval() (P2.7). Forgetting model.eval() before measuring validation accuracy gives noisy and usually worse numbers, and it is a classic bug. Wrap evaluation in torch.no_grad() as well; that part saves memory and does not change the mode.
Two names for
What happens in backpropagation
The mask is part of the forward pass, so the backward pass goes through it (P4.8). A dropped unit sent , so no gradient flows through it and its incoming weights get no update from this example. A kept unit’s gradient is multiplied by the same as its output. Each step trains a different thinned-out sub-network, but all of them share one set of weights.
Why does it help, and where is it used?
Two explanations are common, and both are partial. Dropping units prevents units from relying on one another, as above. The second view: a layer with units has possible masks, so training samples from a huge family of thinned networks, and the full network at test time approximates averaging all of them, as an ensemble (P3.B4). For the hidden units in the picture there are masks. The averaging is approximate and the explanation is a way to think, not a proof.
Where it is used varies. It is common in smaller networks and in fully connected layers, often with between about and , and many transformer implementations include a small dropout. Some very large models trained on huge datasets use little or none, because with enough data overfitting is less of a problem. Treat these as habits to check against a recipe, not rules. Dropout also usually needs more training steps to reach the same training loss, which is why the training loss in the figure above stays higher.
Go deeper Dropout at prediction time on purpose
Some methods keep dropout switched on at prediction time and run the same input several times. The spread of the answers is then used as a rough estimate of how unsure the model is, sometimes called Monte Carlo dropout. How well that spread matches real uncertainty is debated, and it is not the standard way to run a model. It does show that the mask is just a random input to the network, and that eval() is a choice and not something automatic.
Early stopping
The curves above suggest the simplest idea of all: stop training when the validation loss stops improving. The recipe has three parts.
- After every epoch (or every few hundred steps) compute the loss on the validation set (P3.A4).
- Save a copy of the weights whenever the validation loss reaches a new lowest value. This copy is the best checkpoint.
- If the validation loss has not improved for a number of checks in a row, called the patience, stop. Load the best checkpoint, not the last weights.
Patience matters because validation loss is noisy: one bad epoch does not mean the run is over, and one good epoch does not mean it is time to stop. A larger patience is safer and costs more training time. In the cell above, patience was steps. Over the five runs the best checkpoint came between step and step .
Early stopping also acts as a regularizer in its own right: the longer you train, the more complex a function the network can express, so stopping earlier limits it. (In some simple settings stopping early behaves much like weight decay, but this does not carry over exactly to deep networks.)
One more point. The validation set made the choice of stopping step, so its score is a little optimistic by construction. That is why the cell above reports on a separate test set (P3.A4).
Label smoothing
The other three tools act on the weights, the activations or the length of training. Label smoothing works on the target. With a one-hot label, cross-entropy keeps asking for the true class to get probability (P1.E3), and that needs the logit of the true class to be infinitely larger than the others. The loss never says “enough”. So the weights and logits tend to keep growing, which is one reason networks become over-confident.
Label smoothing replaces the one-hot target over classes by
a mix of the one-hot vector and the uniform distribution (P1.E2). The true class gets and every other class . Szegedy et al. introduced it for the Inception-v3 image network (arXiv 2015, CVPR 2016).
A worked example, and . The numbers are those of P1.E2, with the formula of P1.E3. The target becomes for the true class and for each of the nine others. Its entropy is bits, which is nats (P1.E2 uses bits, the training loss uses nats). A one-hot label has entropy .
Now the training loss, with the model’s probabilities :
- The best the model can do is . The loss is then the entropy of the target, nats, and the gradient with respect to the logits, (P4.6), is exactly . Training has a place to stop.
- That place needs a finite logit gap. The true class needs more than each other class. With a one-hot target the loss only reaches as the gap goes to infinity.
- Being sure is now penalized. Suppose the model gives the true class and spreads the remaining equally. The one-hot loss is , which is small. The smoothed loss is , higher than the best value of , and the gradient on the true class is : it pushes the confidence back down.
For and the target becomes , the example in P3.A8.
One convention to check. PyTorch’s CrossEntropyLoss(label_smoothing=ε) uses exactly this form: is spread over all classes, including the true one. The PyTorch docs describe it as a mixture of the original target and a uniform distribution. Some other write-ups spread over the wrong classes only, which gives different numbers for the same , so check the definition before you compare values. The value is a common choice, not a rule.
What it does, and what it does not. Label smoothing often gives less over-confident probabilities. Müller, Kornblith and Hinton (NeurIPS 2019) report better calibration (P3.A10) on several tasks as well as better generalization, and also that a teacher trained with smoothing teaches a student worse in knowledge distillation (P10.F2). Results depend on the task, so it is a tool to try, not a promise. It is not a prior on the weights (P1.D11), because it changes the targets and not the parameters. And if the labels are really wrong, as in our noisy task, smoothing softens the damage but does not know which labels are wrong.
Other ways to hold a network back
- Data augmentation adds fresh, slightly changed copies of the training data (flips, crops, noise), so the network cannot memorize one fixed picture. It is often very effective for images, and P4.18 covers it.
- Noise injection adds small random noise to inputs or activations. Dropout is one kind of multiplicative noise on activations.
- A smaller network, or more data. Fewer parameters limit what can be fitted, and more data is the best regularizer when it is available.
- Max-norm constraints cap the length of each unit’s weight vector. This is a projection (P1.F7), and Srivastava et al. used it together with dropout.
Which to use?
There is no single recipe, but these habits are common starting points, not rules:
- Always keep a validation set and watch the two curves. That is the only way to know whether you have a problem (P4.22).
- AdamW with a small weight decay is a common default for transformers and for many other models.
- Early stopping is cheap, so a saved best checkpoint is almost free insurance.
- Dropout is worth trying when a smaller network overfits. When the training set is large, try little or none.
- Label smoothing is worth trying for classification with many classes, and it needs only one number.
- They interact. Dropout slows training, and weight decay and the learning rate (P4.14) work together, so change one thing at a time. Each has its own strength to tune.
Intuition
An overfit network is a student who memorized the practice exam. Weight decay makes memorizing expensive, because big weights cost something. Dropout makes the student study with a random half of the notebook missing each day, so no single page can carry the answer. Early stopping takes the exam as soon as the practice-test score stops improving. Label smoothing stops the student from being certain when the answer key itself is sometimes wrong.
The analogy breaks in one place: a real student can tell when a question is hard. A network treats every training label as equally true, including the wrong ones, and only these tricks stop it.
Math
- Weight decay: ; gradient step gives . Adam: decoupled form (P4.13).
- Inverted dropout: with independent . and .
- Backward through dropout: .
- Evaluation: .
- Number of masks: for units.
- Label smoothing: . For softmax with cross-entropy, . The minimum is at , a logit gap of ( for , ).
- Early stopping: keep at , stop when no new minimum for the patience.
Code
The program below shows dropout in train and eval mode, checks that the built-in label smoothing equals the formula, and builds the two weight-decay groups (weights decayed, biases not). Run locally with PyTorch 2.9.1; the dropout masks are random, so your zeros will fall in other places.
import torch
from torch import nn
torch.manual_seed(0)
drop = nn.Dropout(p=0.5) # p is the DROP probability
x = torch.ones(1, 8)
drop.train()
print("train:", drop(x))
print("train:", drop(x)) # a fresh mask on every call
drop.eval()
print("eval: ", drop(x)) # identity
# the scale 1/(1-p): average over many masks
drop.train()
big = torch.ones(100000)
print("mean:", round(drop(big).mean().item(), 3))
# label smoothing: the built-in equals the formula
z = torch.tensor([[2.0, 0.5, -1.0]])
y = torch.tensor([0])
for eps in (0.0, 0.1):
loss = nn.CrossEntropyLoss(label_smoothing=eps)(z, y)
print(f"eps={eps}: {loss.item():.4f}")
t = torch.tensor([[0.9 + 0.1 / 3, 0.1 / 3, 0.1 / 3]])
print("by hand:", round(-(t * torch.log_softmax(z, 1)).sum().item(), 4))
# which parameters get weight decay: weight matrices only
model = nn.Sequential(nn.Linear(10, 64), nn.ReLU(), nn.Linear(64, 1))
decay = [p for p in model.parameters() if p.ndim >= 2]
no_decay = [p for p in model.parameters() if p.ndim < 2]
opt = torch.optim.AdamW(
[{"params": decay, "weight_decay": 0.1},
{"params": no_decay, "weight_decay": 0.0}], lr=1e-3)
print([g["weight_decay"] for g in opt.param_groups],
[sum(p.numel() for p in g["params"]) for g in opt.param_groups])train: tensor([[0., 0., 2., 0., 0., 0., 2., 2.]])
train: tensor([[0., 2., 2., 2., 2., 0., 2., 2.]])
eval: tensor([[1., 1., 1., 1., 1., 1., 1., 1.]])
mean: 0.998
eps=0.0: 0.2413
eps=0.1: 0.3913
by hand: 0.3913
[0.1, 0.0] [704, 65]The first two lines are two different masks for the same input: the kept entries become . In eval mode the layer returns the input. The mean over units is close to , as inverted dropout promises. The two losses and are with and without smoothing, and the hand-made target gives the same . The last line shows the two decay values and the group sizes: weights () get decay , and the biases () get none.
Check your understanding
A layer uses inverted dropout with drop probability . By what number is each kept output multiplied during training?
Kept outputs are divided by the keep probability , which is a factor of . Multiplying by would shrink the average output further, is the drop probability itself, and would be .
What does an
nn.Dropoutlayer do aftermodel.eval()has been called?In evaluation mode all units are used and nothing is scaled, because the scaling by was already done in training. A smaller probability, a fixed mask and a multiplication by the keep probability all describe other schemes (the original paper scaled the weights at test time instead).
Which statement about the two meanings of in dropout is correct?
In PyTorch is the chance that an element is zeroed, so drops about of the units. The 2014 JMLR paper used for the retain probability. The two meanings agree only when .
Training with early stopping ends because the validation loss has not improved for the patience. Which weights should the final model use?
The weights at the final step come after the patience window, in which the validation loss was already no better, so they are usually a little overfit. Step 1 has not learned anything yet, and averaging every step would include those bad early weights.
With classes and , label smoothing in the form gives the true class which target value?
The true class gets , and each of the four others gets . The value forgets the share of the uniform mix that the true class also receives, would be , which is not what the formula gives, and is the unsmoothed target.
Exercises
- A weight is and its loss gradient is at this step. With weight decay and learning rate in plain SGD, what is the weight after one step?
Show answer
The factor is , so the weight becomes . - A unit outputs and the drop probability is . What does the unit send in training when it is kept and when it is dropped? What are the expected value and the variance of what it sends?
Show answer
Kept: . Dropped: . The expected value is , and the variance is , which is . A simulation with a million masks gives about and . - A layer has units and . How many units are dropped at one step on average, and what is the standard deviation of that count?
Show answer
The count is the sum of independent Bernoulli variables with probability (P1.D3), so its mean is and its standard deviation . - Four classes and . Write the smoothed target for true class . What is the cross-entropy loss if the model outputs , and what would it be with the one-hot target?
Show answer
The target is , from and . The smoothed loss is , which is . The one-hot loss is . - The validation losses after epochs to are , , , , , , , . With patience , after which epoch does early stopping stop, and which epoch’s weights are kept?
Show answer
The lowest loss, , is at epoch 4. Epochs 5, 6 and 7 are not better, so that is three checks in a row and training stops after epoch 7. The weights from epoch 4 are loaded.
Next: P4.18 covers data augmentation, the other main tool against overfitting. P4.19 covers normalization layers, which also behave differently in training and evaluation, and P4.22 puts the curves from this lesson into a training and debugging recipe.