Skip to content
Deep learning Core 25 min read

Regularisation: dropout, weight decay, augmentation

A network big enough to be useful is big enough to memorise its training set. Regularisation is everything you do to make it learn the rule instead of the examples — shrink the weights, inject noise, multiply the data, soften the targets — and each technique is a different statement of what you believe a good solution looks like.

10,000 ft

Machine learning is a bet that a function fitted to some examples will work on examples it has never seen. Classical theory (bias and variance) says you win the bet by limiting model capacity. Deep learning broke the intuition: networks with far more parameters than training examples generalise well, yet the same networks can perfectly memorise random labels. What separates the two outcomes is not parameter count but the implicit and explicit preferences built into training — the optimiser's noise, the architecture's symmetries, weight decay, dropout, augmentation and early stopping. These are the levers on this page. They connect upward to learning theory (double descent, flat minima), sideways to optimisers (weight decay is implemented there) and downward to the training recipe, where you decide when to reach for them.

2,000 ft

Every regulariser does one of four things. Constrain the parameters (weight decay, max-norm): prefer small, simple weights. Inject noise during training (dropout, stochastic depth, SGD itself): force the network to work even when parts of it are missing, which averages over many networks. Enlarge the data (augmentation, mixup, CutMix): encode invariances you know are true, so the network sees "more" examples. Constrain the outputs or the process (label smoothing, early stopping): stop the model becoming over-confident or over-fitted. A reader who remembers only this map can place any new technique on it.

Four levers on generalisation
Four levers on generalisation. Fit the rule, not the examples, Constrain parameters, Inject noise, Enlarge the data, Constrain outputs / process, weight decay (L2) max-norm, dropout stochastic depth SGD noise, crops, flips, colour mixup, CutMix RandAugment, label smoothing early stoppingFour levers on generalisation. Fit the rule, not the examples, Constrain parameters, Inject noise, Enlarge the data, Constrain outputs / process, weight decay (L2) max-norm, dropout stochastic depth SGD noise, crops, flips, colour mixup, CutMix RandAugment, label smoothing early stopping

Ground level

What overfitting looks like in a deep network

You see it in the curves: training loss keeps falling, validation loss bottoms out and climbs. The model is spending capacity on the idiosyncrasies of the training set. For deep networks the picture is stranger than for a polynomial fit, and three empirical facts frame everything else.

  1. Networks can memorise anything. Zhang et al. (2016) trained standard image classifiers on CIFAR-10 with the labels replaced by random noise. The networks reached zero training error anyway — they memorised 50,000 arbitrary labels — while test accuracy was, of course, chance. With the true labels the same architecture generalises well. Capacity alone cannot explain generalisation.
  2. Explicit regularisers help, but they are not the main story. The same paper found that turning off weight decay, dropout and augmentation hurt test accuracy by a few points, not catastrophically. Architecture (convolutions, residual connections) and SGD's implicit preferences do most of the work. Explicit regularisation is the final few per cent — which is often the part that matters.
  3. More capacity can reduce overfitting. Belkin et al. (2018) and Nakkiran et al. (2019) documented double descent: test error rises as a model approaches the size where it can just barely interpolate the training data, then falls again as it grows further. The worst place to be is exactly at the interpolation threshold, where the fit is forced and brittle. Our code below lands on that threshold on purpose.

Weight decay: prefer small weights

The oldest regulariser adds a penalty \(\tfrac{\lambda}{2}\|\boldsymbol\theta\|^2\) to the loss. Its gradient is \(\lambda\boldsymbol\theta\), so each SGD step becomes \(\boldsymbol\theta \leftarrow (1-\eta\lambda)\boldsymbol\theta - \eta\mathbf g\): the weights decay geometrically towards zero unless the data keeps pushing them out. (For Adam, apply the decay outside the adaptive scaling — that is AdamW; see optimisers.)

