Topic: ml-fundamentals · deep dive

Regularisation

Everything that trades a little training fit for lower error on unseen data: L1, L2 and elastic net, weight decay and why AdamW decouples it, dropout from training to inference, augmentation and mixing, early stopping, and what regularisation still means for networks that can memorise their training set, with the bias-variance split and double descent decomposed. Fits on real data are computed in your browser and checked against scikit-learn and PyTorch. Sources linked inline; checked 3 October 2026, rebuilt 24 October 2026, split layout and 3D figures 10 November 2026. Reading: 32 min, plus 8 in closed details.

The idea in one screen

Regularisation restricts what training can fit (a penalty on the weights, noise in the forward pass, more varied data, or fewer steps) so that the gap between training and test loss narrows: training error rises a little, and error on data the model has not seen falls.

You need: a training step and its loss (the parent Topic: ml-fundamentals, Reading tab, places every regulariser in one step at step 6, Regularise), and Adam's update for section 3 (Optimisers and learning-rate schedulers). Label smoothing as a loss is on Loss functions; normalisation on Normalisation and initialisation.

λ
the strength of a penalty; λ = 0 is the unregularised fit.
Bias, variance
how far the average fit is from the truth, and how much the fit changes from one training sample to the next.
Keep probability p
the chance a unit survives dropout in one step (PyTorch's p is the drop probability, 1 − p).
Thinned network
the subnetwork left after one dropout mask.
Decoupled weight decay
shrinking the weights in the update rule itself, outside the optimiser's rescaling (AdamW).
Patience
evaluations without improvement that early stopping tolerates.
Interpolation threshold
the model size at which it can just fit the training set exactly; where double descent peaks.
Every technique in one table (reference)
TechniqueActs onWhat it doesThe knob, and typical valuesWhere it is used in 2026
L1 (lasso)the lossadds λΣ|w|: some weights become exactly 0 (sparse model, feature selection)λ, tuned by cross-validationlinear and generalised linear models
L2 (ridge)the lossadds λΣw2: every weight shrinks, none to exactly 0; steadies correlated featuresλ, tuned by cross-validationlinear models; the classical form of weight decay
Elastic netthe lossboth: sparsity, plus sharing between correlated featuresλ and the mix ρlinear models with correlated features
Weight decaythe updateshrinks every weight by a fixed fraction each step; equal to L2 for plain SGD, not for Adam0.1 with AdamW in LLM pretraining; 5 × 10−4 in AlexNetalmost every network, including LLMs
Dropoutthe forward passzeroes random units in training: an implicit ensemble of thinned networkskeep 0.5 for hidden units, 0.8 for inputs (the 2014 paper); drop 0.1 in Transformersfine-tuning, smaller models; mostly off in LLM pretraining
Stochastic depththe forward passdrops whole residual blockssurvival probability, 0.5 at the last blockvision networks (drop-path)
Data augmentationthe datalabel-preserving random transforms enlarge the training setwhich transforms, how strongvision and speech everywhere
Mixup, CutMixdata and labelstrain on blends of two examples with blended labelsα of a Beta(α, α) mixing weightimage classifiers
Label smoothingthe targetssoftens one-hot targets: caps overconfidenceε = 0.1classifiers, the original Transformer
Early stoppingthe schedulestop when validation loss turns up; keep the best checkpointpatienceany run that repeats data

The parent's Training lab tab trains presets for dropout, early stopping, Adam with L2 against AdamW and label smoothing live, with claims checked over ten seeds; its When training goes wrong tab diagnoses overfitting ("Train falls, validation rises") on recorded runs.

The same network memorises without a regulariser; with dropout the gap stays narrow

One MLP (64 inputs, two hidden layers of 96 ReLU units, 10 outputs) on scikit-learn's 8 × 8 digits: 1,437 training and 360 test images, the same seed and 300 epochs of Adam for both runs; solid is training loss, dashed is test loss, the vertical bar is the gap at epoch 300 measured (PyTorch, train_digits.py). At epoch 300 training and test loss are 0.0000 and 0.1297 without dropout, 0.0355 and 0.0763 with; test error over five seeds: 3.17% without dropout, 2.28% with. The lowest-test-loss point (epoch 60, 0.0974) is what early stopping would keep. The test images stand in for a validation set here.

1 · What regularisation is, and what it buys

A penalty. Minimise the training loss J(w) plus λ·Ω(w), where Ω measures how complex the weights are. As λ grows the fit gets simpler and its training error rises; the right λ minimises error on held-out data, so it is tuned on a validation set or by cross-validation, never on the test set.

A constraint. The same solutions come from minimising J(w) subject to Ω(w) ≤ t: each λ corresponds to some budget t (a Lagrange multiplier argument; Goodfellow et al., section 7.2). Tibshirani defined the lasso this way, least squares subject to Σ|wj| ≤ t (1996). This view explains why L1 gives zeros (section 2).

A third view: the penalty as a prior (depth)

A prior. Negative log-likelihood plus a penalty is maximum a posteriori estimation: the penalty is the negative log of a prior on the weights. A Gaussian prior N(0, τ2) gives the L2 penalty ‖w‖2/(2τ2); a Laplace prior gives L1, log p(w) = −α‖w‖1 + constant (Goodfellow et al., eq. 7.24 and section 5.6.1). For least squares with noise variance σ2, the ridge λ (on ‖y − Xw‖2 + λ‖w‖2) is σ2/τ2 derived: a strong belief that weights are small (small τ) is a large λ.

The bias-variance trade. A regularised model is biased towards simple answers; in exchange its fit varies less from one training sample to the next. That buys most when data are scarce relative to the model. The chart measures it on real data: ten baseline measurements of 442 diabetes patients and their disease progression a year later (Efron et al. 2004).

Predict, then drag: with 40 training patients the best penalty cuts held-out error by about a seventh against plain least squares. With 400 patients, will it cut more or less? Move m.

The answer: the best ridge fit is 49% below least squares at m = 20, 14.6% at 40, 3.2% at 100, and under 1% from 200 patients on computed by this chart. Ten coefficients and 400 patients leave little variance to remove.

A penalty pays when data are scarce, and almost nothing when they are not

lassoridgeelastic net, ρ = 0.5no penalty (least squares)

Each curve is the mean squared error on the held-out patients over 40 random splits: fit on m patients (standardised with their own statistics), test on the other 442 − m. Splits come from a seeded generator (seeds 1 to 40), the same for every method and λ; one split's held-out error was checked against scikit-learn to 10−8 (recompute.py). Left of the minimum the fit varies too much (variance); right of it, it is too simple (bias). The best λ is read off the test curves for display; in practice it is chosen by cross-validation inside the training data.

The split, exactly. A trained model is an estimator too (the same bias-plus-variance split that Statistics for ML, section 1, makes for a single number): the training set is a random sample, so the fitted fˆ\hat f is a random function. For squared error with target y=f(x)+εy = f(x) + \varepsilon (noise mean 0, variance σ2\sigma^2), averaging over training sets,

𝔼[(fˆ(x)−y)2]=(𝔼[fˆ(x)]−f(x))2⏟bias2+𝔼[(fˆ(x)−𝔼[fˆ(x)])2]⏟variance+σ2⏟irreducible.\mathbb{E}\big[(\hat{f}(x) - y)^2\big] = \underbrace{\big(\mathbb{E}[\hat{f}(x)] - f(x)\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{E}\big[(\hat{f}(x) - \mathbb{E}[\hat{f}(x)])^2\big]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{irreducible}}.

Bias² is what the model family gets wrong on average; variance is how much the prediction scatters between training sets; σ2\sigma^2 is noise no model can remove. The classic picture: as capacity grows, bias falls and variance rises, so test error traces a U (section 8 shows where that picture breaks). Every regulariser on this page trades bias for variance; two model choices act on one term each. Ensembling attacks variance: averaging MM models whose errors have variance σ2\sigma^2 and pairwise correlation ρ\rho gives ρσ2+(1−ρ)σ2/M\rho\sigma^2 + (1 - \rho)\sigma^2/M (Hastie, Tibshirani and Friedman, The Elements of Statistical Learning, 2nd ed., eq. 15.1). With M=10M = 10: 0.1σ20.1\sigma^2 for independent errors but 0.55σ20.55\sigma^2 at ρ=0.5\rho = 0.5, so correlation sets the floor, which is why random forests decorrelate their trees (and why dropout's implicit ensemble, section 4, helps). Boosting attacks bias: each new weak learner fits what the ensemble still gets wrong.

Derivation of the decomposition (depth)
  1. Write f‾=𝔼[fˆ(x)]\bar f = \mathbb{E}[\hat f(x)] and split fˆ−y=(fˆ−f‾)+(f‾−f)−ε\hat f - y = (\hat f - \bar f) + (\bar f - f) - \varepsilon.
  2. Square: three squares plus three cross terms, 2(fˆ−f‾)(f‾−f)2(\hat f - \bar f)(\bar f - f), −2(fˆ−f‾)ε-2(\hat f - \bar f)\varepsilon and −2(f‾−f)ε-2(\bar f - f)\varepsilon.
  3. Each cross term has a factor with mean zero: 𝔼[fˆ−f‾]=0\mathbb{E}[\hat f - \bar f] = 0 by definition, and 𝔼[ε]=0\mathbb{E}[\varepsilon] = 0 with the test noise independent of the training set that made fˆ\hat f; (f‾−f)(\bar f - f) is fixed. All three vanish; the squares give variance, bias² and σ2\sigma^2.

2 · Penalties: L1, L2 and elastic net

Why L1 gives exact zeros. In the constraint view the fit is the first point where the growing ellipses of equal training error touch the allowed region. The L2 region is a circle, with no corners, so the touching point is almost never on an axis. The L1 region is a diamond whose corners sit on the axes, and an ellipse arriving from most directions meets a corner first: at a corner, one coefficient is exactly 0.

Fig. 2, step by step

  1. Training error is a bowl. Over the coefficients of bmi and bp (correlated at 0.40; all 442 patients, standardised to unit length), the training error is a quadratic bowl. Its bottom is least squares, (790, 402): with no penalty the fit sits there.
  2. One level of error is an ellipse. Accept a training error +36.1% above least squares: the coefficient pairs with exactly that error form a gold ring round the bowl, an ellipse on the floor. Both penalties below pick their fit on this ring, so only the shape of the penalty decides where.
  3. L2: the budget is a disc. Ridge allows only b12 + b22 ≤ r2, a glass column over a disc. The lowest point of the bowl inside it is on its wall, where the ring touches the disc: (184, 132) at λ = 0.009. The dots follow the ridge path from least squares; neither coefficient is 0.
  4. L1: the budget is a diamond. The lasso allows |b1| + |b2| ≤ t, a prism whose corners sit on the axes. At the same training error the lowest allowed point is the corner on the bmi axis, (290, 0) at λ = 1.491: bp is exactly 0.
  5. From above: the textbook picture. The same two fits on the one ellipse: the disc touches it off the axes, the diamond at its corner.
  6. Shrink the budget: the paths. As λ grows, ridge pulls both coefficients towards 0 along a curve and reaches an axis only at b = 0; the lasso moves in a straight line until bp leaves the model at λ = 1.270 with bmi at 388, then slides along the bmi axis to 0, reached at λ = 2.148.

Explore every method and both pairs: step the explorer with Lasso, then switch to Ridge. Each step allows a little more training error, the same for every method, so the grey dot (the other method) sits on the same ellipse as the fit: only the shape of the penalty decides where. Then switch the pair to s1 and s2, two cholesterol measures correlated at 0.90: the lasso keeps one and drops the other, ridge keeps both and pulls them towards each other. Early stopping runs plain gradient descent from 0 and stops it early; watch it trace the ridge path.

Real data: two of the ten diabetes variables, standardised to mean 0 and unit length, response centred. Each point is an exact fit: lasso by least angle regression, ridge in closed form, elastic net by coordinate descent, all checked against scikit-learn 1.9 to 10−7 or better (recompute.py). Penalty convention: (1/2n)‖y − Xb‖2 + λ(ρ‖b‖1 + (1 − ρ)/2 ‖b‖2), ρ = 1 lasso, 0 ridge, 0.5 elastic net. Early stopping: plain gradient descent on the same squared error from 0 with a small step η = n/(50λmax(XᵀX)), a hundredth of the largest stable step, stopped at the first step whose training error is at most the step's level. Each method's λ is found by bisection to match that level.

L1's corners put the fit on an axis; L2's circle never does

lasso regionridge regionelastic net regionellipse of equal training error through the fitthe other method, same training errorridge path (early stopping mode)

The same thing as a formula. For a quadratic loss with curvature H around its unregularised minimum w*, one weight's answer is (Goodfellow et al., eq. 7.13 and 7.23):

L1 (lasso)L2 (ridge)Elastic net
PenaltyλΣi|wi|λΣiwi2λ1‖w‖1 + λ2‖w‖22
Solution for one weightw = sign(w*) max(|w*| − λ/H, 0): soft-thresholding, exactly 0 whenever |w*| ≤ λ/Hw = H/(H + λ) · w*: a constant factor, never 0 unless w* issoft-threshold, then divide
Effect on weightssome exactly 0: sparse models, feature selectionall shrink, none to 0; steadies correlated featuressparse, and shares weight across correlated features
Differentiablenot at 0 (needs a subgradient or a proximal step)everywherenot at 0
PriorLaplaceGaussiana compromise between the two
Use whenfeature selection, interpretable modelsmulticollinearity, stabilising predictionsmany correlated features, or more features than examples

The solution row takes the penalty as λ|w| for L1 and (λ/2)w2 for L2.

Elastic net. Zou and Hastie added an L2 term to the lasso for three limits they list (2005, section 1): with more features than examples (p > n) the lasso selects at most n of them; from a group of highly correlated features it tends to select only one, and does not care which; and when n > p with high correlations, ridge predicts better than the lasso. The L2 part makes the penalty strictly convex, which gives the grouping effect: strongly correlated features get similar coefficients and enter or leave together.

Standardise first, and leave the intercept alone. The penalty treats all coefficients alike, so a feature measured in grams is penalised a thousand times less than the same feature in kilograms. Centre and scale every feature before fitting (the diabetes data here are scaled to unit length, as in Efron et al.'s equation 1.1), and do not penalise the intercept: centring the response removes it.

The same λ means different things in different libraries (conventions)

The page's convention is glmnet's and scikit-learn's Lasso and ElasticNet: (1/2n)‖y − Xb‖2 + λ(ρ‖b‖1 + (1 − ρ)/2 ‖b‖2), with scikit-learn calling λ alpha and ρ l1_ratio. scikit-learn's Ridge(alpha) instead minimises ‖y − Xb‖2 + alpha‖b‖2, with no 1/2n, so its alpha is nλ. The old form λ1‖w‖1 + λ2‖w‖2 maps to λρ and λ(1 − ρ)/2 after the same 1/2n scaling. A λ copied between conventions can be off by a factor of 2n.

All ten coefficients: the Coefficient paths tab shows every diabetes coefficient as λ grows under each penalty and reproduces Efron et al.'s Figure 1 numbers.

3 · Weight decay, and why AdamW decouples it

Weight decay pulls every weight a little towards 0 at each step. It can be implemented two ways:

  1. L2 in the loss: add (λ/2)‖w‖2 to the objective. The penalty enters the gradient as λw and then flows through the optimiser's machinery.
  2. Decoupled, in the optimiser: change the update rule itself, w ← w − ηλw, applied beside the gradient step.

For plain SGD the two coincide, up to rescaling λ by the learning rate (Loshchilov and Hutter 2017, Proposition 1). For Adam they do not: the L2 term is divided by the per-parameter √v̂ like the rest of the gradient, so weights with large, noisy gradients are barely decayed while weights with tiny gradients are pulled to 0 at full speed. Decoupling restores the same decay for every weight, and that is the whole of AdamW.

Predict: six weights get pure noise as their gradient, from tiny to large, so the only systematic force on them is the decay. Under Adam with L2, which end lowest, the quiet ones or the noisy ones? Fig. 3 runs both optimisers on the same noise.

Fig. 3, step by step

  1. Twelve weights at 1, the same noise twice. Front row Adam with L2 in the loss, back row AdamW; each column gets a gradient of pure noise, σ = 10−4 to 10 (labels on the floor). With no signal anywhere, the only systematic force is the decay, and the green glass sheet is what decay alone gives, (1 − ηλ)t.
  2. AdamW, steps 0 to 2,000. The decay is applied to the weight directly, outside Adam's rescaling, so all six sink with the sheet (0.82 by step 2,000; the six weights at 0.73 to 0.87); the noise only jiggles them around it.
  3. Adam with L2, steps 0 to 2,000. The term λw enters the gradient and is divided by √v̂ with everything else. Where the noise is tiny, λw dominates the gradient, Adam normalises it to a full-size step, and the weight is driven to 0.02; where the noise is large, λw is drowned and the σ = 10 weight is still at 1.00. The dots show how fast each column is falling.
  4. Both rows at step 3,000. AdamW's six weights sit at 0.70 to 0.81, around decay alone (0.74); Adam with L2 has sent the three quietest to about 0 and left the loudest at 0.97.

Adam with β = (0.9, 0.999), ε = 10−8, learning rate 10−3, λ = 0.1, 3,000 steps; gradients are seeded Gaussian noise with the standard deviation under each bar illustrative. At step 2,000 Adam with L2 has driven the three quietest weights to 0.02, where decay alone leaves 0.82; the σ = 10 weight is still at 1.00. Matches torch.optim.Adam and AdamW (torch 2.14.1, float64) to 10−14 (check_wd.py).

What λ multiplies. In Loshchilov and Hutter's Algorithm 2 the decay step is ηtλθ, where ηt is the schedule multiplier and not the base learning rate α, so decay and learning rate are tuned independently. PyTorch's AdamW applies θ ← θ − γλθ with γ the learning rate itself (PyTorch 2.14 docs; default λ = 0.01). So weight_decay=0.1 at a learning rate of 3 × 10−4 shrinks each weight by 3 × 10−5 of itself per step derived: γλ, and halving the learning rate halves the decay too. The paper's λ is PyTorch's λ times α.

Which parameters. Decay is usually applied to weight matrices only. nanoGPT decays every parameter with two or more dimensions (matrix weights and embeddings) and leaves biases and LayerNorm gains alone (model.py, configure_optimizers), with λ = 0.1 (train.py). Decaying a normalisation gain pulls it towards 0 and fights the normalisation it belongs to.

Typical values. AlexNet used SGD with weight decay 0.0005 and found "this small amount of weight decay was important for the model to learn. In other words, weight decay here is not merely a regularizer: it reduces the model's training error" (Krizhevsky et al. 2012, section 5). With AdamW, 0.1 is the usual pretraining value: GPT-3 (paper page), ViT (paper page); BERT used L2 weight decay 0.01 (paper page).

Why decay at all if an LLM never overfits? A model that sees most of its data once has little to overfit, yet nearly every LLM recipe keeps weight decay. D'Angelo, Andriushchenko et al. argue that in both regimes "weight decay is never useful as an explicit regularizer but instead changes the training dynamics in a desirable way": with multi-epoch SGD on vision tasks it strengthens SGD's implicit regularisation, and in near one-epoch LLM training it balances the bias-variance trade-off of stochastic optimisation, giving lower training loss and more stable training (NeurIPS 2024, abstract). AlexNet's authors saw the same in 2012: decay lowered the training error.

4 · Dropout

In each training step every unit is dropped independently at random: its output is 0 for that step, with all its incoming and outgoing connections. No unit can rely on one specific partner (co-adaptation), so the network learns redundant, robust features. A network with n units contains 2n possible thinned networks sharing one set of weights, and each training case trains a freshly sampled one: dropout trains an implicit ensemble (Srivastava et al. 2014, section 1). At test time there are three ways to use it: the single weight-scaled network (with inverted dropout, the plain forward pass), the arithmetic mean of k sampled thinned networks (Srivastava et al.'s Monte Carlo average), or their geometric mean, which AlexNet's authors said weight scaling approximates.

Fig. 4, step by step

  1. The full network. Test digit 242, labelled 4: its 64 pixels (grey columns, height is brightness), two hidden layers of 96 ReLU units (height is activation) and 10 outputs. With nothing dropped (the weight-scaled network, a plain forward pass under inverted dropout) it says 4 at 32%: an ambiguous digit.
  2. Thinned network 1. One mask: 52 of 64 pixels and 47 and 40 of the 96 units survive (flat grey tiles are dropped), and the dots flow only through survivors. This subnetwork says 1 (38%).
  3. Thinned network 2. A fresh mask is a different network with the same weights (50, 39 and 52 kept); it says 9 (30%).
  4. Thinned network 3. Another (54, 42, 40 kept) says 7 (59%). In training, every example meets a freshly sampled one.
  5. The average of 30. Averaging the outputs of 30 thinned networks gives 4 at 26%; the black marks are the weight-scaled network's single pass, close to the average. The votes are split: the most common single answer, 1, gets only 8 of 30. MC dropout reads that spread as uncertainty.

The hero's network, seed 0 with dropout: 64 inputs (8 × 8 pixels scaled to [0, 1]), two hidden layers of 96 ReLU units, 10 outputs; dropout keeping 0.8 of the inputs and 0.5 of each hidden layer (nn.Dropout(0.2) and nn.Dropout(0.5)), Adam at 10−3, batch 64, 300 epochs, on 1,437 of scikit-learn's 1,797 digits; the other 360 (stratified, fixed seed) are the test set. Weights stored as 8-bit integers with one scale per unit; the stored network's weight-scaled error is the same 1.39% offline and here. Thirty masks per digit, from a fixed seed.

Try any digit: the explorer runs the same 30 masks on six ambiguous and three clear test digits and opens on all 30 averaged; step back to see them one at a time. On a clear digit they all agree. The spread of the votes is what MC dropout uses as an uncertainty.

Each mask is a different network with its own opinion; their average lands on the weight-scaled answer

This thinned network
input, × = dropped pixel
hidden layer 1 (96 units, keep 0.5)
hidden layer 2 (96 units, keep 0.5)
Its prediction
Average of the thinned networks so far (black tick: weight-scaled network)
Votes so far
Corrected: the paper keeps about half the hidden units, not 0.8
An older version of this page said to keep about 0.8 of hidden units. Srivastava et al. write that the retention probability "can simply be set at 0.5, which seems to be close to optimal for a wide range of networks and tasks. For the input units, however, the optimal probability of retention is usually closer to 1 than to 0.5" (section 1). Their practical guide: "Typical values of p for hidden units are in the range 0.5 to 0.8. For input layers ... For real-valued inputs (image patches or speech frames), a typical value is 0.8" (Appendix A.4), and their MNIST runs use 0.5 for hidden units and 0.8 for inputs (sections 6.1 and 7.4). So: keep about 0.5 for hidden units, about 0.8 for inputs. On MNIST with the width fixed, test error was flat for retention between 0.4 and 0.8 and rose towards 1 (section 7.3, Figure 9a).
p means opposite things in the paper and in PyTorch
In Srivastava et al., p is the probability of keeping a unit. In PyTorch's nn.Dropout(p) it is the probability of dropping it (default 0.5), and Keras and most papers since follow the framework. The paper's "p = 0.8 for inputs" is nn.Dropout(0.2), and nn.Dropout(0.8) would keep only a fifth. Even the mixup paper's dropout experiments use the dropping convention (p ∈ {0.5, 0.7, 0.8, 0.9}; Zhang et al. 2018, section 3.4).

The factor 1/p goes either in training or at inference, never nowhere

activationscaled up by 1/p in trainingscaled down by p at inferencewhat a dropped unit would have sent

Train against inference: where the scaling goes

Training drops units; inference drops nothing. With every unit present a layer would send about 1/p times what the next layer saw in training, so the activations are rescaled to match the expected value: the original scheme multiplies them (equivalently the outgoing weights) by p at inference; inverted dropout, what frameworks do, divides the survivors by p in training, so inference is a plain forward pass. The two "are equivalent with appropriate scaling of the learning rate and weight initializations at each layer" (Srivastava et al., section 10).

Watch the inverted scheme, then switch to the original one: the numbers that reach the next layer are the same, only the place of the factor moves. Then switch to "Scaling forgotten" to see the bug; the counters under the chart carry this pass's numbers.

  1. The layer. 96 activations of the first hidden layer, from one real test digit; together they send their sum to the next layer.
  2. Draw a mask. Each unit is kept with probability p = 0.5, independently, a coin per unit (× marks the dropped ones).
  3. Drop. Dropped units output 0 for this pass and receive no gradient; the survivors send about half as much.
  4. Scale in training? Inverted dropout divides every survivor by p, so each doubles (green); the original scheme and the bug pass them through unchanged.
  5. One training pass. What this pass sends to the next layer. Every training step draws a fresh mask, so the next layer sees a different thinned network each time.
  6. Over 1,000 masks. The average of what the layer sends, against the exact expectation p × (sum of all activations) × (training scale): the size of input the next layer learned its weights for.
  7. Inference: nothing dropped. Every unit is present. Inverted dropout scales nothing, a plain forward pass; the original scheme multiplies the outputs by p = 0.5 (orange), the paper's "weights are multiplied by p at test time"; with the bug nothing is scaled because the training-side scaling never happened.
  8. Train and test agree, or not. With either scheme inference sends the training average: they differ only in where the factor sits. With the scaling forgotten, inference sends twice what the next layer saw in training. Frameworks build the scaling in, so the usual slip there is evaluating in train() mode, where dropout keeps firing.

The 96 bars are the real first-hidden-layer activations of the same network on one test digit; keep probability 0.5 for this layer, as it was trained. "Sent" is the plain sum of the layer's outputs; the mean over 1,000 masks uses a fixed seed. Exact expectation: p × (sum of all activations) × (training scale). Forgetting the factor sends inputs 2× larger than training ever saw.

How good the weight-scaled shortcut is. Averaging all 2n thinned networks is impossible; the weight-scaled network is the shortcut. On MNIST, Srivastava et al. found that "around k = 50, the Monte-Carlo method becomes as good as the approximate method" and thereafter slightly better, "well within one standard deviation" (section 7.5). AlexNet calls the shortcut "a reasonable approximation to taking the geometric mean of the predictive distributions" of the thinned networks (Krizhevsky et al. 2012, section 4.2). Gal and Ghahramani read dropout as approximate Bayesian inference and kept it on at test time to get uncertainty from the spread of the sampled predictions, "MC dropout" (2016).

Does not reproduce the k = 50 crossing on this network
Here weight scaling (1.39% test error) stays below the Monte Carlo average at every k tried, 1.90% at k = 200; the shape does reproduce (one thinned network alone errs on 10.65%, and the average improves quickly up to a few tens). A different network, dataset and test set from the paper's MNIST run.
Monte Carlo averaging against weight scaling, measured over all 360 test digits (chart, and a live re-run)
arithmetic mean of k thinned networks (band: lowest to highest of the repeats)geometric meanweight scaling, one passyour browser's run

Dropout on a linear model is ridge. For linear regression with each input kept with probability p, the expected loss is ‖y − pXw‖2 + p(1 − p)‖Γw‖2 with Γ = (diag(XᵀX))1/2: ridge with each weight's penalty scaled by its feature's spread, strength (1 − p)/p after absorbing p into w (Srivastava et al., section 9.1). On the diabetes data, whose columns have unit length so Γ = I, input dropout with keep 0.8 is ridge with alpha = 0.25: averaged over 4,000 random masks, the fitted coefficients match scikit-learn's ridge to within 0.3% of the largest coefficient measured (recompute.py).

Variants

  • Stochastic depth drops whole residual blocks instead of units, with a survival probability falling linearly from 1 at the input to pL = 0.5 at the last block (Huang et al. 2016); a dropped block passes its input through the skip connection, so the network is shallower for that step. Vision Transformers call it drop-path. In CutMix's ImageNet comparison it took ResNet-50 from 23.68% to 22.46% top-1 error (section 7).
  • DropBlock drops contiguous regions of a convolutional feature map, because neighbouring activations are correlated and information still flows past single dropped units (Ghiasi et al. 2018, abstract); attention dropout drops attention weights.
  • Gaussian dropout multiplies activations by noise from N(1, σ2) with σ2 = (1 − p)/p, matching Bernoulli dropout's mean and variance with no scaling at test time; it worked "as well, or perhaps better" (Srivastava et al., section 10).
The 2014 practical guide, and dropout with BatchNorm (depth)
  • Width: if n units are right without dropout, use at least n/p with it (Appendix A.1).
  • Learning rate and momentum: dropout makes gradients noisy, so the paper used 10 to 100 times the usual learning rate, or momentum 0.95 to 0.99 instead of 0.9 (A.2), with max-norm constraints (each unit's incoming weight vector capped at a norm c of 3 to 4) to stop the weights blowing up (A.3). On MNIST, dropout with max-norm gave 1.05% error against 1.62% for L2 alone (Table 9, section 7).
  • With BatchNorm: dropout shifts a unit's variance between training and test, while BatchNorm keeps the running variance it measured in training; when dropout sits before a BatchNorm layer this "variance shift" makes the pair worse than either alone; one of Li et al.'s remedies is to apply dropout only after the last BatchNorm layer (Li et al. 2018, abstract and Table 4). BatchNorm also regularises a little by itself, through the noise of its batch statistics, "in some cases eliminating the need for Dropout" (Ioffe and Szegedy 2015, abstract; more on Normalisation and initialisation).

5 · Data augmentation, mixup and CutMix

Data augmentation applies random but realistic transforms (flips, rotations, crops, colour shifts, noise) that do not change the label, which enlarges and diversifies the training set: it attacks overfitting at the data level, and is the highest-leverage fix where it is possible. A transform is only an augmentation if it preserves the label, and that depends on the task: a horizontal flip is fine for photographs of cats and wrong for digits, where a flipped 2 is not a 2.

Mixup trains on blends of two random training examples and their one-hot labels, x̃ = λxi + (1 − λ)xj, ỹ = λyi + (1 − λ)yj, with λ drawn from Beta(α, α); α → 0 recovers ordinary training. CutMix pastes a random rectangle of one image into another and mixes the labels in proportion to the area (Yun et al. 2019); Cutout blanks a random square with no label change (DeVries and Taylor 2017).

Try: pick a real 8 × 8 digit and a transform; for mixup, a second digit and λ. The label row shows what the network is trained to predict. Predict first: is the horizontal flip an augmentation for digits?

Digits: scikit-learn's copy of the UCI optical digits (8 × 8, 17 grey levels), the test digits of the hero's network. Transforms are computed here: integer shifts of one pixel, rotation by up to 15° with bilinear resampling, Gaussian noise, a 3 × 3 cutout, mixup and CutMix with the label weights the papers use (CutMix: the pasted area's share).

Each transform keeps the label, changes it on purpose, or breaks it

What they bought. On ImageNet, mixup with α between 0.1 and 0.4 helped and larger α underfitted; ResNet-50's top-1 error fell from 23.5% to 23.3% at 90 epochs and from 23.6% to 22.1% at 200 epochs, bigger models and longer runs gaining most (Zhang et al. 2018, section 3.1 and Table 1).

AlexNet's augmentation, its cost, and searched policies (depth)

AlexNet's random 224 × 224 crops and their horizontal reflections from 256 × 256 images "increases the size of our training set by a factor of 2048" (with highly dependent examples), and without them "our network suffers from substantial overfitting"; random shifts of colour along the principal components of the RGB values "reduces the top-1 error rate by over 1%" (Krizhevsky et al. 2012, section 4.1). AlexNet computed its crops on the CPU while the GPU trained, so they cost nothing. Later work searched the space of transforms automatically: RandAugment, with two parameters, matched AutoAugment's searched policy on ImageNet, 77.6% top-1 for ResNet-50 against 76.3% for the standard baseline (Cubuk et al. 2019, Table 3).

Label smoothing is the target-side relative: train against (1 − ε) on the true class and ε spread over the rest, which caps how confident the model becomes. Its formulas, its two conventions, its effect on calibration and why it hurts distillation are on Loss functions; the parent's Training lab has the preset "Label smoothing caps overconfidence". As a regulariser of accuracy its record is mixed: on CIFAR-100 with PyramidNet-200 it raised top-1 error from 16.45% to 16.73% on its own, and helped only combined with Cutout or DropBlock (Yun et al., Table 5; section 7).

6 · Early stopping

Monitor the validation loss during training and stop before the model overfits: training loss keeps falling while validation loss traces an asymmetric U (Goodfellow et al., section 7.8 and Figure 7.3), as the hero's unregularised run does (lowest at epoch 60, 0.0974, then up to 0.1297 by epoch 300). In practice: evaluate every so often, keep the checkpoint with the best validation loss, and stop once it has not improved for a set number of evaluations (the patience). It is free, and it composes with everything else here. Two costs: it needs a validation set, and the data held out for it are not trained on; Goodfellow et al. describe retraining on all the data for the number of steps early stopping found (Algorithm 7.2).

Why it regularises. Stopping gradient descent after τ steps of size ε keeps the weights near where they started. For a linear model with a quadratic loss, starting from 0, it is equivalent to L2 regularisation with α ≈ 1/(τε) (eq. 7.45): the number of steps plays the role of the inverse weight decay. The early-stopping mode of the explorer in section 2 shows it on real data: the gradient-descent iterates stay close to the ridge path, closest for the weakly correlated pair, and visibly apart for the two cholesterol measures correlated at 0.90, where the approximation's assumptions are stretched.

What it saves can be large. In mixup's corrupted-label experiments, with half the CIFAR-10 labels randomised, plain training reached 18.8% test error at its best epoch and ended at 44.6% (Zhang et al. 2018, Table 2; the "Corrupted labels" view in section 7). Recorded runs are on the parent page: When training goes wrong → "Train falls, validation rises" (300 digit images with 30% of labels wrong, best validation step marked), and the Training lab's preset "Early stopping keeps the best validation loss", which also shows the gap between stopping and rolling back to the best checkpoint.

7 · What each buys, measured

Published comparisons that ran several regularisers on one model, one dataset and one recipe. Pick a study; bars are the change in test error against the study's own baseline run (the dashed line), so a bar to the left is a gain.

Augmentation and mixing buy whole points; weight decay and label smoothing alone, tenths or nothing

How to read these
Each study is one run per setting, so differences of a few tenths of a point are within noise. CutMix's tables are its authors' re-runs of the rival methods (except the rows marked *, taken from the original papers), in a study written to show CutMix winning. Gains do not add: Cutout plus label smoothing beat either alone on CIFAR-100, while on CIFAR-10 weight decay added nothing to random crops for Inception.
The values behind the chart (transcribed from the papers' tables)
  • MNIST, dropout paper (Srivastava et al. 2014, Table 9; 784-1024-1024-2048-10 ReLU network): L2 1.62%, L2 + L1 towards the end 1.60%, L2 + KL-sparsity 1.55%, max-norm 1.35%, dropout + L2 1.25%, dropout + max-norm 1.05%.
  • CIFAR-10, Inception (Zhang et al. 2017, Table 1; 100% training accuracy in every row): test accuracy 85.75% with neither, 86.03% weight decay only, 89.31% random crops only, 89.05% both. Augmentation buys about 3.5 points; weight decay at most 0.3.
  • ImageNet, ResNet-50 (Yun et al. 2019, Table 3; 300 epochs): baseline 23.68%, Cutout 22.93%, Mixup 22.58%, Manifold Mixup 22.50%, stochastic depth 22.46%, DropBlock* 21.87%, Feature CutMix 21.80%, CutMix 21.40% top-1 error.
  • CIFAR-100, PyramidNet-200 (Yun et al., Table 5): baseline 16.45%, label smoothing 16.73%, Cutout 16.53%, Mixup (α = 1.0) 15.63%, Cutout + label smoothing 15.61%, DropBlock + label smoothing 15.16%, ShakeDrop 15.08%, CutMix 14.47%, CutMix + ShakeDrop 13.81%.
  • Corrupted labels, CIFAR-10 (Zhang et al. 2018, Table 2; PreAct ResNet-18, 200 epochs; best epoch / last epoch): 20% wrong, plain 12.7 / 16.6, mixup + dropout 6.2 / 6.2; 50% wrong, plain 18.8 / 44.6, mixup + dropout 10.9 / 10.9; 80% wrong, plain 36.5 / 73.9, mixup + dropout 24.0 / 24.8. Dropout rates there are drop probabilities (0.7 at 20%, 0.8 at 50% and 80%).

8 · Regularisation in networks that can memorise everything

Zhang et al. trained standard image networks on CIFAR-10 with the labels replaced by random ones. Every network still fitted them, 99.3% to 100% training accuracy with test accuracy at chance, about 10% (Zhang et al. 2017, Table 1). Explicit regularisers did not stop it: with weight decay on, Inception and both MLPs still fitted random labels (99.2% to 100%), and so did Inception with random crops or augmentation, given more epochs; only AlexNet with weight decay failed to converge (Appendix, Table 4). Their conclusion: explicit regularisation "may improve generalization performance, but is neither necessary nor by itself sufficient for controlling generalization error", and the architecture and SGD itself regularise implicitly.

Double descent. Classical intuition says test error rises steadily once a model has more parameters than examples. For many models it instead peaks at the interpolation threshold, where the model can just barely fit the training set, then falls again; well-tuned L2 regularisation removes the peak. Nakkiran et al. prove it for isotropic linear regression and show it for random-feature models and CNNs (2020, abstract and section 5.2). Their random ReLU features experiment, repeated here on the digits at a smaller size, reproduces both the peak and its removal.

Predict: with 200 training images, at what number of random features does the unregularised test error peak? Then compare the curves.

toy Random ReLU features x̃ = ReLU(Wx), Wij ~ N(0, 1/d), pixels scaled to [−1, 1], one-hot targets, least squares (1/n)‖Φb − Y‖2 + λ‖b‖2; λ = 0 is the minimum-norm solution. The unregularised peak is at 210 features (test MSE 41.5); the best-λ curve has no peak. Nakkiran et al. used Fashion-MNIST (d = 784) and n = 500; here scikit-learn's digits (d = 64), n = 200 training images, the other 1,597 for testing, mean of 10 seeds (features and training images redrawn). "Best λ" picks, at each width, the λ of this grid with the lowest mean test squared error (on the test images, as their optimal curves do); the classification view uses the same λ. double_descent.py.

Without a penalty, test error peaks where features just outnumber the 200 images; the best λ flattens it

Which term makes the peak. Belkin et al. (PNAS 2019, arXiv 1812.11118): "This 'double descent' curve subsumes the textbook U-shaped bias-variance trade-off curve by showing how increasing model capacity beyond the point of interpolation results in improved performance." The smallest setting where this can be checked against an exact formula is Belkin, Hsu and Xu's weak-features regression (SIAM J. Math. Data Science 2020, arXiv 1903.07571): 100 independent Gaussian features, a target linear in all 100 plus noise (σ=0.2\sigma = 0.2, ‖β‖=1\lVert\beta\rVert = 1), a model that sees only the first pp features, fitted by least squares on n=40n = 40 examples (the minimum-norm solution once p>40p > 40, which is what gradient descent from zero finds). We refitted it on 1,000 independent training sets for every pp from 1 to 100 and split the test error into bias² and variance (section 1) simulated (with Gaussian inputs a fit's test error is exact, ‖wˆ−β1..p‖2+‖βp+1..D‖2+σ2\lVert\hat w - \beta_{1..p}\rVert^2 + \lVert\beta_{p+1..D}\rVert^2 + \sigma^2); against the paper's closed-form Theorem 1 (excerpt in src/inputs/) our averages reproduce it independently to within 3.2% everywhere at least 5 features from the threshold. At p=39,40,41p = 39, 40, 41 the theorem's expectation is infinite, and our average there is dominated by a few near-singular training sets.

Predict, then drag: at the threshold p=40p = 40, is the spike in bias² or in variance? Then raise λ.

Switch the signal: whether the second descent beats the first depends on the problem, and tuned ridge makes the curve monotonic.

Median over the 1,000 training sets of the smallest singular value of the 40×p40 \times p training inputs: 0.086 at p=40p = 40 against 3.55 at p=10p = 10 and 3.95 at p=100p = 100. Least squares divides the noise by these singular values (Linear algebra for ML owns the SVD), so at p=np = n (a square random matrix) the fit amplifies noise without limit; this is one of the three factors in Schaeffer et al., "Double Descent Demystified" (arXiv 2303.14151). Past the threshold the minimum-norm solution spreads the weight over many directions and variance falls again. Ridge adds λ\lambda to the squared singular values, which caps the amplification: λ=0.1\lambda = 0.1 cuts the error at p=40p = 40 from about 285,600 to 6.8. With λ=0\lambda = 0 the circles are Theorem 1, exact. weak_features_dd.py.

Variance, not bias, makes the peak, and a little ridge removes it

Why the peak: the smallest singular value of the training matrix collapses at p=np = n

Which descent wins, tuned ridge, and when more data hurts (depth)

Selecting features in order of decreasing βj2\beta_j^2, as the two decaying signals do, is the paper's "prescient" selection model (its Figure 2).

With the signal spread evenly the best error is at p=100p = 100 (0.667, against 1.057 at best below the threshold); when the first features carry most of the signal, the classic sweet spot wins (0.119 at p=14p = 14 against 0.440). Nakkiran et al. (arXiv 2003.01897) prove that "optimally-tuned ℓ2\ell_2 regularization achieves monotonic test performance as we grow either the sample size or the model size" in this kind of setting. More data can hurt: the same formula at fixed p=60p = 60 with the signal spread evenly gives 1.195 at 30 examples, 6.54 at 55 (near the threshold n=pn = p), 1.83 at 80 and only 0.63 at 200. Nakkiran et al. ("Deep Double Descent", arXiv 1912.02292) found the same in deep networks: "increasing (even quadrupling) the number of train samples actually hurts test performance" in some regimes, and "double descent occurs not just as a function of model size, but also as a function of the number of training epochs".

Checked against the papers
The old notes said "the decomposition still holds; the variance term just behaves non-monotonically". The decomposition is an identity, so it always holds, and in this linear run the variance is indeed what spikes. But as an explanation of double descent in deep networks that sentence is a simplification: Yang et al. (ICML 2020, arXiv 2002.11328) measure that "the bias is monotonically decreasing as in the classical theory, the variance is unimodal or bell-shaped" with width, Nakkiran et al. show epoch-wise and sample-wise versions and propose an "effective model complexity", and no single mechanism is agreed for deep networks (unconfirmed as a single cause).

Grokking. On small algorithmic datasets (modular arithmetic tables), Power et al. saw networks fit the training set early and then, long after, jump from chance to perfect validation accuracy; of the interventions they tried, "weight decay is particularly effective at improving generalization", more than halving the data needed (2022, sections 1 and 3).

9 · What large-model training still uses

A model that sees most of its data once has little opportunity to overfit, so LLM pretraining dropped dropout (PaLM, T5 1.1 and nanoGPT pretrain with none, where the 2017 Transformer and BERT used 0.1) but kept weight decay, 0.1 with AdamW in GPT-3, for its effect on the optimisation (section 3). Overfitting returns with repetition: fine-tuning on small datasets for several epochs is where dropout (0.1 in PaLM's fine-tuning), LoRA dropout (0.05 to 0.1 in QLoRA), early stopping on a validation set and data augmentation come back. Image classifiers, trained for many epochs on far fewer examples, are where augmentation, mixing and stochastic depth still earn whole points (section 7).

Model by model: dropout, weight decay and the rest, with sources (reference)
ModelDropoutWeight decay and otherSource
AlexNet (2012)0.5 in the first two fully connected layers; "roughly doubles the number of iterations required to converge"0.0005, SGD; crops, flips, colour shiftssections 4 and 5
Transformer (2017)0.1 on every sub-layer output and the embeddings; removing it cost 1.2 BLEUlabel smoothing 0.1paper page
BERT (2018)0.1 on all layersL2 weight decay 0.01paper page
GPT-3 (2020), ViT (2020)0.1 with AdamWGPT-3, ViT
T5 1.1none in pretraining (T5 itself used 0.1)paper page
Switch Transformer (2021)fine-tuning: 0.1 outside the experts and 0.4 inside them worked best; raising it everywhere hurtpaper page
PaLM (2022)"trained without dropout, although dropout of 0.1 is used for finetuning in most cases"section 5
nanoGPT"for pretraining 0 is good, for finetuning try 0.1+"0.1 on matrices and embeddings onlytrain.py
QLoRA (2023)LoRA dropout 0.1 up to 13B parameters, 0.05 abovepaper page
DDPM (2020)0.1 on CIFAR-10, where samples without it showed overfitting artefacts; 0 on the other datasetspaper page

10 · Mistakes that the sections above do not show

Evaluating with dropout or BatchNorm still in training mode
In PyTorch, dropout and BatchNorm behave differently under model.train() and model.eval(). Evaluating in training mode drops units at random and gives noisy, worse numbers; forgetting the inference-side correction in a hand-written scheme gives inputs 1/p times larger than training ever saw (the "Scaling forgotten" mode in section 4).
Adam's weight_decay argument is L2, not decoupled decay
torch.optim.Adam(weight_decay=...) adds λw to the gradient, which Adam then rescales per parameter (section 3). Use AdamW for decoupled decay, with weight matrices in one parameter group and biases, LayerNorm and RMSNorm gains in another with no decay, as nanoGPT does.
Copying λ between libraries or learning rates
scikit-learn's Ridge alpha is n times its Lasso alpha for the same penalty; PyTorch's AdamW decay per step is learning rate × λ, so a λ tuned at one learning rate is a different decay at another (sections 2 and 3).
Standardising with statistics from the whole dataset
L1 and L2 penalties depend on each feature's units, so features must be standardised; but compute the means and scales on the training split only, then apply the same transform to validation and test data, as the held-out chart in section 1 does.
Choosing λ, patience or the stopping step on the test set
Every regularisation knob is a hyperparameter; tuning it on the test set leaks it. Use a validation set or cross-validation. (The "best λ" curves in sections 1 and 8 are chosen on their test data, as in the paper they follow, and labelled so.)
An augmentation that changes the label
Flipping digits or text, rotating a 6 into a 9, cropping out the object: the transform must preserve the label for the task at hand. Mixup and CutMix change the label on purpose, and say by how much.
Regularising a model that is underfitting
If training loss is itself high, more regularisation makes it worse. Check the training curve first; the parent's When training goes wrong tab starts from the symptom.