Lesson 8 of 187 min
Dropout, weight decay and early stopping
A network with more neurons than it needs learns its own pictures, mistakes included; stop at the best epoch, switch off random neurons while it trains, or shrink every weight a little at every step.
After this lesson you can reduce overfitting in a network.
Loading the video…
Refreshers
An idea from an earlier lesson shows up here when the video leans on it.
In real code
What the video left out, as you will meet it in your own code.
Stop later and restore the best weights
Track how many epochs have passed since validation loss last improved. Save an independent copy of the checkpoint. The last epoch tells you when you stopped. The saved epoch tells you which weights to use. PyTorch’s checkpoint guide
from copy import deepcopy
import torch
from torch import nn
losses = [0.72, 0.54, 0.60, 0.62, 0.51, 0.65, 0.67]
model = nn.Linear(1, 1, bias=False)
def train_mock(epoch):
with torch.no_grad():
model.weight.fill_(epoch) # Identify each mock checkpoint.def stop_and_restore(losses, patience):
best_loss = float("inf")
for epoch, loss in enumerate(losses, start=1):
train_mock(epoch)
if loss < best_loss:
best_loss, best_epoch, best = loss, epoch, deepcopy(model.state_dict())
elif epoch - best_epoch >= patience:
break
model.load_state_dict(best)
return epoch, best_epoch, int(model.weight.item())print(stop_and_restore(losses, patience=2))(4, 2, 2)
Watch why dropout doubles the survivors
With dropout probability 0.5, each surviving input is doubled during training. Across many masks, the average stays near the original value. You can think of the masks as sampling many thinner networks with shared weights. In evaluation mode, dropout passes the input through. PyTorch’s Dropout reference
torch.manual_seed(0)
drop = nn.Dropout(0.5)
x = torch.ones(100_000)
training = drop(x)
drop.eval()
print(training.unique().tolist(), round(training.mean().item(), 2))
print(drop(x).unique().tolist())[0.0, 2.0] 1.0 [1.0]
Compare Adam's decay with AdamW's
With a zero data gradient, Adam's default weight decay still adds decay * weight to the gradient. Adam's running averages then affect the update. AdamW applies the shrink directly. PyTorch's Adam also exposes decoupled_weight_decay=True. Adam reference · AdamW reference
for optimizer in (torch.optim.Adam, torch.optim.AdamW):
weight = nn.Parameter(torch.tensor(0.5))
opt = optimizer([weight], lr=0.001, weight_decay=1.0)
weight.grad = torch.zeros_like(weight)
opt.step()
print(optimizer.__name__, f"{weight.item():.4f}")Adam 0.4990 AdamW 0.4995
Choose what to shrink
Pick strengths on a clean validation split, with the same split and seeds across trials. Keep a separate test split for your final score. Use parameter groups if the recipe leaves a bias or a normalization parameter out of decay. This linear layer gives its weight and bias different settings.
layer = nn.Linear(64, 256)
opt = torch.optim.AdamW([
{"params": [layer.weight], "weight_decay": 0.01},
{"params": [layer.bias], "weight_decay": 0.0},
], lr=0.001)
print([group["weight_decay"] for group in opt.param_groups])[0.01, 0.0]
Give the model more examples
More correctly labeled examples can help. For digits, a small shift can make a new training view without changing the label. Here one bright pixel moves right by one column, and the left edge is filled with zeros. Apply this to training images and leave the validation images unchanged.
digit = torch.zeros(8, 8)
digit[2, 3] = 1
shifted = torch.zeros_like(digit)
shifted[:, 1:] = digit[:, :-1]
print(torch.nonzero(digit).tolist(), torch.nonzero(shifted).tolist())[[2, 3]] [[2, 4]]
Run on Python 3.13.3 and PyTorch 2.15.0. Checked on .
Quiz
Two questions on this lesson, and one from earlier. Answer as often as you like.
1 of 3
From earlier: Overfitting and regularization
With the penalty at a strength of 1, degree nine misses its own 20 penguins by 262 grams and new ones by 394. At a strength of 1,000, by 842 and 768. What is wrong at 1,000?
2 of 3
You train for 200 epochs. The training loss keeps falling toward 0. The validation loss is lowest at epoch 65, then it climbs. Which weights do you keep?
3 of 3
You train with torch.optim.AdamW(model.parameters(), lr=0.01, weight_decay=0.5). Besides its usual step, what does a weight of 2 become at every step?
The ideas in this lesson
- Early stopping
- Check the validation loss each epoch, keep the weights from its lowest point, and stop once it has not improved for a while.
- Dropout
- While training, switch off a random share of the neurons at every step, so no single one is always there; at test, all are on.
- Weight decay
- At every step, shrink every weight a little towards 0, so a weight stays big only if many examples keep pushing it.
It leans on
Transcript
What the video says, part by part. Press a time to watch from there.
How to stop a network memorizing
Here's a challenge. We give a network pictures of numbers to learn from. Some of their labels are wrong, on purpose. By the end, it has learned the wrong ones too. So how do you stop a network from learning its mistakes?
A network made to overfit
Here's a network made to overfit, on purpose. It learns from five hundred pictures of digits... and about one label in four was changed to a wrong digit.
Real data has wrong labels too.
It has a hidden layer of two hundred and fifty-six neurons. That's far more than it needs.
It trains for two hundred epochs.
After each epoch, it's checked on the pictures set aside, with their right labels.
At epoch sixty-five... it gets about eighty-eight percent right.
After two hundred epochs, will it get more right, about the same, or fewer?
Two curves move apart
Watch the two losses. The loss on its own pictures stays higher at first, because a quarter of their labels are wrong. Then it falls, and falls, below the loss on the pictures set aside. That one falls until epoch sixty-five... then it turns and climbs.
After two hundred epochs, about seventy-seven percent right. A hundred and twenty-nine of its pictures have a wrong label. For a hundred and fourteen of them, it now gives back the wrong label. It's like a student who memorizes last year's answer key, mistakes and all. That's overfitting.
Stop at the best epoch
So why not just stop at the best epoch?
After each epoch, if the loss on the pictures set aside is the lowest yet, keep a copy of the weights. If the loss goes twenty epochs without a new low, stop and go back to the copy. Here it stops at epoch eighty-five, and keeps epoch sixty-five: about eighty-eight percent. That's early stopping.
Switch off random neurons
A network that trains too long learns its own pictures' mistakes.
Can we make memorizing harder in the first place? At every step of training, switch off a random half of the hidden neurons. Their output is zero for that step, and the next step switches off a different half. So no single neuron is always there.
One picture's answer can't sit in just a few of them... so the network has to learn what many pictures share. That's dropout.
Fewer mistakes learned
Trained with dropout, it learns seventy-eight of the hundred and twenty-nine wrong labels, not a hundred and fourteen. And at the end, it gets about eighty-four percent right.
At test, every neuron is on
So at test time, is half the network switched off? No. After model dot eval, the line that puts the network in test mode, every neuron is on.
Now see what goes wrong without it. We score the same three hundred and sixty pictures five times. The results range from seventy-seven to eighty-one percent. Dropout is still switching neurons off.
Shrink every weight a little
A network that memorizes its pictures, wrong labels included, needs big weights to do it. The Machine Learning course showed this: fitting each odd example takes big weights. Here, with no fix, the weights grew to almost three times their size before training.
Weight decay works at every step of training. On top of its usual step, every weight is multiplied by a number just under one. That number is one, minus the learning rate times the weight decay. Here, AdamW's learning rate is a thousandth, and the weight decay is one. So that number is zero point nine nine nine.
One is a strong setting, picked for this short run. So a weight of zero point five becomes...?
Just under zero point five. A little smaller, every step.
Big weights now cost
So a weight shrinks a little every step, unless many pictures keep pushing it up.
The weights stay near their size before training. It's Machine Learning's penalty on big weights, done by the optimizer at every step. Now it only learns fourteen wrong labels, and gets about eighty-nine percent right. One warning. Use AdamW. Plain Adam has a weight decay setting too, but Adam mixes it in with the slopes, so it acts differently. Give it a weight decay of one, and this network gets ten percent. That's about what you'd get by guessing.
They work together
Dropout and weight decay together: about ninety-one percent, and only eight wrong labels learned. Early stopping only adds a little here. Keeping the best weights improves the score a little.
And big language models? GPT-2 used dropout. A newer model, on the second card, doesn't use any. Weight decay is still on: OLMo 2, an open model, shrinks every weight at every step.
In code
In code, there are three changes. First, put a Dropout layer between the two layers. Second, hand the weights to AdamW, with its weight decay. And third... whenever the loss on the pictures set aside is the lowest yet, keep a copy of every weight. At the end, load the copy back. It keeps epoch one hundred and ninety-three. That's about ninety-two percent right, a little better than the last epoch.
Three fixes
So, keep the best epoch. Switch off random neurons while training, and none at test time. And shrink every weight a little at every step.
The lab
That's the end of this unit. In the lab, you make a network twenty layers deep that still learns, and keep it from learning wrong labels.
Make memorizing harder
Each fix makes the mistakes harder to learn. Now try it on this lesson's page, and take the quiz. Turn on dropout and early stopping, and see where it stops.
You use this lesson in Lab 3: A deep digit reader that doesn't memorize, which comes next.
Facts last checked on .
