Search

Search papers and lessons

Overfitting

Level 3 · 12 min read

Overfitting is when a model learns the noise in its training data along with the signal, so it scores well on examples it has seen and poorly on new ones.

On this page

  • Colour = topic mix
  • Probability
  • Learning basics
  • Losses & regularization
  • Discrete math
  • Sign in to see your progress

TL;DR

A model is fitted to a finite sample, and that sample contains both the pattern we care about and random accidents specific to that sample. Overfitting is when the model spends its capacity on the accidents. Its training error keeps falling, but its error on new data stops falling and then rises. The difference between those two errors is the generalization gap, and keeping it small is most of the craft of machine learning.

Where you'll see it: when a deep network memorises its training set and fails on held-out images, when a decision tree grows until each leaf holds one example, and when a model tuned on a small validation set looks better than it is in production.

Intuition

Memorising the answer key

A student who memorises last year's exam answers scores perfectly on last year's exam. On this year's exam, with different questions testing the same material, the same student does badly. They did not learn the subject. They learned the answer key, including its typos and its particular wording.

A model has the same temptation. Given a training set, the most direct way to reduce training error is to store the examples and reproduce their labels. Real data is not only the underlying rule, though. Each measurement has noise: a sensor that reads slightly high, a label that a tired annotator got wrong, a photo with an unusual shadow. A model with enough flexibility can bend itself to pass through those accidents. The result fits the training set beautifully and generalises poorly, because the accidents do not repeat.

A curve through every point

Picture ten noisy points scattered around a gentle upward trend. A straight line misses some points a little, but it captures the trend. A polynomial of degree nine has ten coefficients, so it can pass through all ten points exactly. Between the points it swings wildly. Its training error is zero, and its predictions for new inputs are nonsense. The line is too simple to capture every wiggle, and the polynomial is too flexible to be trusted between the points. Both are wrong in different ways, and the job is to find the complexity in between.

012345600.10.20.30.40.50.6model complexityerror
  • training error
  • validation error
Training error keeps falling as complexity grows. Validation error falls, bottoms out near complexity 3.35, then climbs. The gap between the two curves is overfitting.

This is why we need the held-out data from Train, Validation and Test Sets. Training error alone cannot tell you whether a model has learned the rule or the noise. Only error on data the model did not see can.

The math

Setting up the problem

Suppose the data come from an unknown rule plus noise:

y=f(x)+ε,E[ε]=0,Var(ε)=σ2.y = f(\mathbf{x}) + \varepsilon, \qquad \mathbb{E}[\varepsilon] = 0, \quad \mathrm{Var}(\varepsilon) = \sigma^2.

Here x\mathbf{x} is an input, ff is the true rule we are trying to learn, yy is the observed output, and ε\varepsilon is random noise with variance σ2\sigma^2. Often the noise is taken to be Gaussian.

We pick a model f^\hat{f} from a family, for example linear functions or polynomials of a given degree, using a training set of nn examples. Under squared loss (see Loss Function and Mean Squared Error) there are two errors to compare.

The training error is the average loss on the examples used to fit the model:

Errtrain=1n∑i=1n(yi−f^(xi))2.\mathrm{Err}_{\text{train}} = \frac{1}{n} \sum_{i=1}^{n} \big(y_i - \hat{f}(\mathbf{x}_i)\big)^2.

The test error is the expected loss on a new example drawn from the same distribution, including new noise:

Errtest=E[(y0−f^(x0))2].\mathrm{Err}_{\text{test}} = \mathbb{E}\big[(y_0 - \hat{f}(\mathbf{x}_0))^2\big].

Overfitting is the situation where Errtrain\mathrm{Err}_{\text{train}} is much smaller than Errtest\mathrm{Err}_{\text{test}}. The generalization gap is their difference, Errtest−Errtrain\mathrm{Err}_{\text{test}} - \mathrm{Err}_{\text{train}}.

Why the training error is too optimistic

The training error is a biased estimate of test error for a simple reason. The model was chosen, and its parameters tuned, to make the training points fit. Part of what it fitted is the noise in those points, which will not repeat. So training error systematically understates test error.

For ordinary least squares with pp parameters (including any intercept) fitted on nn examples, when the model family contains the true rule, and when test error is measured at the same inputs with fresh noise, there is a clean expression for the typical size of this optimism. Write E\mathbb{E} for expectation over the noise. Then

E[Errtrain]=σ2(1−pn),E[Errtest]=σ2(1+pn).\mathbb{E}[\mathrm{Err}_{\text{train}}] = \sigma^2 \left(1 - \frac{p}{n}\right), \qquad \mathbb{E}[\mathrm{Err}_{\text{test}}] = \sigma^2 \left(1 + \frac{p}{n}\right).

