Skip to content

Module 10

Anurag Prasad edited this page Nov 9, 2026 · 10 revisions

Module 10 — Regularization, Generalization and Learning Theory

⬅️ 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


Overview and learning goals

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.

Beginner: the big picture

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
Loading

Core concepts and derivations

Train/validation/test splits and data leakage

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.

Underfitting, overfitting and the generalisation gap

Gap $=R(\hat\theta)-\hat R(\hat\theta)$ (Module 06). Learning curves (error vs training-set size or epochs) diagnose the regime: large persistent gap → overfitting (more data, regularisation); both errors high and close → underfitting (more capacity, better features, longer training).

Bias–variance trade-off

For $y=f(x)+\varepsilon$, $\mathbb{E}\varepsilon=0$, $\mathrm{Var}\varepsilon=\sigma^2$, and an estimator $\hat f_{\mathcal{D}}$ trained on a random dataset $\mathcal{D}$:

$$ \mathbb{E}_{\mathcal{D},\varepsilon}\bigl[(y-\hat f(x))^2\bigr]=\underbrace{\bigl(f(x)-\mathbb{E}_{\mathcal D}\hat f(x)\bigr)^2}_{\text{bias}^2}+\underbrace{\mathrm{Var}_{\mathcal D}\bigl(\hat f(x)\bigr)}_{\text{variance}}+\underbrace{\sigma^2}_{\text{irreducible}} . $$

Derivation: add and subtract $f$ and $\mathbb{E}\hat f$; cross terms vanish because $\varepsilon$ is independent of $\hat f$ with zero mean and $\mathbb{E}[\hat f-\mathbb{E}\hat f]=0$. Flexible models have low bias but high variance.

Bias-variance trade-off with polynomial fits and double descent with min-norm least squares

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 $p$ of $D=150$ Gaussian features and $n=40$ samples: test error peaks at the interpolation threshold $p=n$ and descends again. Original figure (figures/make_figs_2.py); the second model follows the min-norm setting studied by Belkin, Hsu & Xu (2019).

L1/L2 penalties and weight decay

$L_{\text{reg}}=L+\frac\lambda2\lVert\mathbf{w}\rVert_2^2$ gives gradient $\nabla L+\lambda\mathbf{w}$, so SGD becomes weight decay: $\mathbf{w}\leftarrow(1-\eta\lambda)\mathbf{w}-\eta\nabla L$. For linear regression this is ridge: $\hat{\mathbf{w}}=(X^\top X+\lambda I)^{-1}X^\top\mathbf{y}$, which shrinks along small-singular-value directions by $\sigma_i^2/(\sigma_i^2+\lambda)$. Bayesian view: a Gaussian prior $\mathbf{w}\sim\mathcal{N}(0,\tau^2I)$ with Gaussian noise yields MAP = ridge with $\lambda=\sigma^2/\tau^2$. $L_1$ ($\lambda\lVert\mathbf{w}\rVert_1$) corresponds to a Laplace prior; its proximal step is soft-thresholding $\mathrm{sign}(w)\max(\lvert w\rvert-\eta\lambda,0)$, which produces exact zeros (sparsity).

Dropout and stochastic regularisation

During training, zero each activation independently with probability $p$ and (inverted dropout) multiply survivors by $1/(1-p)$, so $\mathbb{E}[\tilde a]=a$ and no change is needed at test time. It prevents co-adaptation and approximates averaging an exponential ensemble of thinned networks (Srivastava et al. 2014); for linear models it acts like an adaptive L2 penalty (Wager et al. 2013). Stochastic depth/DropPath randomly skips residual blocks. Use model.eval() to disable it.

Augmentation, label smoothing, input noise and parameter sharing

Augmentation (flips, crops, colour jitter, noise, elastic deformations; cutout/RandAugment/AutoAugment) injects invariances. Label smoothing replaces one-hot targets by $(1-\varepsilon)\mathbf{y}+\varepsilon/K$, penalising over-confident logits. Input/weight noise acts as smoothness regularisation. Parameter sharing (convolution, recurrence) is a structural regulariser (Modules 11–12).

Early stopping and ensembles

Stop when validation loss stops improving and keep the best checkpoint. For gradient descent on a quadratic, stopping at time $t$ shrinks coefficients like ridge with $\lambda\sim1/(\eta t)$ (Goodfellow et al. 2016, §7.8). Ensembles average predictions of independently trained models; if $M$ models have variance $\sigma^2$ and pairwise correlation $\rho$, the ensemble variance is $\rho\sigma^2+\frac{1-\rho}{M}\sigma^2$ — diversity matters.

Mixup, CutMix and related methods

Mixup (Zhang et al. 2018): $\tilde{\mathbf{x}}=\lambda\mathbf{x}_i+(1-\lambda)\mathbf{x}_j$, $\tilde{\mathbf{y}}=\lambda\mathbf{y}_i+(1-\lambda)\mathbf{y}_j$, $\lambda\sim\mathrm{Beta}(\alpha,\alpha)$ — encourages linear behaviour between examples. CutMix pastes a patch from another image and mixes labels in proportion to area.

ERM, capacity, VC dimension and double descent

Classical theory bounds the gap by capacity: for a hypothesis class of VC dimension $d_{VC}$ and $N$ samples, with probability $1-\delta$, $R(h)\le\hat R(h)+O!\left(\sqrt{\frac{d_{VC}\ln(N/d_{VC})+\ln(1/\delta)}{N}}\right)$. Modern networks have $d_{VC}\gg N$ yet generalise: Zhang et al. (2017) showed they can fit random labels, so capacity alone does not explain generalisation. Double descent (Belkin et al. 2019; Nakkiran et al. 2020): beyond the interpolation threshold, test error can fall again as capacity grows (Figure 10.1, right). Implicit regularisation of SGD, minimum-norm solutions and architecture are leading explanations.

Worked example

Ridge shrinkage. Data $(1,2),(2,4),(3,6)$: $\sum xy=28$, $\sum x^2=14$. Unregularised $w=2$; ridge $w=\frac{28}{14+\lambda}$: $\lambda=14\Rightarrow w=1$. Weight decay step. $w=2$, $\eta=0.1$, $\lambda=0.5$, zero loss gradient: $w\leftarrow(1-0.05)\cdot2=1.9$. Inverted dropout. Keep prob $0.8$: surviving activations are multiplied by $1.25$, so their expectation is unchanged. Bias–variance. If bias²$=0.04$, variance$=0.09$, noise $\sigma^2=0.25$, expected squared error is $0.38$; a smoother model that trades variance $0.09\to0.03$ for bias² $0.04\to0.07$ lowers it to $0.35$.

Implementation

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

Advanced topics

  • 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).

Pitfalls and best practices

  • 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.

Conceptual questions and answers

Q1. State the bias–variance decomposition and say what each term means.

Expected squared error = bias² (systematic error of the average model) + variance (sensitivity to the training sample) + irreducible noise $\sigma^2$.

Q2. Why does L2 regularisation shrink weights, and how is it a prior?

Its gradient $\lambda\mathbf{w}$ pulls each weight toward 0 (weight decay). It is MAP estimation under a zero-mean Gaussian prior.

Q3. Why does L1 yield sparse solutions while L2 does not?

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 $1/(1-p)$ in dropout?

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.

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?

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?

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?

It reduces variance by averaging; gains shrink as members become correlated ($\rho\to1$).

Q9. What does label smoothing do to the logits?

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?

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.

Sources and further reading

  • 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 ➡️

🎓 Deep Learning Hub

🏠 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

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally