Repository navigation
Module 10
⬅️ Module 09 · 🗺️ Curriculum · 🏠 Home · Module 11 ➡️
Level: Intermediate · Prerequisites: Modules 03, 06, 08 · Time: about 8–9 hours
On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading
A model that fits the training data perfectly may fail on new data. Generalisation is the central goal of learning; regularisation is any technique that improves it, and evaluation hygiene (proper splits, no leakage) is how we measure it honestly. This module covers penalties, stochastic regularisers, data augmentation, the bias–variance trade-off, double descent and learning-theory ideas.
After this module you should be able to:
- split data correctly and recognise leakage;
- derive the bias–variance decomposition and diagnose under/overfitting;
- derive L2 weight decay and L1 sparsity effects and a Bayesian interpretation;
- explain dropout, label smoothing, mixup/CutMix, augmentation, early stopping and ensembles;
- discuss capacity, VC dimension and why overparameterised networks can still generalise.
Memorising answers to practice questions is not the same as understanding the subject. We therefore split data into training (fit), validation (choose hyperparameters, stop early) and test (final, touched once). If training error is low but validation error is high the model overfits; if both are high it underfits.
flowchart LR
D["All data"] --> TR["Train: fit parameters"]
D --> VA["Validation: tune hyperparameters, early stopping"]
D --> TE["Test: report once"]
TR --> M["Model"]
VA --> M
M --> TE
Split before any preprocessing that uses statistics (scaling, imputation, feature selection, tokenizer training) and respect structure: split by patient/user/document/time, not by row, when examples are correlated; use time-ordered splits for forecasting. Leakage — information from validation/test entering training (duplicates, future data, target-derived features, normalisation fit on all data) — inflates scores and is among the most common causes of non-reproducible results. Use cross-validation for small datasets, with the same care.
Gap
For
Derivation: add and subtract