The gap is therefore about 2σ2p/n2\sigma^2 p / n. Read it carefully. The optimism grows with the number of parameters pp and shrinks with the number of examples nn. A model with many parameters on little data memorises. A model with few parameters on lots of data barely overfits, because the gap scales with σ2\sigma^2 but is divided by nn.

Bias and variance

For a fixed test input x0\mathbf{x}_0, squared-error test risk splits into three terms. Averaging over possible training sets, the expected test error is

E[(y0−f^(x0))2]=(E[f^(x0)]−f(x0))2⏟bias2+E[(f^(x0)−E[f^(x0)])2]⏟variance+σ2⏟irreducible noise.\mathbb{E}\big[(y_0 - \hat{f}(\mathbf{x}_0))^2\big] = \underbrace{\big(\mathbb{E}[\hat{f}(\mathbf{x}_0)] - f(\mathbf{x}_0)\big)^2}_{\text{bias}^2} + \underbrace{\mathbb{E}\big[(\hat{f}(\mathbf{x}_0) - \mathbb{E}[\hat{f}(\mathbf{x}_0)])^2\big]}_{\text{variance}} + \underbrace{\sigma^2}_{\text{irreducible noise}}.

Bias is the error from the model family being too restrictive. Variance is how much the fitted model changes when the training sample is redrawn. A flexible model has low bias and high variance: it follows each training set closely, so different training sets give very different curves. Overfitting is the high-variance end of this trade. The full treatment lives in Bias-Variance Tradeoff.

Regularisation as a constraint

One standard response is to penalise complexity directly. Ridge or L2 regularisation minimises

∑i=1n(yi−w⊤xi)2+λ∥w∥22,\sum_{i=1}^{n} \big(y_i - \mathbf{w}^\top \mathbf{x}_i\big)^2 + \lambda \lVert \mathbf{w} \rVert_2^2,

where w\mathbf{w} is the weight vector, λ≥0\lambda \ge 0 controls the penalty, and ∥w∥22\lVert \mathbf{w} \rVert_2^2 is the squared length of the weights (see Vector Norm). Large λ\lambda shrinks the weights toward zero and makes the model smoother. Small λ\lambda recovers the unpenalised fit. In effect the penalty forbids the model from using extreme weights to chase individual points.

Worked examples

Example
Counting the gap for a small linear model

A linear model with p=5p = 5 parameters is fitted to n=20n = 20 examples. The noise has σ=2\sigma = 2, so σ2=4\sigma^2 = 4.

  1. Expected training error: σ2(1−p/n)=4×(1−5/20)=4×0.75=3.0\sigma^2 (1 - p/n) = 4 \times (1 - 5/20) = 4 \times 0.75 = 3.0.
  2. Expected test error: σ2(1+p/n)=4×1.25=5.0\sigma^2 (1 + p/n) = 4 \times 1.25 = 5.0.
  3. Gap: 5.0−3.0=2.05.0 - 3.0 = 2.0. Check with 2σ2p/n=2×4×5/20=2.02\sigma^2 p / n = 2 \times 4 \times 5 / 20 = 2.0. The two routes agree.
  4. Now increase the data to n=200n = 200 with the same five parameters. The gap becomes 2×4×5/200=0.22 \times 4 \times 5 / 200 = 0.2.

Interpretation: the same model that overfits noticeably on 20 examples barely overfits on 200. More data is the most reliable cure.

Example
The interpolating polynomial

We have n=10n = 10 points with distinct inputs. A polynomial of degree 9 has 10 coefficients.

  1. Lagrange interpolation shows that a unique degree-9 polynomial passes through all 10 points.
  2. So its training error is exactly 00.
  3. Between and beyond the training inputs, the polynomial can take values far from the true rule, because nothing constrains it there.
  4. Compare a degree-1 line. Its training error is larger, but it has two parameters, so the penalty p/n=0.2p/n = 0.2 on its gap is small.

Interpretation: zero training error is a warning sign when the parameters are at least as many as the examples. It is not evidence of a good model.

Example
Watching overfitting with a validation curve

Let xx be a complexity knob, such as polynomial degree or the number of boosting rounds. Suppose, for illustration, that the training error follows 0.5 e−0.5x0.5\,e^{-0.5x} and the validation error follows 0.5 e−0.5x+0.004 e0.8x0.5\,e^{-0.5x} + 0.004\,e^{0.8x}.

  1. At x=0x = 0: training error 0.5000.500, validation error 0.5040.504. The model is underfitting and both are high.
  2. At x=2x = 2: training error 0.1840.184, validation error 0.2040.204.
  3. At x=3.35x = 3.35: training error about 0.0940.094, validation error about 0.1520.152. Here the validation curve reaches its lowest point.
  4. At x=6x = 6: training error 0.0250.025, validation error about 0.5110.511. Training keeps improving while validation gets much worse.
  5. Stop around the validation minimum. Training further only widens the gap.

