◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Overfitting and the Bias–Variance Tradeoff

Why a model that is perfect on its training data can be useless on new data, how to spot it with learning curves, the classic bias–variance tradeoff that explains it, and the surprising "double descent" of modern, enormous models.

Level
●●●●● Easy
Reading
14 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Training, Validation and Test Sets

This leads to

Regularization: L1 and L2
The full path from zero — 5 concepts before this one
  1. What Is AI?
  2. How Machines Learn
  3. Supervised, Unsupervised and Reinforcement Learning
  4. Supervised Learning
  5. Training, Validation and Test Sets
  6. Overfitting and the Bias–Variance Tradeoff

Read them roughly in this order. See it on the concept map →

Why it matters

The goal of machine learning is not to fit the training data. It is to do well on data the model has never seen. Those two goals pull apart, and the gap between them is called overfitting. It is the central problem of the field.

Overfitting means a model has learned the training data too well: not just the real patterns, but also the noise and accidents peculiar to those particular examples. It looks superb in training and disappoints in use. Its opposite, underfitting, means the model is too simple to capture the real pattern at all, and it does badly everywhere.

Almost every technique in the next few chapters exists to fight overfitting: Regularization: L1 and L2, Cross-Validation, early stopping, Dropout and Regularizing Neural Networks, Data Augmentation, and Hyperparameter Tuning done honestly. Diagnosing whether a model is overfitting or underfitting tells you what to try next: more data, a bigger model, a smaller one, or better features. Without that diagnosis, you are guessing.

The intuition

Picture three students preparing for a maths exam by working through past papers.

  • The first student skims a few papers and learns one rule of thumb: "the answer is usually about 10". They do badly on the past papers and badly on the real exam. That is underfitting: too simple to capture what is going on.
  • The second student learns the methods: how to factorise, how to solve equations. They do well on the past papers and well on the exam. That is a good fit.
  • The third student memorises every answer on every past paper, typos included. They score 100% on the past papers and badly on the exam, because the exam has new questions. That is overfitting.

The same three outcomes appear when you fit curves to data. Below, twelve points were generated from a smooth wave plus random noise. A straight line (left) can't follow the wave. A cubic curve (middle) follows the trend and ignores the noise. A degree-11 polynomial (right) has 12 parameters for 12 points, so it can pass through every one exactly, with zero training error, and it goes wild in between.

Underfitting degree 1: too simple train MSE 0.157 · test MSE 0.294 Good fit degree 3: follows the trend train MSE 0.020 · test MSE 0.0749 Overfitting degree 11: threads every point train MSE 0.000 · test MSE 223,499 dots: 12 training points · dashed grey: the true curve sin(2πx) · solid: the fitted polynomial
Fig. 1 Three polynomial fits to the same 12 noisy points from a sine wave. Degree 1 underfits: it misses the wave. Degree 3 fits well: it follows the trend. Degree 11 overfits: it threads every point exactly, so its training error is 0, but it swings wildly between them and its test error is enormous.

The key is that noise can't be predicted. The random wobble in each training point won't repeat in new data. A model flexible enough to fit the noise has, by definition, learned something that won't generalise.

Key idea Underfitting: too simple, bad on training and test data. Overfitting: too flexible, great on training data, bad on test data. You can only tell them apart by measuring on data the model didn't train on.

How it works

Capacity and the U-shaped curve

A model's capacity is how flexible it is: how many different patterns it can represent. A straight line has low capacity. A degree-11 polynomial, a deep decision tree or a large neural network has high capacity. Capacity roughly grows with the number of parameters, but also depends on how they are used and constrained.

As capacity grows, training error falls steadily, because a more flexible model can always fit the training data at least as well. Test error behaves differently. At first it falls too, as the model becomes able to capture the real pattern. Then, past a sweet spot, it rises, as the extra flexibility goes into fitting noise. The difference between test and training error is the generalisation gap.

0 1 2 3 4 5 6 7 8 9 10 11 model capacity: polynomial degree mean squared error (log scale) 0.0001 0.01 1 100 10,000 1,000,000 noise level (0.0625) Test error new data: falls, then rises Training error keeps falling as capacity grows; reaches 0 (drawn at the floor) once the curve passes through all 12 points Sweet spot: degree 3 lowest test error ← underfitting overfitting →
Fig. 2 Training and test error against polynomial degree, for the same 12 points (log scale). Training error falls all the way to zero. Test error falls until degree 3, stays flat to about degree 5, then climbs steeply. The dashed line is the noise level, the best any model could do on new data.

Here are the real numbers behind the picture. The noise added to the data has variance 0.252=0.06250.25^2 = 0.0625, so no model can have test MSE below that.

Degree Training MSE Test MSE Diagnosis
1 0.157 0.294 underfitting: both errors high
3 0.020 0.075 good: test error near the noise floor
9 0.006 2.891 overfitting: big gap
11 0.000 223,499 memorised the training points

The pattern to remember: underfitting shows as high training error; overfitting shows as a big gap between training and test error.

The bias–variance decomposition

There is a precise way to split the test error into parts, for squared-error loss. Imagine repeating the whole experiment many times: draw a fresh training set from the same source, fit the model, and predict at some fixed input xx. The prediction would differ from run to run. Three things contribute to its average squared error:

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

The E\mathbb{E} means "average over many repetitions" (the expected value). f(x)f(x) is the true underlying value, yy is a noisy observation of it, and y^\hat{y} is the model's prediction. In words:

  • Bias is how far the average prediction is from the truth. It measures systematic error: the model is wrong in the same direction no matter which training set it sees. A straight line fitted to a wave has high bias.
  • Variance is how much the predictions jump around from one training set to another. It measures sensitivity to the particular sample. The degree-11 polynomial has huge variance: change one training point slightly and the curve changes completely.
  • Irreducible error σ2\sigma^2 is the noise in the labels themselves. No model can remove it.

(This "bias" is a statistical idea and has nothing to do with the bias term bb in a linear model, or with social bias.)

A worked example. Suppose the true value at some input is f(x)=5f(x) = 5. You train the same kind of model on three different training sets, and at that input the three models predict 4, 6 and 8.

  • Average prediction: (4+6+8)/3=6(4 + 6 + 8)/3 = 6. Bias =6−5=1= 6 - 5 = 1, so bias² =1= 1.
  • Variance: average squared distance from 6: ((4−6)2+(6−6)2+(8−6)2)/3=8/3≈2.67\big((4-6)^2 + (6-6)^2 + (8-6)^2\big)/3 = 8/3 \approx 2.67.
  • Check: the average squared error against the true value is ((4−5)2+(6−5)2+(8−5)2)/3=(1+1+9)/3=3.67\big((4-5)^2 + (6-5)^2 + (8-5)^2\big)/3 = (1 + 1 + 9)/3 = 3.67, which is exactly 1+2.671 + 2.67.

Add the label noise σ2\sigma^2 and you have the expected test error at that point. Here variance contributes more than bias, so the remedy is to make the model steadier: more data, fewer parameters, or Regularization: L1 and L2.

The bias–variance tradeoff is the observation that, as you raise capacity, bias tends to fall and variance tends to rise. Simple models are stable but systematically wrong. Flexible models are right on average but erratic. The best test error sits where their sum is smallest: the bottom of the U.

Learning curves: the diagnostic tool

How do you tell which problem you have? Plot a learning curve: training and validation performance as a function of the number of training examples.

0 500 1000 1500 0 0.25 0.5 0.75 1 training examples accuracy High variance: depth-8 tree big gap: more data helps training validation 0 500 1000 1500 0 0.25 0.5 0.75 1 training examples accuracy High bias: depth-2 tree both low and close: more data won't help training validation
Fig. 3 Learning curves on the handwritten-digits dataset. Left, a depth-8 decision tree: training accuracy is near 100% and validation accuracy is far below but climbing, the signature of high variance, which more data would help. Right, a depth-2 tree: both curves are low and close together, the signature of high bias, which more data won't fix.
  • High variance (overfitting): training score high, validation score much lower, with a big gap that narrows as data grows. Fixes: more data, a simpler model, regularisation, data augmentation, fewer features, early stopping, ensembles such as Random Forests and Bagging.
  • High bias (underfitting): both scores low and close together, flattening out. More data won't help. Fixes: a more flexible model, better features, less regularisation, training longer.

A related plot, the validation curve, varies one capacity setting (polynomial degree, tree depth, regularisation strength) instead of the data size. It is how you find the bottom of the U.

Double descent: what changed with deep learning

The U-shaped curve was textbook wisdom for decades. Then deep learning broke it. Modern neural networks often have far more parameters than training examples, enough to memorise the training set completely, including randomly shuffled labels, and yet they generalise well. By the classical picture they should be hopelessly overfit.

