Overfitting and the bias-variance trade-off

Why a model that is perfect on its training data can fail on new data, and how to find the level of complexity that generalises.

Lesson 23 of 6615 minIntermediate

You will learn to

  • Recognise underfitting and overfitting from training and validation scores
  • Explain error on new data as bias squared, plus variance, plus noise
  • Choose a level of model complexity with validation data instead of training data

Before this lesson

Intuition

Imagine studying for an exam by memorising last year's answers word for word. You would ace last year's paper and struggle with this year's, because you learned the specific questions instead of the subject. A model can do the same thing: it can fit the rows it was trained on so closely that it learns their accidents (measurement noise, rare coincidences) instead of the pattern that will repeat.

That is overfitting. Its opposite is underfitting: a model too simple to capture the real pattern, which does badly everywhere, like a student who only skimmed the chapter titles.

Two quantities explain both failures:

  • Bias is the error that comes from wrong assumptions. A straight line fitted to a curved relationship is wrong in a systematic way, no matter how much data you give it.
  • Variance is the error that comes from sensitivity to the training sample. A very flexible model fitted to two different samples of the same problem gives two very different answers.

Making a model more flexible lowers bias and raises variance. The craft is to find the point in between where the error on new data is lowest. That point cannot be found by looking at training error, because training error keeps falling as the model gets more flexible.

Picture it

Underfit: too simpleGood fitOverfit: memorises noise
The same twelve points fitted by a model that is too simple, one that is about right, and one flexible enough to pass through every point.

The flat line misses the obvious rise and fall: high bias. The wiggly line passes through every point, so its training error is close to zero, but its shape between the points is dictated by noise: high variance. Draw twelve new points from the same process and the middle curve will predict them best.

Model complexityErrorUnderfittingOverfittingSweet spotError on new dataError on training dataBias squaredVariance
As complexity grows, bias falls and variance rises. Error on new data is lowest where their sum is lowest, while training error keeps going down.

The math

Take a regression problem where the target is a true function plus noise, y=f(x)+εy = f(x) + \varepsilon, with noise of mean zero and variance σ2\sigma^2. Train a model f^\hat{f} on a random training sample. For a new point xx, the expected squared error, averaged over all the training samples you could have drawn and over the noise, splits into three parts:

E[(y−f^(x))2]=(E[f^(x)]−f(x))2⏟bias2+E[(f^(x)−E[f^(x)])2]⏟variance+σ2⏟noise\mathbb{E}\big[(y - \hat{f}(x))^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{noise}}
  • Bias squared: how far the average model (over many training samples) is from the truth.
  • Variance: how much an individual model scatters around that average.
  • Noise: the part of yy that no function of xx can predict. It is the floor.

The decomposition is exact for squared error. For other losses, such as classification accuracy, there is no clean three-term split, but the same trade-off holds: flexible models track their training sample, simple models ignore parts of the signal.

Training error does not appear in the formula at all. A model's error on the rows it learned from is a biased, optimistic estimate of its error on new rows, and the more flexible the model, the more optimistic it is. That is why model choice must use data the model did not train on: a hold-out set or, better, cross-validation.

Worked example

We drew 30 points from y=sin⁡(2πx)+εy = \sin(2\pi x) + \varepsilon with noise standard deviation 0.3, then fitted polynomials of degree 1, 3 and 15. We measured the root mean squared error (RMSE) three ways: on the 30 training points, with 5-fold cross-validation on those same 30 points, and on 1,000 fresh points from the same process.

DegreeTraining RMSE5-fold CV RMSERMSE on 1,000 new points
1 (a straight line)0.490.520.57
30.250.270.35
150.203.290.38

Read it column by column:

  • Training error always improves with degree. Judged on training data, degree 15 wins.
  • Cross-validation disagrees. Degree 15 is wildly unstable: in some folds the fitted curve shoots far away from the held-out points, which inflates the average. Degree 3 has the best CV score.
  • New data agrees with cross-validation. Degree 3 is best and close to the noise floor of 0.3; nothing can do much better. The straight line underfits (bias); degree 15 overfits (variance).

The lesson is not "use degree 3". It is: pick complexity with data the model has not seen, and expect the training score to flatter the most flexible model.

In mlflow, every score on a run's leaderboard is already a cross-validated score, so ranking models on the leaderboard is ranking them on unseen folds. The knobs that move a model along the complexity axis are its hyperparameters: max_depth for trees, the penalty strength for ridge and lasso, the number of neighbours for k-nearest neighbours.

Common mistakes

  • Choosing a model by its training score. The most flexible model always looks best on its own training data. Compare validation or cross-validated scores.
  • Reading a big train-validation gap as bad luck. A gap that persists across folds is variance. Constrain the model, add data, or remove noisy features.
  • Assuming more complexity is always better with enough data. More data lowers variance, so it lets you afford more complexity, but it does nothing for bias or noise.
  • Tuning until the validation score stops improving, then reporting that score. After many trials the validation folds have been used to choose, so their score is optimistic too. Keep a final hold-out you never tune on; see Overfitting the validation set.
  • Treating regularization as a fix for underfitting. A penalty trades a little bias for less variance. If a model underfits, make it more flexible or give it better features instead.

Try it in mlflow

Make a decision tree overfit, then rein it in

  1. Open Pipelines and pick a classification or regression pipeline (the Churn prediction use case works).
  2. Open the Models part, add Decision Tree in Automatic mode (no depth limit) and train it.
  3. Back in the pipeline, switch Decision Tree to Manual, set max_depth to 3 and train again.
  4. Compare the cross-validated scores of the two runs on the Runs page.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. A model scores 99% accuracy on its training data and 71% on validation folds. What is the most likely diagnosis?
  2. 2. Which change usually lowers variance without changing the algorithm family?
  3. 3. Why can you never reach zero error on new data, even with a perfect model?