Module 6 · Training well: optimisers, overfitting, regularisation and augmentation
Time: about 6 hours with readings · Lab: python course/labs/lab06_training_dynamics.py
You need: Module 2 §5 (gradient descent and the learning rate), Module 2 §9 (mean and standard deviation) and Module 5 (a two-layer network and mini-batch training).
By the end you can:
- choose a learning rate sensibly and recognise when training is diverging or crawling;
- explain what Adam does differently from plain gradient descent;
- diagnose underfitting vs overfitting from training and validation curves;
- explain weight decay, dropout, early stopping and data augmentation, and when each helps;
- read TrayCheck's own training history and explain every setting in
vision_train.py.
Why this matters in TrayCheck
Every training choice in vision_train.py comes from this module:
Setting in vision_train.py |
Concept |
|---|---|
tf.keras.optimizers.Adam(5e-4), later Adam(1e-5) |
Optimiser and learning rate |
RandomFlip("horizontal"), RandomRotation(.05) |
Data augmentation |
Dropout(.25) |
Regularisation |
EarlyStopping(monitor="val_loss", patience=3, restore_best_weights=True) |
Early stopping |
batch_size=32, epochs=12 then 6 |
Mini-batch training budget |
About the lab: for speed, Lab 6 runs its experiments on scikit-learn's handwritten-digits dataset (small 8 × 8 images of the digits 0–9) with the small network you build by hand in Lab 5, not on food photos. Each experiment changes one thing, so the effect is easy to see; the lessons carry over to TrayCheck directly.
Why this matters for the internship
You won't train the vendor's model, but you may be shown its training results, and this module is what lets you read them:
- Overfitting has an operational meaning. A model that scores far better on its training data than on held-out data has partly memorised its training examples, for example the trays, crockery and lighting of the sites it was trained on. Expect it to do worse at a new hospital.
- Ask for the validation and test numbers, not the training numbers. Training accuracy says almost nothing about how the model will perform on your trays (Module 1 §7).
- Augmentation tells you what variation the model was prepared for. If the vendor's training used no rotations or lighting changes, a different camera angle or lighting on your wards is a risk to test for in UAT.
1. Learning rates
The learning rate is the single most important setting. Lab 6 trains the same network for 20 epochs at five learning rates:
lr 0.001 final train loss 2.0653 val acc 0.287 ← barely moved
lr 0.01 final train loss 0.7578 val acc 0.889
lr 0.1 final train loss 0.1085 val acc 0.967
lr 1.0 final train loss 0.0060 val acc 0.986 ← best here
lr 5.0 final train loss 2.3714 val acc 0.100 ← diverged: back to guessing
Module 2 §5 showed why on a single parameter: each step multiplies the distance to the best value by (1 − 2 × learning rate), so past a certain size the steps overshoot by more each time. The best value depends on the model, data and optimiser, so you find it by experiment on validation data. A useful habit: start from a known-good default for your optimiser (3 × 10⁻⁴ is a common starting point for Adam), then search on a log scale (0.0001, 0.001, 0.01…), not by adding 0.01, because what matters is the factor by which you change it.
Momentum and Adam
Plain SGD steps straight down the current gradient, g. Two refinements power almost all modern training.
Momentum steps along a running total of recent gradients instead of the current one alone:
Each step, the old total v shrinks to 90% and the new gradient is added, so older gradients fade out gradually. Watch what that does in two situations, starting from v = 0:
| Step | 1 | 2 | 3 | 4 | 5 | … | 10 |
|---|---|---|---|---|---|---|---|
| Steady gradient (+1 every step): v | 1.0 | 1.9 | 2.71 | 3.44 | 4.10 | … | 6.51 |
| Zig-zag gradient (+1, −1, +1…): v | 1.0 | −0.1 | 0.91 | −0.18 | 0.84 | … | −0.34 |
When the gradient keeps pointing the same way (a long, gentle slope), v builds up and the steps grow towards 10 times the plain step: training accelerates. When it flips back and forth (a narrow valley, where plain gradient descent bounces from wall to wall), the contributions cancel and v stays small: the zig-zag is damped. Like a heavy ball rolling downhill, it keeps going in consistent directions and ignores jitter.
Adam combines momentum with a separate step size for every parameter. It keeps two running averages per parameter: m, the average gradient (the momentum part), and s, the average squared gradient (how large this parameter's gradients typically are). Its step is
(plus a tiny constant to avoid dividing by zero, and a correction for the first few steps when the averages are still near their starting value of zero). Dividing by √s rescales each parameter's gradient to a typical size of about 1. Example: two parameters whose gradients are steadily 100 and 0.01. Plain gradient descent with η = 0.001 moves them by 0.1 and 0.00001 per step, a 10,000-fold difference, so no single learning rate suits both. Adam moves both by 0.001 per step. That is why Adam works well with little tuning across layers whose gradients differ in size, and why TrayCheck uses it.
Why two learning rates in TrayCheck? Stage 1 trains a brand-new head on top of a frozen backbone, so 5 × 10⁻⁴ is fine. Stage 2 unfreezes the last 20 backbone layers, whose ImageNet weights are already good. A large step would destroy them, so it drops 50× to 10⁻⁵. This "small learning rate for fine-tuning" rule is standard (Keras's transfer learning guide makes the same point).
2. Underfitting, overfitting and the generalisation gap
| Symptom | Diagnosis | Typical fixes |
|---|---|---|
| Training loss stays high | Underfitting: model too simple, or not trained enough | Bigger model, train longer, better learning rate |
| Training loss low, validation much worse | Overfitting: memorising training examples | More data, augmentation, regularisation, early stopping, smaller model |
| Both good and close | Healthy | Check the test set once, then stop tinkering |
Lab 6 forces overfitting with only 10 training images per digit and a 256-unit network:
epoch 50 train loss 0.1293 val loss 0.3582 train acc 1.000 val acc 0.914
epoch 300 train loss 0.0128 val loss 0.2655 train acc 1.000 val acc 0.914
Training loss ends 21x lower than validation loss, and train accuracy is 100%:
the network has memorised its 100 examples. That train-validation gap is overfitting.
Textbooks often draw a U-shaped validation curve that rises once overfitting starts. Here it mostly flattens. Both happen in practice, and what you always see is the gap.
The statistical framing is the bias–variance trade-off. Picture fitting a curve through noisy points. A straight line can't follow a genuinely curved pattern however much data you give it: its errors come from its built-in assumptions, called bias. A very wiggly curve can pass through every point, noise included; fit it to a different sample and it wiggles differently: its errors come from sensitivity to the particular sample, called variance. The best models sit between the two. (Very large neural networks complicate this classic picture, since they can fit training data perfectly and still generalise well, but the practical diagnosis above still holds: watch the gap.)
TrayCheck's own curves
From vision/training_history.json, stage 1 (new head, frozen backbone):
epoch 1 loss 1.4719 acc 0.380 val_loss 0.9135 val_acc 0.637
epoch 3 loss 0.4707 acc 0.845 val_loss 0.5298 val_acc 0.812
epoch 6 loss 0.2355 acc 0.935 val_loss 0.4751 val_acc 0.800 ← lowest validation loss
epoch 9 loss 0.1598 acc 0.950 val_loss 0.4896 val_acc 0.825 ← 3 epochs without improvement: stop
Early stopping (patience 3) stopped after epoch 9 and restored epoch 6's weights. Training accuracy (95%) is well above validation (80–84%), so there is a generalisation gap. Part of it is genuine overfitting. Part is that the validation photos come from Food-101's training split, whose labels are known to be noisy, while the test photos come from the hand-checked test split. That's one reason test accuracy (88.75%) ends up higher than validation (Module 9).
3. Regularisation: four tools
Weight decay (L2). Add a penalty to the loss: λ/2 times the sum of the squares of all the weights (written ½λ‖W‖²; λ, "lambda", sets its strength). The slope of ½λw² is λw, so on every step each weight is first shrunk by a small fraction of itself, hence "decay", before the ordinary gradient update. Why that helps: a model with large weights reacts sharply to tiny differences in its inputs, which is how it fits noise; keeping weights small keeps the learned function smooth. The penalty means a weight only grows large if it earns its place by reducing the main loss. In Lab 6 it gave the best result on the small dataset (val acc 0.928 vs 0.919).
Dropout. During training, randomly switch off (set to zero) each hidden unit with probability p (TrayCheck: 0.25), a fresh random choice at every step. Because any unit might vanish, the network can't rely on one unit or one fragile combination; it has to spread what it knows across many units, which tends to generalise better. Each step effectively trains a different thinned network, and the full network at prediction time behaves like an average of them. At prediction time dropout is switched off.
The survivors are scaled up by 1/(1 − p) to keep the next layer's input the same size on average. Example: four units each outputting 1.0, p = 0.25. On average 3 survive, summing to 3; scaled by 4/3 they sum to 4, the same as with all four on. Without the scaling, the next layer would see inputs a quarter smaller in training than at prediction time. In Lab 6 dropout 0.5 didn't help this tiny network (0.911). Regularisers are tools to test, not guaranteed wins.
Early stopping. Watch a validation metric and stop when it stops improving, keeping the best weights. What you watch matters:
watch val accuracy, patience 3 stop at epoch 10, keep epoch 7: val acc 0.950
watch val loss, patience 3 stop at epoch 40, keep epoch 37: val acc 0.978
watch val loss, patience 10 stop at epoch 60, keep epoch 58: val acc 0.983
Accuracy moves in coarse jumps (one more photo right or wrong), so it can trigger a stop too
early. Loss is smoother. TrayCheck watches val_loss.
Data augmentation. Train on randomly transformed copies of the data so the model learns to ignore those transformations. The lab shows the rule that matters most: augment for variation you will actually see.
centred val off-centre val
trained on 100 originals 0.914 0.379
trained on 100 + 400 shifted 0.903 0.799
Shifting doesn't help on centred digits (they're always centred), but it doubles accuracy on
off-centre ones. TrayCheck uses horizontal flips and rotations of up to ±18° (RandomRotation(.05)
means ±5% of a full turn), because a plate photographed from the other side or at a slight angle
is still the same dish. Vertical flips would be fine for food too. Flipping would be wrong for
digits (a mirrored "2" isn't a 2) or text. Augmentation layers are only active during training;
model.predict skips them.
Batch normalisation (preview)
MobileNetV2 contains 52 batch normalisation layers. Each one standardises the values
passing through it, exactly as Module 4 §1 standardised inputs (subtract the mean, divide by the
standard deviation), but inside the network and for every layer. During training it uses the
current batch's mean and variance; at prediction time it uses stored running averages (Module 7 §4
works an example). That stabilises and speeds up training. Fine-tuning with small
batches can corrupt those stored statistics, so TrayCheck keeps every BN layer frozen and calls
the backbone with training=False (Module 8).
A practical training recipe
Condensed from widely used practitioner advice (Karpathy's A Recipe for Training Neural Networks and Andrew Ng's course on improving deep networks, both in Go deeper):
- Look at the data first (Module 9).
- Get a simple baseline working end to end, with honest evaluation.
- Check the loss at initialisation (≈ log K).
- Overfit a single small batch to prove the model and training loop can learn.
- Then regularise: augmentation, dropout or weight decay, early stopping.
- Tune the learning rate on a log scale; change one thing at a time; keep notes.
- Evaluate on the test set once at the end.
Check your understanding
1. Training loss suddenly becomes NaN after a few epochs. What's the likeliest cause and fix?
The learning rate is too large: steps overshoot and values explode. Lower it by a factor of 10. (Lab 6's lr 5.0 run shows the same divergence.)
2. Why does TrayCheck use a 50× smaller learning rate in stage 2?
Stage 2 updates pre-trained backbone weights that already encode useful features. Large steps would destroy them ("catastrophic forgetting"), so fine-tuning uses small steps.
3. Training accuracy 95%, validation accuracy 82%. Underfitting or overfitting? Name two remedies.
Overfitting (a large generalisation gap). Remedies: more or more varied data (augmentation), stronger regularisation (dropout, weight decay), early stopping, or a smaller model. Also check whether validation labels are noisy, as they are in TrayCheck's case.
4. Would vertical flips be sensible augmentation for TrayCheck? For handwritten digits?
For food photographed from above, usually yes: an upside-down plate is still the same dish. For digits, no: flipping turns some digits into other symbols. Augment only with transformations that preserve the label.
5. Why can early stopping on validation accuracy stop too soon?
Accuracy changes in coarse steps and is noisy on small validation sets, so a few unlucky epochs can look like a plateau. Validation loss changes smoothly and reflects confidence, so it's a more reliable signal.
Go deeper
Short on time or new to this? The study guide says exactly which of these to read first.
Core
- Deep Learning (Goodfellow et al.), Chapter 7, Regularization for Deep Learning, especially 7.1 (parameter norm penalties), 7.4 (dataset augmentation), 7.8 (early stopping) and 7.12 (dropout); and Chapter 8, Optimization for Training Deep Models, especially 8.3 (SGD, momentum) and 8.5 (adaptive learning rates, including Adam).
- Understanding Deep Learning (Prince), Chapter 6, Fitting models, Chapter 8, Measuring performance (including double descent) and Chapter 9, Regularization.
- Andrej Karpathy, A Recipe for Training Neural Networks (2019).
Optional
- Dive into Deep Learning: Weight Decay, Dropout, and the Optimization Algorithms chapter (Minibatch Stochastic Gradient Descent, Momentum, Adam).
- Distill, Why Momentum Really Works (Goh, 2017): distill.pub/2017/momentum.
- DeepLearning.AI Deep Learning Specialization, Course 2: Improving Deep Neural Networks: Hyperparameter Tuning, Regularization and Optimization (Andrew Ng, Coursera).
- Papers: Kingma & Ba, Adam, ICLR 2015; Srivastava et al., Dropout, JMLR 2014; Ioffe & Szegedy, Batch Normalization, ICML 2015; Shorten & Khoshgoftaar, A survey on Image Data Augmentation for Deep Learning, Journal of Big Data 2019.
Interview angle
"I trained in two stages with Adam: first only the new head at 5e-4 with the backbone frozen, then the last 20 backbone layers at 1e-5, small enough not to wreck the pre-trained features. Regularisation is flips and small rotations, dropout 0.25 and early stopping on validation loss, which kept epoch 6's weights in stage 1. There's still a train–validation gap, partly because the validation labels come from Food-101's noisier training split."