In 2018–2019, Mikhail Belkin and colleagues showed what happens if you keep increasing capacity past the point where the model can fit the training data exactly (the interpolation threshold). Test error peaks at that threshold, as the classical picture predicts, but then falls again, sometimes below the classical best. They called this double descent. Preetum Nakkiran and colleagues at OpenAI then showed in 2019 that it appears in deep networks too, as a function of model size and even of training time.

number of parameters (log scale) test error (log scale) 2 10 40 100 1,000 0.1 1 10 interpolation threshold: parameters = 40 training points classical regime the U-shaped curve modern regime: error falls again, below the classical best Experiment regression with random features, 40 training points, minimum-norm least squares; median of 40 repeats Classical best 0.163 at 20 parameters Peak 11.8 at 40 parameters Far right 0.072 at 3,000 parameters
Fig. 4 Double descent in a small experiment: test error of random-features regression with 40 training points as the number of parameters grows. Error follows the classical U until about 20 parameters, peaks sharply at 40 (where the model can just fit every training point), then falls again, ending below the classical best.

Why the second descent? Past the threshold there are many parameter settings that fit the training data exactly, and the training procedure picks one of a special kind, typically the "smoothest" or smallest-weight one. Gradient descent started from small weights has this preference built in; it acts as implicit regularisation. With more parameters there are more candidate solutions, and the smoothest one gets smoother. The peak at the threshold happens because there is exactly one way to fit the data, and it is usually a contorted one.

What this means in practice:

  • The gap between training and test error is still the thing to watch. Double descent doesn't make overfitting go away; it says that "more parameters" isn't the same as "more overfitting" once a model is very large and implicitly regularised.
  • For classical models (polynomials, trees, linear models with hand-made features) the U-shaped picture remains the right guide.
  • Huge models such as large language models usually sit far to the right of the threshold, and are trained on so much data that they often see each example only once or a few times. Their main risk is memorising specific training text rather than classical overfitting.

In code

The polynomial experiment from scratch. np.polyfit finds the least-squares polynomial of a given degree:

import numpy as np

rng = np.random.default_rng(1)
def make_data(n):
    x = rng.uniform(0, 1, n)
    y = np.sin(2 * np.pi * x) + rng.normal(0, 0.25, n)   # true curve + noise
    return x, y

x_tr, y_tr = make_data(12)       # a small training set
x_te, y_te = make_data(1000)     # a big test set from the same source

for degree in [1, 3, 9, 11]:
    coefs = np.polyfit(x_tr, y_tr, degree)              # least-squares fit
    mse_tr = np.mean((np.polyval(coefs, x_tr) - y_tr) ** 2)
    mse_te = np.mean((np.polyval(coefs, x_te) - y_te) ** 2)
    print(f"degree {degree:2d}  train MSE {mse_tr:7.4f}  test MSE {mse_te:9.4f}")
# degree  1  train MSE  0.1567  test MSE    0.2941
# degree  3  train MSE  0.0199  test MSE    0.0749
# degree  9  train MSE  0.0055  test MSE    2.8913
# degree 11  train MSE  0.0000  test MSE 223498.7948

scikit-learn computes validation curves and learning curves for you, using Cross-Validation (here 5 folds) to get the validation scores. On the handwritten-digits dataset (1,797 tiny 8×8 images, 10 classes):

import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import validation_curve, learning_curve
from sklearn.tree import DecisionTreeClassifier

X, y = load_digits(return_X_y=True)    # 1,797 8x8 images of handwritten digits

# Capacity: how deep may the tree grow?
depths = [1, 2, 4, 6, 8, 10, 15, 20]
tr, va = validation_curve(DecisionTreeClassifier(random_state=0), X, y,
                          param_name="max_depth", param_range=depths, cv=5)
for d, a, b in zip(depths, tr.mean(axis=1), va.mean(axis=1)):
    print(f"depth {d:2d}  train {a:.3f}  validation {b:.3f}")

# Learning curve: does more data help a depth-8 tree?
sizes, tr, va = learning_curve(DecisionTreeClassifier(max_depth=8, random_state=0), X, y,
                               train_sizes=[0.1, 0.25, 0.5, 0.75, 1.0], cv=5)
for n, a, b in zip(sizes, tr.mean(axis=1), va.mean(axis=1)):
    print(f"n={n:4d}  train {a:.3f}  validation {b:.3f}")
