Sub topic 12
Recognizing and Reducing Overfitting
This chapter assumes you can build PyTorch DataLoader objects and understand epochs, loss, and gradient descent. You also need a training loop that reports metrics on both the training and validation sets.
What overfitting looks like
Overfitting happens when a model learns details that are specific to the training images instead of learning patterns that generalize to new images. The model may memorize backgrounds, camera artifacts, or individual objects.
A common sign is a growing gap between training and validation performance:
| Pattern | Likely meaning |
|---|---|
| Training loss decreases while validation loss increases | The model is overfitting |
| Both losses remain high | The model may be underfitting |
| Training and validation metrics are similar but poor | The features, data, or model may be unsuitable |
Accuracy alone can hide the problem. Cross-entropy loss often reveals overfitting earlier. A model can keep improving its training accuracy while becoming less reliable on unseen images.
Use a validation set during development, but keep the test set untouched until you have finished choosing the model and training settings. Looking at test results repeatedly turns the test set into another validation set.
Find the best checkpoint
Save the model whenever validation loss improves. This process is called early stopping when you stop training after validation performance fails to improve for several epochs.
import copy
import torch
best_val_loss = float("inf")
best_state = None
epochs_without_improvement = 0
patience = 3
for epoch in range(30):
train_loss, train_acc = run_epoch(
model, train_loader, criterion, device, optimizer
)
val_loss, val_acc = run_epoch(
model, val_loader, criterion, device
)
if val_loss < best_val_loss:
best_val_loss = val_loss
best_state = copy.deepcopy(model.state_dict())
epochs_without_improvement = 0
else:
epochs_without_improvement += 1
print(
f"epoch {epoch + 1}: "
f"train loss {train_loss:.3f}, "
f"val loss {val_loss:.3f}"
)
if epochs_without_improvement >= patience:
print("stopping early")
break
if best_state is not None:
model.load_state_dict(best_state)The deepcopy matters. Without it, later training can change the saved parameters because a state dictionary contains references to tensors.
Choose a remedy
Start with the least disruptive remedy. Make sure the validation split is sound before changing the model.
- Add realistic augmentation, such as crops, horizontal flips, or small rotations. Do not use transformations that change the class.
- Add weight decay. It discourages unnecessarily large weights.
- Reduce the learning rate when fine-tuning the backbone.
- Unfreeze fewer layers, or train the classification head for more epochs before unfreezing.
- Collect more varied images.
- Reduce the model size if the dataset is very small.
- Stop at the best validation checkpoint.
A pretrained backbone is already a useful regularizer because it begins with general visual features. However, unfreezing too many layers with a large learning rate can quickly damage those features.
Exercise
Exercise
Training accuracy reaches 99%, but validation accuracy stays near 70% and validation loss rises for four epochs. Name two actions you would take before evaluating on the test set.
Show answer
Check for leakage or an unrepresentative split, then restore the best validation checkpoint and try stronger realistic augmentation, weight decay, or less fine-tuning.