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.
- training error
- validation error
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:
Here is an input, is the true rule we are trying to learn, is the observed output, and is random noise with variance . Often the noise is taken to be Gaussian.
We pick a model from a family, for example linear functions or polynomials of a given degree, using a training set of 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:
The test error is the expected loss on a new example drawn from the same distribution, including new noise:
Overfitting is the situation where is much smaller than . The generalization gap is their difference, .
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 parameters (including any intercept) fitted on 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 for expectation over the noise. Then
The gap is therefore about . Read it carefully. The optimism grows with the number of parameters and shrinks with the number of examples . 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 but is divided by .
Bias and variance
For a fixed test input , squared-error test risk splits into three terms. Averaging over possible training sets, the expected test error is
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
where is the weight vector, controls the penalty, and is the squared length of the weights (see Vector Norm). Large shrinks the weights toward zero and makes the model smoother. Small recovers the unpenalised fit. In effect the penalty forbids the model from using extreme weights to chase individual points.
Worked examples
A linear model with parameters is fitted to examples. The noise has , so .
- Expected training error: .
- Expected test error: .
- Gap: . Check with . The two routes agree.
- Now increase the data to with the same five parameters. The gap becomes .
Interpretation: the same model that overfits noticeably on 20 examples barely overfits on 200. More data is the most reliable cure.
We have points with distinct inputs. A polynomial of degree 9 has 10 coefficients.
- Lagrange interpolation shows that a unique degree-9 polynomial passes through all 10 points.
- So its training error is exactly .
- Between and beyond the training inputs, the polynomial can take values far from the true rule, because nothing constrains it there.
- Compare a degree-1 line. Its training error is larger, but it has two parameters, so the penalty 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.
Let be a complexity knob, such as polynomial degree or the number of boosting rounds. Suppose, for illustration, that the training error follows and the validation error follows .
- At : training error , validation error . The model is underfitting and both are high.
- At : training error , validation error .
- At : training error about , validation error about . Here the validation curve reaches its lowest point.
- At : training error , validation error about . Training keeps improving while validation gets much worse.
- 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.
| Remedy | What it does | Cost or risk |
|---|---|---|
| More data | Lowers , shrinking the gap | Often expensive or impossible to obtain |
| Smaller model | Reduces the number of parameters | Can underfit if too small |
| L2 Regularization | Penalises large weights | Needs tuned on validation data |
| Early Stopping | Stops training when validation error rises | Needs a validation set and a patience rule |
| Dropout | Randomly disables units during training | Slower training, more hyperparameters |
| Data Augmentation | Creates plausible new examples from existing ones | Augmentations must preserve the label |
| Ensemble Learning or Bagging | Averages models trained on different samples | More 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 parameters and is fitted on examples with noise variance . Using the approximation from the math section, what is the expected gap between test and training error?Show answer
The gap is about . Test error is expected to be about 0.4 higher than training error. Doubling the data to 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 rather than at , even though training error is lower at ?Show answer
The validation error is the estimate of performance on new data. It is lowest near at about 0.152 and rises to about 0.511 at . Lower training error at 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 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.