# depth  1  train 0.198  validation 0.198
# depth  2  train 0.316  validation 0.312
# depth  4  train 0.601  validation 0.544
# depth  6  train 0.832  validation 0.717
# depth  8  train 0.942  validation 0.779
# depth 10  train 0.987  validation 0.787
# depth 15  train 1.000  validation 0.786
# depth 20  train 1.000  validation 0.786
# n= 143  train 0.989  validation 0.518
# n= 359  train 0.979  validation 0.602
# n= 718  train 0.980  validation 0.681
# n=1077  train 0.951  validation 0.736
# n=1437  train 0.942  validation 0.779

Read the depth table from the top. Depths 1 and 2 underfit: training and validation are equally bad. From depth 10 on, the tree memorises the training set (100%) while validation stalls at about 79%: a gap of over 20 points. The learning curve says the depth-8 tree is data-hungry: validation accuracy climbs from 52% to 78% as the training set grows and hasn't levelled off. (A random forest on the same data reaches well above 90%, because averaging many trees cuts variance.)

Common pitfalls

  • Judging by training error. A model's training score tells you almost nothing about its real performance. Always compare with held-out data.
  • Overfitting the validation set. Trying hundreds of models or settings and keeping the best validation score overfits the validation set. The winner's score is optimistic. Keep a final test set (Training, Validation and Test Sets) and see Hyperparameter Tuning.
  • Too many features for the data. With 5,000 features and 100 examples, a linear model can fit pure noise perfectly. A useful rule of thumb is to worry whenever features approach or exceed examples. Use regularisation or feature selection inside the pipeline.
  • Training too long. For neural networks, validation loss often falls, bottoms out and then rises while training loss keeps falling. Stop at the bottom (early stopping; see Regularization: L1 and L2 and Training Neural Networks in Practice).
  • Blaming overfitting for everything. If training error is high, the model is underfitting, and regularisation will make it worse.

Watch out A training accuracy of 100% is a warning sign, not an achievement. On real, noisy data it almost always means the model has memorised examples, including their noise and labelling mistakes.

Where it leads

A bit of history

The tension between fitting the data and keeping the model simple is old. William of Ockham's razor (14th century) advised against needless complexity. Statisticians formalised the danger of fitting noise through the 20th century. The bias–variance decomposition was introduced to machine learning by Stuart Geman, Elie Bienenstock and René Doursat in their 1992 paper on neural networks and the bias/variance dilemma. Vladimir Vapnik and Alexey Chervonenkis built a theory of capacity (the VC dimension) from the late 1960s that bounded the generalisation gap.

Deep learning upset the tidy picture. In 2017, Chiyuan Zhang and colleagues showed that standard image networks can perfectly fit randomly shuffled labels, yet generalise well on real labels, which classical capacity measures could not explain. Belkin, Hsu, Ma and Mandal (2019) named and demonstrated double descent, and Nakkiran and colleagues (2019) showed it in modern deep networks. Explaining why huge models generalise remains an active research question.

Try it

  1. In the polynomial code, change the training set from 12 to 100 points. Rerun the degrees 1, 3, 9 and 11. What happens to the degree-9 and degree-11 test errors? Why?
  2. Compute bias² and variance by hand for predictions 3, 5, 5, 7 when the truth is 5. Which is the problem here?
  3. Repeat the learning-curve code with max_depth=None, then with RandomForestClassifier(random_state=0) from sklearn.ensemble. How does the final validation accuracy change?

Hint for 1: with 100 points, a degree-11 polynomial has far fewer parameters than data points, so it can no longer thread every point. Hint for 2: the average is exactly 5.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. A model has training error 0.157 and test error 0.294; a more flexible one has 0.020 and 0.075. A third has 0.006 and 2.891. Which one is overfitting?

  2. Your learning curve shows training and validation scores both low and close together, flattening out. What should you try?

  3. At one input the truth is 5, and models trained on three different training sets predict 4, 6 and 8. What are the bias² and variance?

  4. A decision tree scores 100% on its training data. What should you conclude?

  5. In double descent, test error peaks at the interpolation threshold and then falls again as parameters keep growing. Why does it fall?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Interactive

MLU-Explain: The Bias Variance Tradeoff

Amazon Machine Learning University (MLU-Explain) · Beginner · Free

An interactive essay on underfitting, overfitting and the bias–variance decomposition, with models you can make more or less flexible.

Interactive

MLU-Explain: Double Descent

Amazon Machine Learning University (MLU-Explain) · Intermediate · Free

A visual explanation of why test error can fall again once models grow past the point where they fit the training data exactly.

Course

Machine Learning Crash Course

Google · Beginner · Free

Short, practical lessons with interactive visualisations covering regression, classification, embeddings and neural nets.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/overfitting.md