Overfitting & Regularisation

Watch a model memorise noise, then fix it. Compare training and validation error, see bias and variance, add data, apply L1 and L2 penalties and run k-fold cross-validation step by step.

fits every pointthe real pattern (dashed)

1Memorising isn't learning

A flexible enough model can pass through every training point, noise and all. It scores perfectly on what it has seen and wildly wrong in between and beyond.

sweet spottrainingnew datamore flexible →error

2Training error lies

As a model gets more flexible, its error on the training data only goes down. Its error on new data falls, then rises again. The sweet spot is at the bottom of that U.

beforeafter

3Regularisation calms it down

Charge the model for large weights and the wild swings cost too much to keep. The curve smooths out toward the real pattern, even though it is just as flexible as before.

Start here

Underfitting, a good fit, overfitting

Fifteen training points, measured with noise from a smooth curve (dashed). We fit polynomials: degree 1 is a straight line, and each extra degree lets the curve bend once more. The goal isn't to hit the training points. It's to predict new points from the same curve. Turn on the validation points (fresh data the model never trains on) to see how each fit really does.

00.250.50.751-101
training pointsdegree-3 fitthe real curve
3
Validation points
Training error
0.020
Validation error
0.058

About right: it follows the real pattern and ignores most of the noise. Validation error is near its lowest.

Errors are mean squared error. The noise alone costs 0.04, so no model can reliably beat about 0.04 on new data.

The central picture

Training error lies, validation error doesn't

Every degree from 0 to 14, on a log scale. Training error can only go down as the model gets more flexible: at degree 14 there are 15 coefficients for 15 points, and it passes through every one (error 0). Validation error falls, bottoms out, then explodes. Choose the model at the bottom of the validation curve, never by training error.

0.00010.0010.010.11101001,00010,00001234567891011121314polynomial degreenoise floor
training errorvalidation errornoise floor (0.04)

The dashed marker follows the degree slider above.

Two ways to be wrong

Bias and variance

Imagine collecting the 15 points again, and again: 20 different training sets from the same curve. Fit the same degree to each (thin violet lines). Bias is how far their average (thick amber) is from the truth: being wrong in the same way every time. Variance is how much they disagree with each other: being wrong in a different way every time. Expected error on new data is bias² + variance + noise.

00.250.50.751-101
one fit per training settheir averagethe real curve
Degree
Bias²
0.004
Variance
0.008
Noise
0.040

The fits hug the truth and mostly agree. Both bias and variance are small: the sweet spot.

More flexibility trades bias for variance. The best model balances the two.

The best cure

More data

Overfitting is a flexible model with too little data to pin it down. Keep the degree-12 model and give it more points. With 15 it can almost thread every point; with a few hundred, the noise averages out and there's nothing left for the wiggles to grab.

00.250.50.751-101
15
Training error
0.010
Validation error
107

Notice the training error goes up as data is added: it's harder to memorise 200 points than 15. That's healthy. The two errors meeting near the noise floor is what a well-fitted model looks like.

When more data isn't available, the next sections are the alternatives.

Keep the model, tame it

Regularisation: a price on big weights

Back to 15 points and degree 12. The wild curve needs huge weights that cancel each other out. Regularisation adds their size to the loss, so the model only keeps a big weight if it really pays for itself. L2 (ridge) charges λ·Σw² and shrinks all weights smoothly. L1 (lasso) charges λ·Σ|w| and sets many of them to exactly 0, which also picks features for you.

00.250.50.751-101

The 13 weights (log scale; w₀ is the intercept and is never penalised)

-0.60.4-4.3-3772225-338-575744664-787-284321
w0w1w2w3w4w5w6w7w8w9w10w11w12
Penalty
0
Train error
0.002
Validation
1.482
Zero weights
0
0.010.1110100010⁻⁶10⁻⁴10⁻²1.0100validation error by λnoise floor

No penalty: the weights run into the hundreds and the curve swings off the chart.

Watch it choose

Cross-validation: choosing without cheating

One validation set wastes data and can be lucky or unlucky. k-fold cross-validation splits the data into 5 folds; each fold takes a turn as the validation set while the model trains on the rest. Average the 5 scores and every point has been used for both training and checking. Step through it choosing the degree for 20 points.

Each cell is one point, coloured by its fold.

00.250.50.751-101

Points are coloured by fold. Enlarged: the held-out fold, which the curve was trained without.

degree12345average
1
2
3
5
8
12
Step 0 / 38
600 ms

Press Start to run 5-fold cross-validation over 6 degrees: 30 fits in all.

And keep a separate test set locked away until the very end. Once you've used data to choose anything, its score is no longer an honest estimate.

The toolbox

Other ways to fight overfitting

Early stopping

Train while watching validation loss, and stop (keeping the best weights) when it starts rising. Cheap and used almost everywhere in deep learning.

Dropout