Interpretation: the correct model size is where the validation error bottoms out, not where the training error does.

Tradeoffs and failure modes

Overfitting is a cost that comes with flexibility, so the remedies all trade it against something else.

RemedyWhat it doesCost or risk
More dataLowers p/np/n, shrinking the gapOften expensive or impossible to obtain
Smaller modelReduces the number of parametersCan underfit if too small
L2 RegularizationPenalises large weightsNeeds λ\lambda tuned on validation data
Early StoppingStops training when validation error risesNeeds a validation set and a patience rule
DropoutRandomly disables units during trainingSlower training, more hyperparameters
Data AugmentationCreates plausible new examples from existing onesAugmentations must preserve the label
Ensemble Learning or BaggingAverages models trained on different samplesMore computation at training and prediction

Practical warnings:

  • Tuning on the validation set also overfits. Each comparison among many settings adds a little optimism. Keep a test set untouched for the final report.
  • Leakage looks like great generalisation. If training and test examples overlap or share a source, the gap disappears for the wrong reason.
  • Noise is not always white. Label noise, systematic measurement error and distribution shift all make a model fit something that will not repeat. Regularisation does not fix a bias in the data.

Modern deep learning complicates the classical picture. Very large networks often generalise well even though they can fit random labels perfectly, which was a central finding of Zhang and colleagues in 2016. Experiments also show a "double descent" in test error as model size grows past the point where it can interpolate the training data (Belkin and colleagues, 2018). The simple monotone story (more parameters, more overfitting) holds for many classical models but is not the whole picture for large neural networks. Treat the gap as something to measure, not a rule to assume.

History

The early theory was about shrinkage. In 1956 Charles Stein showed that the ordinary sample mean is inadmissible when estimating three or more means at once under squared error, and in 1961 Willard James and Stein gave an explicit estimator that does better by shrinking toward a common value. This was a striking result: a biased estimator can beat the unbiased one on average, because the variance it removes is worth more than the bias it adds.

Ridge regression, which adds the squared-weight penalty above, was proposed by Arthur Hoerl and Robert Kennard in 1970 as a way to stabilise regression when predictors are correlated. Vladimir Vapnik and Alexey Chervonenkis developed the theory of how the complexity of a model class controls the gap between training and test error in the 1970s, and their work underlies much of the modern theory of generalisation.

Deep learning made overfitting a daily concern again. The 2016 paper by Zhang and colleagues, which showed large networks can memorise random labels yet still generalise on real data, changed how researchers think about what capacity really means.

Check yourself

QuestionA model has p=10p = 10 parameters and is fitted on n=50n = 50 examples with noise variance σ2=1\sigma^2 = 1. Using the approximation from the math section, what is the expected gap between test and training error?Show answer

The gap is about 2σ2p/n=2×1×10/50=0.42\sigma^2 p / n = 2 \times 1 \times 10 / 50 = 0.4. Test error is expected to be about 0.4 higher than training error. Doubling the data to n=100n = 100 would halve the gap to 0.2.

QuestionWhy does a degree-9 polynomial on 10 points always have zero training error, and why is that not a sign of a good model?Show answer

A polynomial of degree 9 has 10 coefficients, and 10 distinct points determine a unique such polynomial, so it passes through every training point exactly. Zero training error only shows that the model can fit those points. Between and beyond them, nothing constrains the curve, so its predictions on new inputs can be far from the true rule.

QuestionIn the validation curve example, why should training stop near x=3.35x = 3.35 rather than at x=6x = 6, even though training error is lower at x=6x = 6?Show answer

The validation error is the estimate of performance on new data. It is lowest near x=3.35x = 3.35 at about 0.152 and rises to about 0.511 at x=6x = 6. Lower training error at x=6x = 6 comes from fitting noise, so it hurts the quantity we care about.

QuestionYou are told a model overfits. Name two remedies that reduce the gap without collecting new data, and say what each costs.Show answer

Any two of: L2 regularisation (costs a tuned penalty λ\lambda and may underfit if too large), early stopping (costs a validation set and a stopping rule), dropout (slower training and extra hyperparameters), a smaller model (may underfit), or data augmentation (augmentations must keep the label correct). Each trades some flexibility or compute for a smaller gap.

QuestionA colleague reports 99% accuracy on the validation set, and says the model generalises perfectly because they tried 200 configurations and kept the best. What is wrong with this reasoning?Show answer

Selecting the best of 200 configurations on the validation set makes its score optimistic, because each configuration's score is noisy and the maximum of many noisy scores is biased upward. The 99% is not an honest estimate of performance on new data. The right test is a separate test set that was never used for any of those choices.

Sources