Figure 10.1 — Left: polynomial regression (Legendre basis) on a noisy sine: bias² falls and variance rises with degree. Right: min-norm least squares with figures/make_figs_2.py); the second model follows the min-norm setting studied by Belkin, Hsu & Xu (2019).
During training, zero each activation independently with probability model.eval() to disable it.
Augmentation (flips, crops, colour jitter, noise, elastic deformations; cutout/RandAugment/AutoAugment) injects invariances. Label smoothing replaces one-hot targets by
Stop when validation loss stops improving and keep the best checkpoint. For gradient descent on a quadratic, stopping at time
Mixup (Zhang et al. 2018):
Classical theory bounds the gap by capacity: for a hypothesis class of VC dimension
Ridge shrinkage. Data
import numpy as np
def dropout(a, p, train=True, rng=np.random.default_rng(0)):
if not train or p == 0: return a
mask = rng.random(a.shape) >= p
return a * mask / (1 - p) # inverted dropout
def ridge(X, y, lam):
return np.linalg.solve(X.T @ X + lam * np.eye(X.shape[1]), X.T @ y)
def mixup(x1, y1, x2, y2, alpha=0.2, rng=np.random.default_rng(0)):
lam = rng.beta(alpha, alpha); return lam * x1 + (1 - lam) * x2, lam * y1 + (1 - lam) * y2
print(ridge(np.array([[1.], [2.], [3.]]), np.array([2., 4., 6.]), 14.0)) # [1.]import torch.nn as nn, torch.nn.functional as F
loss = F.cross_entropy(logits, y, label_smoothing=0.1)
net = nn.Sequential(nn.Linear(256, 256), nn.ReLU(), nn.Dropout(0.1))
# early stopping: track val loss, save best state_dict, stop after `patience` epochs without improvement- PAC-Bayes, Rademacher complexity, margin and norm-based bounds give non-vacuous bounds for some networks; algorithmic stability links SGD to generalisation.
- Sharpness/flat minima, SAM and implicit bias of gradient descent.
- Scaling laws relate test loss to data, parameters and compute (Module 23).
- Distribution shift breaks the i.i.d. assumption (Module 24).
- Regularisation by architecture and data: pretraining, multitask learning, self-supervision (Modules 17, 22).
- Cross-validation variants: grouped, stratified, nested (for model selection plus evaluation).
- Tuning on the test set (even indirectly via repeated peeking).
- Fitting scalers/tokenizers/feature selectors on the full dataset before splitting.
- Random row splits for grouped or time-series data.
- Applying dropout/BN in train mode at evaluation.
- Applying weight decay to biases and normalisation parameters.
- Treating augmentation as free: it must preserve the label.
Q1. State the bias–variance decomposition and say what each term means.
Show answer
Expected squared error = bias² (systematic error of the average model) + variance (sensitivity to the training sample) + irreducible noise
Q2. Why does L2 regularisation shrink weights, and how is it a prior?
Show answer
Its gradient
Q3. Why does L1 yield sparse solutions while L2 does not?
Show answer
The L1 penalty has constant-magnitude gradient and a kink at 0, so the proximal step sets small weights exactly to 0; L2's gradient shrinks proportionally, approaching but rarely reaching 0.
Q4. Why scale activations by
Show answer
To keep the expected activation unchanged between training and inference, so no rescaling is needed at test time.
Q5. Give three examples of data leakage.
Show answer
Normalising with statistics from the full dataset; near-duplicate or same-patient samples in both train and test; features derived from the label or from the future in time-series problems.
Q6. What is double descent and does it contradict the bias–variance trade-off?
Show answer
Test error rises to a peak at the interpolation threshold and then decreases again with more parameters. It refines rather than refutes the trade-off: beyond the threshold, the min-norm/implicitly regularised solution has lower variance.
Q7. How does early stopping regularise?
Show answer
It limits how far optimisation moves from the (small) initialisation, equivalent for quadratics to an L2 penalty whose strength decreases with training time.
Q8. Why does ensembling help and when does it not?
Show answer
It reduces variance by averaging; gains shrink as members become correlated (
Q9. What does label smoothing do to the logits?
Show answer
It caps the optimal logit gaps (the target is never exactly 1), reducing over-confidence and often improving calibration, though it can hurt distillation quality.
Q10. Why can networks that fit random labels still generalise on real data?
Show answer
Capacity is not the whole story: data structure, architecture inductive biases and the implicit bias of SGD favour simple, smooth solutions among the many interpolating ones.
- Srivastava, N., et al. (2014). Dropout: a simple way to prevent neural networks from overfitting. JMLR, 15.
- Zhang, C., Bengio, S., Hardt, M., Recht, B., & Vinyals, O. (2017). Understanding deep learning requires rethinking generalization. ICLR.
- Belkin, M., Hsu, D., Ma, S., & Mandal, S. (2019). Reconciling modern machine-learning practice and the classical bias–variance trade-off. PNAS, 116(32).
- Belkin, M., Hsu, D., & Xu, J. (2020). Two models of double descent for weak features. SIAM J. Math. Data Sci., 2(4).
- Nakkiran, P., et al. (2020). Deep double descent. ICLR. arXiv:1912.02292.
- Zhang, H., Cissé, M., Dauphin, Y., & Lopez-Paz, D. (2018). mixup: beyond empirical risk minimization. ICLR. arXiv:1710.09412.
- Yun, S., et al. (2019). CutMix. ICCV. arXiv:1905.04899.
- Szegedy, C., et al. (2016). Rethinking the Inception architecture for computer vision (label smoothing). CVPR.
- Cubuk, E. D., et al. (2019). AutoAugment. CVPR; Cubuk et al. (2020). RandAugment. CVPR Workshops.
- Huang, G., et al. (2016). Deep networks with stochastic depth. ECCV.
- Wager, S., Wang, S., & Liang, P. (2013). Dropout training as adaptive regularization. NeurIPS.
- Vapnik, V. (1998). Statistical Learning Theory. Wiley.
- Kapoor, S., & Narayanan, A. (2023). Leakage and the reproducibility crisis in machine-learning-based science. Patterns, 4(9).
⬅️ Module 09 · 🗺️ Curriculum · 🏠 Home · Module 11 ➡️
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths · ❓ Question bank · 📖 Glossary · 📚 References · ✏️ Contributing
🏠 Home · 🗺️ Curriculum · 🧭 Learning paths
❓ Question bank · 📖 Glossary · 📚 References
Jump to module:
01 02 03 04 05 06 07 08 09 10 11 12
13 14 15 16 17 18 19 20 21 22 23 24