During training, randomly switch off a fraction of a neural network's neurons each step, so no neuron can rely on any one other. Turned off when predicting. Neural Network →

Data augmentation

Make more training data from what you have: flip, crop and recolour images, or paraphrase text. The model sees variety, not repeats.

A simpler model

Fewer features, a lower degree, a shallower tree. If a simple model does as well on validation, prefer it. Decision Tree →

Ensembles

Average many models that overfit in different ways and their errors partly cancel: the variance drops. Random Forest →

Watch the right numbers

Accuracy can hide problems. On imbalanced data, judge validation results by precision, recall or AUC. Evaluation Metrics →

No magic, just arithmetic

The maths, step by step

The smallest possible model: one weight, prediction = w × x, and two points (1, 2) and (2, 3.5). It's too small to overfit, but it shows exactly what the penalty does to a weight.

  1. 1

    Add a price for big weights

    Ridge (L2) regularisation adds λ × w² to the usual squared error. λ (lambda) sets how expensive large weights are.

    loss(w) = Σ (w × x − y)² + λ × w²

  2. 2

    Solve for the best weight

    Set the derivative to zero. λ ends up in the denominator, so a bigger λ means a smaller weight.

    d loss / dw = 2 Σ (w x − y) x + 2 λ w = 0  ⇒  w = Σxy ÷ (Σx² + λ)

    w (λ = 0) = 9 ÷ (5 + 0) = 1.8000

    w (λ = 1) = 9 ÷ (5 + 1) = 1.5000

    w (λ = 5) = 9 ÷ (5 + 5) = 0.9000

    Same data, same model: the penalty alone pulls the weight toward 0. With many weights, that is what flattens the wiggles.

  3. 3

    Or: weight decay, in gradient descent

    The penalty's gradient is 2λw. Subtracting it every step shrinks the weight by a fixed fraction before the usual update.

    data gradient at w = 1.8 = 2 Σ (w x − y) x = 0.0000

    w = (1 − 2ηλ) × w − η × data gradient = (1 − 2 × 0.05 × 1) × 1.8 − 0.05 × 0.0000 = 1.6200

    At w = 1.8 the data are happy (gradient 0), but the decay still pulls it down, toward the ridge answer 1.50. Neural network libraries call this weight decay.

  4. 4

    L1 pushes to exactly zero

    Lasso (L1) charges λ × |w| instead. Its pull is the same size however small w gets, so small weights are pushed all the way to 0 and stay there.

    loss(w) = Σ (w × x − y)² + λ × |w|

    pull from the penalty: λ × sign(w), the same at w = 5 as at w = 0.01

    L2's pull, 2λw, fades as w shrinks, so it makes weights small but almost never exactly 0.

Keep going

Resources

Hand-picked places to go deeper. They're all free to read or watch, and they open in a new tab.

How it works: Overfitting & Regularisation

Step by step

  • Training data
  • Validation data / average fit
  • Fitted curve

Press Start or Step: the step the animation is on lights up below.

  1. 1

    Split into folds

    Shuffle the data and deal it into k equal folds (here 5). Each fold will be held out once.

    folds = shuffle(data).split(k)
  2. 2

    Train on k − 1, score on the one left out

    For each candidate setting and each fold: fit on the other folds, measure error on the held-out fold, which the fit never saw.

    for f in folds: fit(data - f); score(f)
  3. 3

    Average the fold scores

    One number per candidate, using every point for validation exactly once. Big differences between folds mean high variance.

    cv_error = mean(scores)
  4. 4

    Pick the best and retrain on everything

    Choose the setting with the lowest average error, then fit it once on all the data. Report the final score on a separate test set.

    best = argmin(cv_error); fit(all data)

A model overfits when it learns the noise in its training data instead of the pattern behind it. Its training error looks excellent and its error on new data is poor. Underfitting is the opposite: the model is too simple to capture the pattern, so both errors are high.

Training error always falls as a model gets more flexible, so it can't tell you when to stop. Hold out data the model never trains on (a validation set, or k-fold cross-validation) and choose the model whose validation error is lowest. Keep a separate test set for the final, honest score.

The cures: more data; a simpler model; regularisation, which adds a penalty on weight size to the loss (L2 shrinks every weight, L1 sets many to zero); and, for neural networks, early stopping, dropout and data augmentation.

Where you'll meet it

  • Whenever you train any model: check training against validation error to tell underfitting (both high) from overfitting (a big gap).
  • Choosing settings such as polynomial degree, tree depth or the regularisation strength λ, by cross-validation.
  • Interview favourites: “what is the bias–variance trade-off?”, “how do you detect overfitting?”, “L1 vs L2?”, “why do we need a test set as well as a validation set?”.
time O(k × candidates × cost of one fit)space O(n)

k-fold cross-validation fits the model k times for every setting it tries, so it is k times as expensive as a single validation split. Ridge itself costs the same as ordinary least squares; lasso needs an iterative solver.