Learning path: Deep Learning for Production: Transformers, Fine-Tuning and Serving · Step 1 of 13
Dropout, Early Stopping and Batch Norm: Judge Each One by the Validation Curve
Three tools that keep a network honest on unseen data, each judged by its validation curve on 150 digit images: early stopping with patience 5, nn.Dropout(0.5), nn.BatchNorm1d, and the batch norm trap that drops a frozen model from 95.8% to 33.6%.
What you will learn
- Add early stopping with a patience counter and load the best weights back
- Add nn.Dropout and see why model.train() and model.eval() matter
- Add nn.BatchNorm1d and read what it does to training and validation loss
- Avoid the batch norm trap: a frozen encoder that changes in train mode
Before you start
- The Same Network in PyTorch
- The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
Think about coaching a team. One star player gets every pass. On the day she's out, the team falls apart. So in practice you bench players at random, and now nobody can lean on one star. That's dropout. You also watch the practice matches, and when the results stop improving, you end the session. That's early stopping. And before each play, everyone settles into the same steady pace. That's batch norm, more or less.
Three habits, one goal: a network that does well on data it hasn't seen. Training loss always looks good, so we judge each tool by one thing only, its validation curve. The test set stays locked away for the final score.
The problem: training falls, validation turns
The setup: a pretrained ResNet-18 from Hugging Face turns each image into 512 features, and a single nn.Linear layer (the head) sits on top. The data is scikit-learn's load_digits: 1,797 small handwritten digits, resized to 128x128 and split 60/20/20 into 1,078 train, 359 validation and 360 test images. To make overfitting easy to see, the head trains on only 150 of the training images.
Train loss starts at 2.48 and keeps falling, all the way down near 0.0001. Validation loss falls too, to 0.626 at epoch 5. After that it turns around and climbs while train loss is still falling. The model is memorising those 150 images. That gap is what we're fighting, and validation is how we see it.
Early stopping: let validation decide when to quit
Here's the fit function from train.py. Every epoch it trains once and measures the validation loss.
import copy
import torch
from torch import nn
def fit(head, tr, va, epochs=200, patience=None,
lr=0.01):
torch.manual_seed(0)
opt = torch.optim.Adam(head.parameters(), lr=lr)
loss_fn = nn.CrossEntropyLoss()
hist, best, best_state, bad = [], 1e9, None, 0
for ep in range(1, epochs + 1):
head.train()
opt.zero_grad()
loss = loss_fn(head(tr[0]), tr[1])
loss.backward()
opt.step()
with torch.no_grad():
vl = loss_fn(head(va[0]), va[1]).item()
hist.append((ep, loss.item(), vl))
if vl < best:
best, bad = vl, 0
best_state = copy.deepcopy(head.state_dict())
else:
bad += 1
if patience and bad >= patience:
break
if patience:
head.load_state_dict(best_state)
return hist
Three moves make it work:
- A new best? If
vlbeats the best so far, reset the counter and copy the weights somewhere safe withcopy.deepcopy. At epoch 5, 0.626 lands there. - Not better? The counter
badgoes up by one. - Out of patience? When
badreachespatience, break out of the loop and load the safe weights back.
These are the ten epochs the run actually took with patience=5:
| Epoch | Validation loss | Counter |
|---|---|---|
| 1 | 1.314 | 0 (new best) |
| 2 | 0.854 | 0 (new best) |
| 3 | 0.697 | 0 (new best) |
| 4 | 0.641 | 0 (new best) |
| 5 | 0.626 | 0 (best, weights saved) |
| 6 | 0.627 | 1 |
| 7 | 0.636 | 2 |
| 8 | 0.648 | 3 |
| 9 | 0.661 | 4 |
| 10 | 0.675 | 5, stop |
The model we keep is the one from epoch 5, not the one from epoch 10.
Did stopping help?
h1 = make_head()
log1 = fit(h1, sub, (f[va], y[va]), lr=0.01)
h2 = make_head()
log2 = fit(h2, sub, (f[va], y[va]), lr=0.01, patience=5)
no stopping: epochs 200 best val epoch 5 test acc 0.8194
patience 5: epochs 10 test acc 0.8194
Exactly the same test accuracy, 0.8194. Early stopping bought no accuracy here, and it's worth being straight about that. What it did buy is 10 epochs instead of 200, and a kept validation loss of 0.626 instead of 0.804. It saved time and kept the lower loss. It didn't make the model smarter.
Dropout: bench half the numbers at random
The pretrained ResNet has no dropout layers, so compare_curves.py uses a tiny network on the raw 8x8 pixels (64 inputs) and the same 150 training images. It builds three versions that differ by one line:
import torch
from torch import nn
def net(kind):
mid = {"plain": [],
"dropout": [nn.Dropout(0.5)],
"batch norm": [nn.BatchNorm1d(128)]}[kind]
return nn.Sequential(nn.Linear(64, 128), *mid,
nn.ReLU(), nn.Linear(128, 10))
nn.Dropout(0.5) means that on every training step, about half of the 128 numbers coming out of the first layer are switched off at random, a different half each time. No single unit can become the star.
The training loop switches it on and off:
for ep in range(1, epochs + 1):
model.train()
opt.zero_grad()
loss = loss_fn(model(x[tr]), y[tr])
loss.backward()
opt.step()
model.eval()
with torch.no_grad():
vl = loss_fn(model(x[va]), y[va]).item()
hist.append((ep, loss.item(), vl))
model.train() turns dropout on. model.eval() turns it off, so validation always sees the whole network. Forget eval() and your validation numbers come from a half-benched team.
plain: best val 0.340 at epoch 26, final val 0.486, test acc 0.9083
dropout: best val 0.303 at epoch 53, final val 0.367, test acc 0.9194
The plain network reaches its best validation loss, 0.340, at epoch 26 and then climbs to 0.486. With dropout, the best is 0.303 at epoch 53, and it ends at 0.367. Test accuracy moves from 0.9083 to 0.9194. That's only 4 more images right out of 360, on one seed, so don't lean on it. The clearer change is the curve: it climbs less.
Batch norm: a steady range
Inside a network, numbers can drift to all sorts of ranges, and that makes learning harder. A batch norm layer rescales them using a mean and a spread, so the next layer always gets a steady range. In our tiny network it's the one line nn.BatchNorm1d(128).
batch norm: best val 0.353 at epoch 24, final val 0.369, test acc 0.9250
Look at training first. At epoch 10, train loss is 0.108 with batch norm against 0.767 without it, so it learns the training set much faster. Validation is less neat. Its best, 0.353, is a touch worse than plain's 0.340. But it stays close to that and ends at 0.369, where plain climbed to 0.486. Test accuracy is 0.9250, 6 images more than plain.
One run, one small dataset. What we can honestly say is that both curves stayed flatter. Neither is a promise of a better test score every time.
The batch norm trap
Batch norm behaves differently in training and in evaluation:
- In eval mode it uses a stored mean and spread, one fixed reference.
- In train mode it uses the mean of the current batch, and it nudges the stored values too.
Back to the pretrained ResNet. Here's how model.py loads and uses it:
import torch
from torch import nn
from transformers import ResNetModel
NAME = "microsoft/resnet-18"
def load_encoder():
enc = ResNetModel.from_pretrained(NAME)
for p in enc.parameters():
p.requires_grad = False
return enc
def embed(enc, x, train_mode=False):
enc.train(train_mode)
with torch.no_grad():
out = enc(pixel_values=x).pooler_output
return out.flatten(1)
Every parameter has requires_grad = False. The run confirms it:
encoder params: 11176512 trainable: 0
11,176,512 parameters, zero trainable. So nothing can change, right? This time the head is trained on all 1,078 training images. Then we run the same images through the encoder with train_mode=True, in batches of 32:
frozen head test acc: 0.9583
BN stats drift, train mode: 1.3876
same images, max embedding gap: 15.1972
head acc, encoder in train mode: 0.3361
One flag, and accuracy falls from 0.9583 to 0.3361. No error, no warning. The first batch norm layer's stored mean moved by up to 1.39, and the same images now come out with features up to 15.2 apart.
The reason: the stored mean (running_mean) is a buffer, not a parameter. requires_grad = False only freezes parameters, so it never touches it. Freezing a model with batch norm takes two switches: requires_grad = False and eval().
Common mistakes
- Judging by training loss. It falls for every model. Only the validation curve tells you about unseen data.
- Stopping without loading the best weights back. Without
load_state_dict(best_state)you keep the last epoch, which is alreadypatienceepochs past the best. - Forgetting
model.eval()before validation or prediction. Dropout stays on and batch norm keeps using batch statistics. - Thinking
requires_grad = Falsefreezes everything. Batch norm's running mean and variance still move in train mode. - Reading a 4-image gain as proof. One seed on 360 test images can't separate two methods that close.
Quick recap
| Tool | What it does | What it did here |
|---|---|---|
| Early stopping | Quits when validation stops improving, loads the best weights back | Same 0.8194 accuracy in 10 epochs instead of 200 |
nn.Dropout(0.5) | Switches off about half the units at random in training | Validation ended at 0.367 instead of 0.486 |
nn.BatchNorm1d | Rescales values to a steady range | Train loss 0.108 vs 0.767 at epoch 10; validation ended at 0.369 |
eval() | Turns dropout off, makes batch norm use stored stats | Without it, a frozen encoder fell from 0.9583 to 0.3361 |
Try it yourself
In compare_curves.py, change nn.Dropout(0.5) to nn.Dropout(0.2) and run it again. Does the validation curve climb more or less than with 0.5? Next, see how a frozen pretrained model and a small head become a full method in Transfer Learning on Images.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Why Neural Networks: Pixels, One Neuron and Layers
Why pictures need neural networks: a handwritten digit is 784 numbers, one neuron is a weighted sum plus a bias and one small rule, and neurons stack into layers. Worked out on MNIST with NumPy.
The Forward Pass and Activation Functions: ReLU, Sigmoid, Tanh and Softmax
Follow numbers through a tiny 3-2-3 network in NumPy: one matrix product per layer, ReLU inside, softmax at the end, and a count of every weight and bias.
Loss and Backpropagation: How Wrong, and Who Is to Blame
The loss says how wrong the network was; backpropagation says how much each weight is to blame. MSE and cross-entropy, the chain rule by hand on a two-weight chain, then the same gradients from PyTorch autograd.
The Training Loop: Epochs, Mini-Batches, Learning Rate and Optimisers
How training is organised: shuffle, cut into mini-batches, take one step per batch, repeat per epoch. Real MNIST runs compare three learning rates, SGD against Adam, and show the overfitting signal in the validation loss.