Sub topic 12
Recognizing and reducing overfitting
This chapter assumes you have trained the frozen-backbone and fine-tuned classifier from the earlier chapters. You should know PyTorch's train() and eval() modes, the run_epoch helper, and how to read accuracy and loss. Here you learn to spot overfitting in your training logs, tell it apart from similar problems, and choose a remedy.
What overfitting looks like
A model overfits when it learns details of the training images that do not carry over to new images. It may memorize a particular background, a watermark, or the exact pixels of a photo. Training metrics keep improving while validation metrics stall or get worse.
The signal is the gap between the two curves, not either curve alone. Validation loss usually turns upward before validation accuracy drops. Loss penalizes confident wrong answers, so it reacts first.
The best checkpoint is the one at the validation minimum, not the last one.
Telling it apart from other problems
Use the pattern of the two metrics to decide what is wrong before you change anything.
| Pattern | Likely cause | First thing to try |
|---|---|---|
| Train and validation both low and flat | Underfitting: learning rate too low, head too frozen, or a bug | Raise the learning rate, unfreeze `layer4`, check labels |
| Train high, validation much lower, validation loss rising | Overfitting | Stop earlier, add regularization or augmentation |
| Validation higher than train from the start | Training-time augmentation and dropout make training harder, which is normal | Compare again in a later epoch |
| Validation near-perfect, test poor | Leakage between train and validation | Check for duplicate or near-duplicate images |
| Validation accuracy jumps around between epochs | Validation set too small or too noisy | Use more validation images, average over epochs |
Overfitting is common when you fine-tune on a few hundred images per class. A ResNet-18 has about 11 million parameters, and even a frozen backbone feeds the head 512 features per image. Once you unfreeze layer4, the number of trainable parameters grows by orders of magnitude, so the risk grows with it.
Record history and keep the best checkpoint
You cannot recognize a trend you did not record. Store each epoch's metrics and keep a copy of the weights from the best validation epoch. This loop reuses run_epoch, model, criterion, optimizer, train_loader, val_loader, and device from the previous chapters. It adds early stopping, which ends training after patience epochs without improvement.
import copy
def fit(model, train_loader, val_loader, criterion, optimizer, device,
max_epochs=30, patience=4):
history = []
best_loss = float("inf")
best_state = copy.deepcopy(model.state_dict())
best_epoch = 0
stale = 0
for epoch in range(1, max_epochs + 1):
train_loss, train_acc = run_epoch(model, train_loader, criterion, device, optimizer)
val_loss, val_acc = run_epoch(model, val_loader, criterion, device)
history.append((epoch, train_loss, train_acc, val_loss, val_acc))
print(f"epoch {epoch}: train {train_loss:.3f}/{train_acc:.3f} "
f"val {val_loss:.3f}/{val_acc:.3f}")
if val_loss < best_loss:
best_loss, best_epoch, stale = val_loss, epoch, 0
best_state = copy.deepcopy(model.state_dict())
else:
stale += 1
if stale >= patience:
print(f"early stop; best epoch was {best_epoch}")
break
model.load_state_dict(best_state)
return history, best_epochUse copy.deepcopy. state_dict() returns references to the live tensors, so without the copy your "best" weights would keep changing as training continues.
Monitor validation loss rather than accuracy when you pick the best epoch. On a small validation set, accuracy moves in coarse steps, and loss is smoother.
The checkpoint choice uses the validation set, so the validation score is now slightly optimistic. Report the final number from the test split, which you evaluate once, at the end.
Remedies, in the order to try them
1. Check for data leakage first
If the same photo, or a resized copy, sits in both train and validation, the model gets credit for memorizing. That looks like excellent generalization and hides real overfitting. This script finds byte-identical files across splits.
import hashlib
from pathlib import Path
def file_hashes(root):
hashes = {}
for path in Path(root).rglob("*"):
if path.suffix.lower() in {".jpg", ".jpeg", ".png"}:
digest = hashlib.md5(path.read_bytes()).hexdigest()
hashes.setdefault(digest, []).append(path)
return hashes
train_h = file_hashes("data/train")
val_h = file_hashes("data/val")
shared = set(train_h) & set(val_h)
print(f"{len(shared)} identical files appear in both splits")
for digest in list(shared)[:10]:
print(train_h[digest][0], "<->", val_h[digest][0])Hashing catches only exact copies. Burst-mode photos and re-encoded JPEGs of the same scene slip through. If your images come from videos or photo sessions, split by session or source, not by individual file.
2. Get more variety from the data
Stronger augmentation is often the cheapest fix because it works on the data and leaves the model alone. Add ColorJitter or RandomRotation to the training transforms. Apply it only to the training pipeline. Validation keeps its deterministic resize and center crop, as in the earlier chapter. Choose augmentations that match real variation. A vertical flip makes sense for aerial photos but not for street scenes.
More labeled images beat any trick, especially for the classes with the lowest per-class accuracy.
3. Regularize the head
Dropout randomly zeroes a fraction of features during training, which stops the head from relying on any one feature. Weight decay shrinks weights toward zero. Label smoothing lowers the target for the correct class slightly, so the model stops pushing its confidence toward 100% on training images.
import torch
import torch.nn as nn
model.fc = nn.Sequential(
nn.Dropout(p=0.3),
nn.Linear(model.fc.in_features, num_classes),
)
model = model.to(device)
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)
optimizer = torch.optim.AdamW(model.fc.parameters(), lr=1e-3, weight_decay=1e-2)Two consequences to remember:
- The head's saved keys change from
fc.weighttofc.1.weight. When you load the checkpoint for inference, build the sameSequentialhead first. - With label smoothing, loss values are not comparable with runs that used plain cross-entropy. Compare runs only when they use the same criterion.
4. Reduce how much can adapt
A model can overfit because too much of it is trainable. Options, from least to most drastic:
- Lower the learning rate for the unfrozen backbone layers, for example
1e-5instead of1e-4. - Unfreeze fewer layers, and go back to training only the head.
- Pick a smaller architecture.
If a fine-tuned layer4 gives validation loss that is no better than the frozen-backbone run, the extra capacity is not helping, and you should keep the simpler model.
5. Stop earlier
Early stopping, shown above, is a form of regularization. It costs nothing and often accounts for most of the achievable improvement.
A gotcha: frozen batch norm still changes
ResNet contains BatchNorm layers. Setting requires_grad = False stops their weights from receiving gradients, but model.train() still updates their running mean and variance from your small dataset. Those statistics drift away from the ImageNet values the frozen layers were tuned for. This can hurt validation accuracy in a way that looks like overfitting.
To keep frozen BatchNorm layers fixed, put them back in eval mode after each call to model.train().
import torch.nn as nn
def freeze_batchnorm_stats(model):
for module in model.modules():
if isinstance(module, nn.BatchNorm2d):
module.eval()Call freeze_batchnorm_stats(model) right after model.train() at the start of each training epoch. In the run_epoch helper, add the call inside the if training: path before the loop. Try it as an experiment. It can help with very small datasets and makes no difference on larger ones.
A practical routine
- Train the head with the backbone frozen and record the history.
- Compare the final train and validation numbers. A gap under a few points is fine.
- If the gap is large and validation loss is rising, run the hash check, then add augmentation and the head regularization above.
- Change one thing at a time and keep the history of each run, so you can tell which change helped.
- Evaluate the chosen model once on the test split.
Exercise
After 10 epochs of fine-tuning, your log shows train accuracy 0.99 and validation accuracy 0.78. Validation loss was lowest at epoch 3 and has risen since. A hash check finds no duplicates between train and validation. Name two changes you would make, and say which checkpoint you would keep.
Show answer
Keep the checkpoint from epoch 3, the validation-loss minimum, and use early stopping with a patience of a few epochs so it is selected automatically. Then reduce overfitting with two of these: stronger training-only augmentation, dropout in the head, weight decay, label smoothing, a lower backbone learning rate, or unfreezing fewer layers. Change one at a time and compare histories.
Exercise
You add nn.Dropout before the final linear layer, train, and save only state_dict(). At inference, loading the checkpoint into a model whose head is a plain nn.Linear fails. Why, and how do you fix it?
Show answer
The dropout head is an nn.Sequential, so its saved keys are fc.1.weight and fc.1.bias, while a plain nn.Linear expects fc.weight and fc.bias. Rebuild the same nn.Sequential(nn.Dropout(...), nn.Linear(...)) head before calling load_state_dict.