Why should small weights generalise? Three answers, each useful:

  • Bayesian. L2 is the negative log of a Gaussian prior on the weights. Minimising loss + L2 is maximum a posteriori estimation (MLE, MAP and Bayes). You are saying "before seeing data, I believe weights are near zero".
  • Smoothness. For a network, the size of the weights bounds how fast the output can change with the input (its Lipschitz constant is at most the product of the layers' spectral norms). Small weights mean smooth functions, which cannot thread through every noisy point.
  • Shrinkage of weak directions. For a linear model, L2 shrinks the solution along each eigen-direction of the data by \(\lambda_i/(\lambda_i+\lambda)\) (derived in The maths). Directions with plenty of signal (\(\lambda_i \gg \lambda\)) are kept; directions with little (\(\lambda_i \ll \lambda\)), which is where noise gets fitted, are suppressed.

Worked example: ridge at the interpolation threshold

Fifty training examples, fifty features, only five of which matter, Gaussian noise of variance 0.25. With \(\lambda = 0\) the model has exactly enough freedom to fit every point: training MSE 0.000, test MSE 106.4, weight norm 11.0. Adding a tiny decay \(\lambda = 0.01\) gives training MSE 0.039 and test MSE 1.79 — a 60× improvement — by suppressing the near-zero eigen-directions the unregularised fit was inflating. Too much (\(\lambda = 10\)) underfits: test MSE 7.1. These are the outputs of the code in Build it.

Weight decay in modern networks does something different. Most layers in a modern network are followed by a normalisation layer (BatchNorm, LayerNorm, RMSNorm — see initialisation and normalisation). Normalisation makes the layer's output invariant to the scale of its weights: \(f(c\mathbf w) = f(\mathbf w)\) for \(c>0\). Then L2 cannot change what function the network computes at all. What it changes is the dynamics: the gradient of a scale-invariant weight is perpendicular to it and shrinks like \(1/\|\mathbf w\|\), so the effective learning rate of the direction of \(\mathbf w\) is \(\eta/\|\mathbf w\|^2\). Without decay, \(\|\mathbf w\|\) grows over training and learning silently slows; with decay, the norm settles at an equilibrium where the angular update per step is about \(\sqrt{2\eta\lambda}\) (derived below). van Laarhoven (2017), Zhang et al. (2018) and Kosson et al. (2023) work this out; the practical upshot is that for normalised networks, weight decay is mostly a learning-rate controller. That is why its best value is tied to the learning rate and schedule, and why it matters even in billion-token LLM runs that never overfit in the classical sense.

Weight decay is also implicated in grokking: Power et al. (2022) trained small transformers on modular arithmetic and saw validation accuracy jump from chance to near-perfect long after training accuracy had saturated. Of the optimisation choices they compared, weight decay was among the most effective at improving data efficiency — getting the jump with less data.

Dropout: train an exponential ensemble

Hinton et al. (2012) and Srivastava et al. (2014) proposed something that sounds destructive: on every training step, set each hidden unit to zero with probability \(p\), independently.

training step: a random thinned networktest time: every unit, weights unchanged
Dropout samples a different thinned network for every mini-batch (dropped units crossed out; their connections vanish). With n droppable units there are 2ⁿ such sub-networks, all sharing weights. Inverted dropout scales the kept activations by 1/(1−p) during training, so the full network at test time needs no correction.

Three ways to see why this helps:

  • It prevents co-adaptation. A unit cannot rely on a specific partner being present, so each unit must be useful in many contexts. Features become more individually meaningful and more redundant.
  • It trains an ensemble. With \(n\) droppable units there are \(2^n\) thinned networks, all sharing weights; each step trains one of them. At test time, using all units with weights scaled appropriately approximates the geometric mean of the ensemble's predictions — exactly so for a single softmax layer. Ensembles are among the most reliable ways to improve generalisation; dropout gets a weak version almost for free.
  • It is a data-dependent L2 penalty. For a linear model with dropout on its inputs, the expected loss over masks equals the ordinary loss plus \(\tfrac{p}{1-p}\sum_j x_j^2 w_j^2\) (derived below; Wager, Wang and Liang 2013 extend this to generalised linear models). Weights attached to large, frequently active inputs are penalised more. Our code checks this identity by Monte Carlo: 2.7826 against the analytic 2.7759.

Inverted dropout. If units are dropped with probability \(p\) during training, the expected input to the next layer is \((1-p)\) times what it will be at test time. Every modern framework fixes this during training: kept activations are multiplied by \(1/(1-p)\), so the test-time network is used unchanged. With \(p = 0.5\), a surviving activation of 0.8 is passed on as 1.6; averaged over masks the next layer sees 0.8, matching test time.

Where and how much. The original paper used \(p = 0.5\) for hidden units and \(p = 0.2\) for inputs. AlexNet put dropout 0.5 on its two large fully connected layers. The original Transformer used \(p = 0.1\) on every sub-layer output and on the embeddings. In convolutional layers, dropping single activations does little because neighbours are correlated; drop whole channels instead (spatial dropout) or whole residual branches (below). Modern LLM pre-training on a single pass over a huge corpus typically uses little or no dropout — nanoGPT's default comment reads "for pretraining 0 is good, for finetuning try 0.1+" — because when every example is fresh there is little to overfit, and dropout slows convergence.

Dropout at test time. Leave it on, run the network \(T\) times, and the spread of the outputs is an estimate of model uncertainty. Gal and Ghahramani (2015) showed this "MC dropout" approximates Bayesian inference in a deep Gaussian process.

Stochastic depth / DropPath (Huang et al., 2016) applies the idea to whole residual blocks: during training each block \(\mathbf x + F(\mathbf x)\) is replaced by the identity \(\mathbf x\) with some probability (rising linearly with depth, to 0.5 in the last block in the paper). It regularises and speeds training, because skipped blocks cost nothing. It is standard in vision transformers and ConvNeXt — see residual networks.

Data augmentation: write your invariances into the data

If you know that a cat flipped left-to-right is still a cat, you can tell the network by showing it both. Augmentation is the most powerful regulariser in vision because it adds real information — knowledge of the task's symmetries — rather than a generic preference for simplicity.

Technique What it does Encodes
Random resized crop, flip crop a random region and aspect, resize; mirror translation, scale, reflection invariance
Colour jitter perturb brightness, contrast, saturation, hue lighting invariance
Cutout (DeVries and Taylor, 2017) zero out a random square robustness to occlusion
RandAugment (Cubuk et al., 2019) apply \(N\) random ops from a list, each at magnitude \(M\) a whole family, tuned by just two numbers
mixup (Zhang et al., 2017) train on \(\lambda x_i + (1-\lambda)x_j\) with label \(\lambda y_i + (1-\lambda)y_j\) linear behaviour between examples
CutMix (Yun et al., 2019) paste a patch of image \(j\) into image \(i\); mix labels by area localisable features + mixing

AlexNet (2012) already relied on augmentation: random 224×224 crops of 256×256 images plus horizontal flips, and a PCA-based colour perturbation. Without it, the authors reported, the network overfitted substantially. Modern image recipes (DeiT, ConvNeXt) stack RandAugment, mixup, CutMix, random erasing, label smoothing and stochastic depth together.

Augmentation is only as good as the invariance is true. Flipping digits turns some 2s into mirror-image glyphs that are not digits; rotating a "6" by 180° gives a "9"; colour jitter destroys the signal for "is this fruit ripe". For text, the cheap symmetries are rarer: back-translation (translate to another language and back) and synonym substitution exist, but language models mostly get their regularisation from scale — enormous, deduplicated, single-epoch corpora. When data runs short, repetition is the fallback: Muennighoff et al. (2023) found that up to about four epochs of repeated data were nearly as good as fresh data, with returns decaying quickly beyond that. See pre-training data.

Label smoothing: do not chase infinite confidence

Cross-entropy with a one-hot target is minimised only as the correct logit goes to \(+\infty\) relative to the others. The network can keep reducing the loss by growing its logits — and its weights — long after it classifies everything correctly, which makes it over-confident and poorly calibrated. Label smoothing (Szegedy et al., 2015) replaces the target with \((1-\varepsilon)\) on the true class plus \(\varepsilon/K\) spread over all \(K\) classes. The optimum now has a finite logit gap.

Worked example: the finite optimum

ImageNet: \(K = 1000\), \(\varepsilon = 0.1\). The smoothed target puts \(1-0.1+0.1/1000 = 0.9001\) on the correct class and \(0.0001\) on each other class. The softmax that matches it exactly has a logit gap of \(\ln(0.9001/0.0001) = \ln 9001 \approx 9.1\) between the correct class and every other. Beyond that, the loss increases. Logits are held in a sensible range.

Müller, Kornblith and Hinton (2019) showed that label smoothing pulls each class's penultimate representations into tight, equidistant clusters. That improves calibration but erases information about which wrong classes are similar to the right one — so a smoothed teacher is a worse teacher for knowledge distillation.

Early stopping

Keep a validation set, evaluate periodically, keep the checkpoint with the best validation score. It is free, it is always on, and for gradient descent on a quadratic loss it is provably close to L2: stopping after \(\tau\) steps at learning rate \(\eta\) behaves like weight decay with \(\lambda \approx 1/(\eta\tau)\) (Goodfellow et al., Deep Learning, §7.8; derived below). Training longer is literally a weaker prior. Two cautions: modern networks sometimes show epoch-wise double descent, where validation loss rises and then falls again, so stop on a patient rule rather than the first uptick; and if you choose hyperparameters by peeking at the same validation set many times, it stops being an unbiased estimate (see metrics, validation and leakage).

Implicit regularisation: the optimiser's own preferences

Part of why over-parameterised networks generalise is that SGD does not find an arbitrary zero-loss solution; it finds particular ones.

  • On an under-determined linear least-squares problem, gradient descent started from zero converges to the minimum-norm solution among the infinitely many that fit — implicit L2 with no penalty term.
  • Noise and step size favour flat regions. Large learning rates and small batches cannot settle in sharp, narrow minima (the stability limit \(\eta < 2/\lambda_{\max}\) from optimisers forbids it), so they end in flatter ones, which Keskar et al. (2016) associated with better generalisation.
  • Sharpness-aware minimisation (SAM; Foret et al., 2020) makes flatness explicit: minimise the worst-case loss within a small ball, \(\min_{\boldsymbol\theta}\max_{\|\boldsymbol\epsilon\|\le\rho}L(\boldsymbol\theta+\boldsymbol\epsilon)\), approximated with one extra gradient step. It costs about 2× compute per step.
  • Batch normalisation adds noise, because each example is normalised with statistics from a random mini-batch; Ioffe and Szegedy noted it reduced the need for dropout.

First principles

There is no free lunch: averaged over all possible tasks, no learning algorithm beats any other. Generalisation is only possible because real tasks have structure, and a regulariser is a bet on what that structure is. Writing the bets out makes it clear when each technique will help.

  • Weight decay bets that the target is smooth and that small, distributed weights explain the data better than large, specialised ones. It fails gracefully: too strong, and it underfits.
  • Dropout bets that the target can be computed by many redundant pathways. It is a bad bet for very small networks (they have no spare capacity to be redundant with) and a weak one in single-epoch regimes where nothing is seen twice.
  • Augmentation bets on specific symmetries. It is the only lever on this page that adds information you have and the data lacks. When the bet is right it beats every generic regulariser; when it is wrong it teaches the model a falsehood.
  • Label smoothing bets that the labels are not perfectly reliable and that probability estimates near 0 and 1 are not trustworthy anyway.
  • Early stopping bets that the first things gradient descent learns are the general ones. For linear models this is literally true: gradient descent fits the large-eigenvalue directions of the data first, and those are the ones with the most signal.

What breaks if you remove all of them? Usually less than you would fear for a large network on a large, fresh dataset — the architecture and SGD carry the load. A lot breaks when data is small relative to the model: fine-tuning a big pre-trained model on a few thousand examples is exactly where dropout, weight decay, early stopping and augmentation earn their keep.

The maths

Notation. \(X \in \mathbb R^{n\times d}\) design matrix, \(\mathbf y \in \mathbb R^n\) targets, \(\mathbf w \in \mathbb R^d\) weights, \(\lambda \ge 0\) decay strength, \(p \in [0,1)\) drop probability, \(K\) number of classes, \(\varepsilon\) smoothing amount.

Derivation: L2 is MAP with a Gaussian prior

Assume \(y_i = \mathbf w^\top\mathbf x_i + \text{noise}\), noise \(\sim\mathcal N(0,\sigma^2)\), and prior \(\mathbf w\sim\mathcal N(0,\tau^2 I)\). The log-posterior is

\[ \log p(\mathbf w\mid X,\mathbf y) = -\frac{1}{2\sigma^2}\|X\mathbf w-\mathbf y\|^2 - \frac{1}{2\tau^2}\|\mathbf w\|^2 + \text{const}. \]

Maximising it is minimising \(\|X\mathbf w-\mathbf y\|^2 + \lambda'\|\mathbf w\|^2\) with \(\lambda' = \sigma^2/\tau^2\). A tighter prior (small \(\tau\)) or noisier data (large \(\sigma\)) means stronger decay.

Derivation: ridge shrinks each eigen-direction by λᵢ/(λᵢ+λ)

Minimise \(\tfrac1n\|X\mathbf w-\mathbf y\|^2+\lambda\|\mathbf w\|^2\). Setting the gradient to zero: \(\mathbf w_\lambda = (X^\top X + n\lambda I)^{-1}X^\top\mathbf y\). Write \(\tfrac1n X^\top X = Q\Lambda Q^\top\) and let \(\mathbf w_0 = (X^\top X)^{-1}X^\top\mathbf y\) be the unregularised solution (when it exists). Then

\[ Q^\top\mathbf w_\lambda = (\Lambda+\lambda I)^{-1}\Lambda\, Q^\top\mathbf w_0, \qquad\text{i.e.}\qquad (\mathbf w_\lambda)_i = \frac{\lambda_i}{\lambda_i+\lambda}(\mathbf w_0)_i \]

in the eigenbasis. At \(n = d\) the smallest \(\lambda_i\) of a random Gaussian \(X\) is close to zero, so \(\mathbf w_0\) divides noise by near-zero numbers — the 106.4 test MSE. Any \(\lambda\) larger than those tiny eigenvalues removes the blow-up.

Derivation: early stopping ≈ L2 with λ ≈ 1/(ητ)

Gradient descent from \(\mathbf w=0\) on the same quadratic gives, in the eigenbasis, \((\mathbf w_\tau)_i = \big[1-(1-\eta\lambda_i)^\tau\big](\mathbf w_0)_i\). Compare with ridge's factor \(\lambda_i/(\lambda_i+\lambda) = 1 - \lambda/(\lambda_i+\lambda)\). For small \(\eta\lambda_i\), \((1-\eta\lambda_i)^\tau \approx e^{-\eta\tau\lambda_i}\). Directions with \(\lambda_i \gg 1/(\eta\tau)\) are fully learned by both methods; directions with \(\lambda_i \ll 1/(\eta\tau)\) are learned by a fraction \(\approx \eta\tau\lambda_i\) by early stopping and \(\approx \lambda_i/\lambda\) by ridge. Matching gives \(\lambda \approx 1/(\eta\tau)\).

Derivation: input dropout on a linear model is adaptive ridge

Let the mask \(m_j\sim\text{Bernoulli}(1-p)\) independently and the dropped input be \(\tilde x_j = m_j x_j/(1-p)\), so \(\mathbb E[\tilde x_j] = x_j\) and \(\operatorname{Var}[\tilde x_j] = x_j^2\,p/(1-p)\). For one example,

\[ \mathbb E_m\big[(\mathbf w^\top\tilde{\mathbf x}-y)^2\big] = (\mathbf w^\top\mathbf x-y)^2 + \operatorname{Var}\big[\mathbf w^\top\tilde{\mathbf x}\big] = (\mathbf w^\top\mathbf x-y)^2 + \frac{p}{1-p}\sum_j x_j^2 w_j^2 , \]

using \(\mathbb E[Z^2] = (\mathbb E Z)^2+\operatorname{Var}Z\) and independence of the masks. Summed over the data, the penalty is \(\frac{p}{1-p}\sum_j w_j^2\sum_i x_{ij}^2\): an L2 penalty whose strength per weight is proportional to how much energy its input feature carries.

Derivation: weight decay on a scale-invariant weight reaches an equilibrium

Suppose \(L(c\mathbf w) = L(\mathbf w)\) for all \(c>0\) (a weight feeding a normalisation layer). Differentiating in \(c\) at \(c=1\) gives \(\mathbf w^\top\nabla L(\mathbf w) = 0\): the gradient is orthogonal to \(\mathbf w\). Differentiating \(L(c\mathbf w)=L(\mathbf w)\) in \(\mathbf w\) gives \(\nabla L(c\mathbf w) = \nabla L(\mathbf w)/c\): write \(\|\mathbf g\| = G/\|\mathbf w\|\). With SGD and decay, \(\mathbf w' = (1-\eta\lambda)\mathbf w - \eta\mathbf g\), and orthogonality gives

\[ \|\mathbf w'\|^2 = (1-\eta\lambda)^2\|\mathbf w\|^2 + \eta^2 G^2/\|\mathbf w\|^2 . \]

At equilibrium (\(\|\mathbf w'\| = \|\mathbf w\|\), small \(\eta\lambda\)): \(2\eta\lambda\|\mathbf w\|^2 \approx \eta^2G^2/\|\mathbf w\|^2\), so \(\|\mathbf w\|^4 \approx \eta G^2/(2\lambda)\). The angle the weight rotates per step is \(\eta\|\mathbf g\|/\|\mathbf w\| = \eta G/\|\mathbf w\|^2 \approx \sqrt{2\eta\lambda}\). The product \(\eta\lambda\), not either alone, sets how fast normalised layers learn.

Mixup. Draw \(\lambda\sim\operatorname{Beta}(\alpha,\alpha)\) and two examples; train on \(\tilde x = \lambda x_i + (1-\lambda)x_j\), \(\tilde y = \lambda y_i + (1-\lambda)y_j\) (one-hot labels mixed). Small \(\alpha\) (the paper uses 0.1–0.4 on ImageNet) makes most mixes close to one of the two originals.

Label smoothing. Target \(q_k = (1-\varepsilon)\mathbb 1[k=y]+\varepsilon/K\). The cross-entropy \(-\sum_k q_k\log\operatorname{softmax}(\mathbf z)_k\) is minimised when \(\operatorname{softmax}(\mathbf z) = \mathbf q\), i.e. \(z_y - z_k = \ln\frac{1-\varepsilon+\varepsilon/K}{\varepsilon/K}\) for every \(k\ne y\). It also equals ordinary cross-entropy plus \(\varepsilon\) times the cross-entropy from the uniform distribution — a penalty on confident, low-entropy outputs (see entropy, cross-entropy and KL).

Build it

NumPy. Part 1 sweeps weight decay on a linear model sitting exactly at the interpolation threshold. Part 2 checks the dropout-as-ridge identity by Monte Carlo over 200,000 masks.

import numpy as np
rng = np.random.default_rng(0)
n, d = 50, 50                                   # as many features as examples: the worst case for overfitting
w_true = np.zeros(d); w_true[:5] = [2.0, -1.5, 1.0, 0.5, -0.5]
X, Xte = rng.normal(size=(n, d)), rng.normal(size=(2000, d))
y = X @ w_true + 0.5 * rng.normal(size=n)
yte = Xte @ w_true + 0.5 * rng.normal(size=2000)

# 1) Weight decay = ridge regression: closed form w = (X^T X + n*lam I)^-1 X^T y
for lam in [0.0, 1e-3, 1e-2, 1e-1, 1.0, 10.0]:
    w = np.linalg.lstsq(X.T @ X + n * lam * np.eye(d), X.T @ y, rcond=None)[0]
    tr = np.mean((X @ w - y)**2); te = np.mean((Xte @ w - yte)**2)
    print(f"lam={lam:<6} train MSE={tr:6.3f}  test MSE={te:6.3f}  |w|={np.linalg.norm(w):5.2f}")

# 2) Dropout on the inputs of a linear model is ridge with a data-dependent penalty.
p = 0.3                                          # drop probability
w = rng.normal(size=d) * 0.3
masks = rng.random((200_000, d)) > p             # inverted dropout: keep and scale by 1/(1-p)
x0, y0 = X[0], y[0]
mc = np.mean(((masks * x0 / (1 - p)) @ w - y0)**2)
analytic = (x0 @ w - y0)**2 + p / (1 - p) * np.sum(x0**2 * w**2)
print(f"dropout loss, Monte Carlo = {mc:.4f}   analytic = {analytic:.4f}")

Output:

lam=0.0    train MSE= 0.000  test MSE=106.389  |w|=10.99
lam=0.001  train MSE= 0.016  test MSE= 6.381  |w|= 3.85
lam=0.01   train MSE= 0.039  test MSE= 1.787  |w|= 2.70
lam=0.1    train MSE= 0.150  test MSE= 2.291  |w|= 2.11
lam=1.0    train MSE= 1.290  test MSE= 4.421  |w|= 1.19
lam=10.0   train MSE= 4.891  test MSE= 7.106  |w|= 0.29
dropout loss, Monte Carlo = 2.7826   analytic = 2.7759

The irreducible noise is 0.25, so the best model (1.79) still has room to improve — with only 50 examples for 50 features there is not enough data to pin down the five true weights. Try n = 200.

In PyTorch the techniques are one line each:

import torch.nn as nn, torch
drop = nn.Dropout(p=0.1)                                     # inverted dropout; off in model.eval()
loss_fn = nn.CrossEntropyLoss(label_smoothing=0.1)
opt = torch.optim.AdamW(model.parameters(), lr=3e-4, weight_decay=0.05)
# torchvision.transforms.v2: RandomResizedCrop(224), RandomHorizontalFlip(), RandAugment(), MixUp/CutMix

Things to try

  • Set d = 25 and d = 200 with n = 50 and rerun the \(\lambda = 0\) line. You have just traced double descent: test error peaks at \(d = n\) and falls on either side.
  • Replace the closed form by gradient descent from \(\mathbf w = 0\) and record test MSE every 10 steps. Find the step count whose test error matches the best ridge — and compare with \(1/(\eta\lambda)\).
  • Add inverted dropout to the two-layer MLP from neurons and MLPs and plot train and validation loss with \(p = 0, 0.2, 0.5\).
  • Compute the label-smoothing logit gap for \(K = 10\), \(\varepsilon = 0.1\) and for \(K = 50{,}000\) (a language-model vocabulary). What does that suggest about smoothing in LMs?

In practice

  • Start with the cheap, nearly-always-right ones: AdamW weight decay (0.01–0.1 for transformers, 5e-5 to 5e-4 with SGD for CNNs), early stopping on a held-out set, and the standard augmentation for your modality.
  • Diagnose before adding. Regularisers fix a generalisation gap (training much better than validation). If training loss is itself poor, regularisation will make things worse; you need a bigger model or a better optimiser setup first. The recipe puts "overfit first, then regularise" in that order for this reason.
  • Fine-tuning small datasets is where every lever matters: dropout 0.1–0.3, label smoothing 0.1, a few epochs, early stopping, low learning rate, and sometimes freezing layers. Parameter- efficient methods such as LoRA are themselves a strong regulariser — they restrict the update to a low-rank subspace.
  • Exclude biases, normalisation gains and (often) embeddings from weight decay.
  • Turn dropout off at evaluation (model.eval() in PyTorch). Forgetting is a classic bug that shows up as noisy, pessimistic validation numbers.

Common misconceptions

\"More parameters means more overfitting\"

Past the interpolation threshold, adding parameters typically reduces test error (double descent), and the largest models in the world are trained with little explicit regularisation. Overfitting is about the ratio of effective capacity to data and about the training procedure, not raw parameter count.

\"Weight decay just keeps weights small\"

In a network with normalisation layers, the scale of most weights does not affect the output at all. There, decay controls the effective learning rate of the weights' directions. Turning it off can slow late-stage learning even when nothing is overfitting.

\"Dropout is always good\"

It slows convergence, interacts badly with BatchNorm (the variance of activations differs between train and test), and in single-epoch pre-training it usually costs more than it gives. Use it where data is scarce relative to the model.

Check yourself

Why does dropout need a 1/(1−p) rescaling, and when is it applied in modern frameworks?

During training a unit's input is, in expectation, \((1-p)\) times its test-time value because only that fraction of incoming units survives. Inverted dropout multiplies surviving activations by \(1/(1-p)\) during training, so expectations match and the test-time network runs unmodified.

A network gets 99% training accuracy and 70% validation accuracy. Another gets 72% training and 70% validation. Which needs regularisation?

Only the first: it has a 29-point generalisation gap. The second underfits — regularisation would lower its training accuracy further. It needs more capacity, more training or a better optimiser configuration.

With label smoothing ε = 0.1 and 10 classes, what logit gap does the optimum have?

True class target \(0.9+0.01 = 0.91\), others \(0.01\). Gap \(= \ln(0.91/0.01) = \ln 91 \approx 4.51\).

Why is horizontal flipping a good augmentation for ImageNet but a bad one for reading street signs or digits?

Augmentation teaches an invariance. Object identity is invariant to mirroring; the meaning of text and many digits is not (a mirrored "2" or "S" is not the same symbol, and some flipped signs reverse their meaning). A false invariance injects label noise.

Explain why weight decay matters in a BatchNorm network even though BN makes the output independent of the weights' scale.

Scale invariance makes the gradient orthogonal to \(\mathbf w\) and proportional to \(1/\|\mathbf w\|\), so the effective step on the weight's direction is \(\eta/\|\mathbf w\|^2\). Gradient steps alone grow \(\|\mathbf w\|\) (Pythagoras), steadily shrinking the effective learning rate. Decay balances this growth and fixes the angular update at about \(\sqrt{2\eta\lambda}\).

Hard: show that adding Gaussian noise of variance σ² to the inputs of a linear regression is equivalent to ridge, and find λ.

\(\mathbb E_\epsilon[(\mathbf w^\top(\mathbf x+\boldsymbol\epsilon)-y)^2] = (\mathbf w^\top\mathbf x-y)^2+\mathbf w^\top\mathbb E[\boldsymbol\epsilon\boldsymbol\epsilon^\top]\mathbf w = (\mathbf w^\top\mathbf x-y)^2+\sigma^2\|\mathbf w\|^2\). So it is ridge with \(\lambda = \sigma^2\) per example (Bishop, 1995, showed the general version: training with input noise is equivalent to Tikhonov regularisation).

Hard: Why might a teacher trained with label smoothing make a worse distillation teacher?

Distillation transfers the teacher's full output distribution, including the relative probabilities of wrong classes ("dark knowledge"). Label smoothing pushes all wrong-class logits toward the same value and collapses each class's representations into tight clusters, erasing the similarity structure the student would learn from (Müller et al., 2019).

Go deeper

Papers

Courses and books

Code

Where this leads