ML Atlas

Machine learning from zero · Lesson 3.1 · 14 of 33 lessons ready · 10 min

Overfitting: when a model memorises

In short

A flexible model can fit its training data perfectly and still fail on new data. As a polynomial's degree rises, training and test error part ways.

Warm-up Two questions from earlier lessons. A minute, and it never blocks the lesson.
From lesson 2.6: A metric and threshold for the cost of mistakes A spam filter: a good email in spam costs 5 times more than spam in the inbox. Where should the threshold on P(spam) go?

Show the answer

Correct answer: High, about 5 / (5 + 1) ≈ 0.83: only sure cases go to spam

Here the false alarm is the dearer error, so the threshold goes up: c_FP / (c_FP + c_FN) = 5/6 ≈ 0.83, if the model is calibrated. In the lab a dearer alarm also moves the cheapest threshold above 0.5.

From lesson 2.5: Imbalanced classes With 8 malignant in learning, class weights raise recall from 61.5% to 80.0%. What do they not do?

Show the answer

Correct answer: They do not add new examples, so something is still missing compared with all the data

Weights only change how much a mistake on each class costs. All the data with weights gives a recall of 86.8%, so with 8 malignant 6.8 points are missing.

Two students prepare for a maths exam. One works through the ideas behind the problems. The other memorises the answers to every past paper, word for word. On the past papers the second student is flawless. Then the real exam arrives with new numbers. Who do you bet on? Models face exactly this choice, and left alone, a flexible model will happily become the second student.

Predict, then check You fit polynomials of degree 0 to 10 to 30 patients. Which degree gives the smallest error on the test patients?
How sure are you?

Interactive lab

This interactive lab runs in a browser with JavaScript enabled. The text around it describes what the lab shows.

Show the answer

Correct answer: Degree 1 (a plain straight line)

Degree 1 is the best: test error 64.1. Degree 3 has 65.2, degree 6 has 70.3 and degree 10 as much as 132.6, although the training error falls from 60.2 (degree 1) to 51.1 (degree 10). More flexibility lowers the training error, not the test error.

Try this

  • Start at degree 1 and note both errors. Then raise the degree slider one step at a time and watch the training error fall.
  • Keep going and watch the test error. Find the degree where it is lowest — that is the sweet spot for this sample.
  • Push the degree slider to the maximum. Look at the curve between the points: does it still look like a sensible description of how BMI relates to progression?
  • Compare the gap between training and test error at the lowest and at the highest degree. A growing gap is the fingerprint of overfitting.

Now that you've tried it, let's see what was actually going on.

The idea in plain words

In lesson 3 we fitted a straight line. A straight line is stiff: it cannot bend to follow a curve, even when the data clearly curve. A polynomial is a more flexible family of curves:

ŷ = w₀ + w₁x + w₂x² + … + w_d·x^d

The degree d controls the flexibility. Degree 1 is the straight line; degree 2 can make one bend; higher degrees can wiggle more and more. With enough degree a polynomial can pass through every single training point.

That sounds like success, but real data contain noise — random variation that no feature explains. Two patients with the same BMI do not progress identically. A model flexible enough to hit every point is not only learning the trend; it is also learning the noise, the accidents of this particular sample. That is overfitting: the model fits the training data better and better while its predictions for new data get worse. The opposite failure, a model too stiff to capture the real pattern, is underfitting.

Why it works

Take a small random sample of the diabetes patients from lesson 3 and split it into training and test points. A small sample makes the effect easy to see, because a few unusual points can drag a flexible curve far off course.

Follow what happens to the two errors as the degree goes up. The training error keeps going down: a more flexible curve can always do at least as well on the points it is fitted to, because it can imitate any simpler curve. The test error behaves differently. At first it falls too, because the extra flexibility captures real structure. Then, past some degree, it starts to rise, because the curve now bends to chase individual training points, and those bends are wrong for everybody else. The result is the famous U shape of test error.

The reason has a name: the bias–variance trade-off. A stiff model has high bias — it is wrong in a systematic way, whatever sample it sees. A very flexible model has high variance — draw a slightly different sample and you get a wildly different curve. The best model sits in between, flexible enough to follow the signal and stiff enough to ignore the noise. Where that point lies depends on how much data you have: with more data, the noise averages out and more flexibility becomes safe.

Common mistake

The fundamental error is choosing model complexity by training error. Training error always rewards more flexibility, so it will always vote for the most complex model — the memorising student. The second error is assuming overfitting is rare or exotic. It is the default behaviour of any flexible model on limited data, which covers decision trees, neural networks and most of what you will build. The cure is not to avoid flexible models but to control them: simpler models, more data, or regularisation, which penalises extreme weights.

There is a catch hidden in this reasoning: we picked the best degree by looking at the test error, which is exactly what lesson 2 warned against. In the next lesson we learn how to choose settings honestly, using validation and cross-validation.

Catch the AI’s mistake

This is how a chatbot answered. One sentence is factually wrong. Which one?

Question: I fitted polynomials of degree 1 to 10 to 30 patients, BMI against disease progression. Which degree should I choose?

Chatbot’s answer

Show the wrong sentence

The wrong sentence: So the degree with the lowest training error, here degree 10, is also the one that will predict new patients best.

Training error always rewards flexibility, so it cannot pick the degree. In the lesson degree 10 has the lowest training error (51.1 against 60.2 for degree 1), but its test error is 132.6, more than twice the 64.1 of the straight line.

Quiz

Three questions to check yourself. Pick an answer, or open the answer under a question. Keyboard: arrow keys choose, Enter or Space confirms.

1. As the polynomial degree increases, what happens to the training error?
Show the answer

Correct answer: It falls or stays flat, because a flexible curve can copy a simpler one

A higher-degree polynomial contains every lower-degree one as a special case, so it can never fit the training points worse.

2. The training error is tiny but the test error is large. What is the most likely diagnosis?
Show the answer

Correct answer: Overfitting, i.e. a model fitted to the training noise

A large gap between training and test error means the model has learned details of the training sample that do not generalise.

3. Why does more training data usually make a flexible model safer?
Show the answer

Correct answer: Because with more points the noise averages out and the curve cannot chase single points

Noise in individual points stays, but with many points it cancels out, so the fit follows the real trend.

Key takeaways

  • Overfitting means fitting the noise in the training data, so test performance gets worse.
  • Training error always rewards flexibility; only data the model did not learn from reveal overfitting.
  • Test error typically forms a U shape as complexity grows: underfitting on one side, overfitting on the other.
  • More data, simpler models and regularisation all reduce overfitting.

Going further: formula, code, practice

The math

A polynomial of degree d has d + 1 weights: ŷ = w₀ + w₁x + … + w_d·x^d. Fitting by least squares minimises the training error. Every polynomial of degree d − 1 is also a polynomial of degree d (with w_d = 0), so the best training error can only stay the same or fall as d grows. With n points that all have different x, degree n − 1 passes through every point and the training error is 0.

The test error splits into three parts: E[(y − ŷ)²] = bias² + variance + σ². Bias is the systematic miss of a model that is too stiff. Variance is how much the fitted curve changes between samples. σ² is the noise nobody can remove. A higher degree lowers bias and raises variance, which gives the U shape.

The lab reports RMSE, √MSE, in the units of the target.

In code (Python)

Thirty random diabetes patients as the training set, the other patients (inside the training BMI range) as the test set. This is the same kind of experiment as the lab but another random sample, so the numbers differ from the lab's:

import numpy as np
from sklearn.datasets import load_diabetes

X, y = load_diabetes(return_X_y=True, as_frame=True, scaled=False)
x, y = X["bmi"].to_numpy(), y.to_numpy()
perm = np.random.default_rng(0).permutation(len(x))
tr, te = perm[:30], perm[30:]
te = te[(x[te] >= x[tr].min()) & (x[te] <= x[tr].max())]  # stay inside the training range
rmse = lambda i, p: np.sqrt(np.mean((y[i] - p(x[i])) ** 2))
for deg in (1, 3, 10):
    p = np.polynomial.Polynomial.fit(x[tr], y[tr], deg)  # fits on a rescaled x, so degree 10 is stable
    print(f"degree {deg:2d}: train RMSE {rmse(tr, p):6.1f}, test RMSE {rmse(te, p):6.1f}")

Output

degree  1: train RMSE   61.6, test RMSE   63.5
degree  3: train RMSE   60.9, test RMSE   63.8
degree 10: train RMSE   54.7, test RMSE  199.5

The training error keeps falling with the degree. The test error of degree 10 is more than three times that of degree 1.

For practitioners
  • Never choose the degree, or any other flexibility setting, by training error. It always votes for the most flexible model.
  • Look at the gap between training and test error. A small training error with a large test error means overfitting. Both errors high means underfitting.
  • Higher-degree polynomials explode outside the range of the training data. Do not use them for extrapolation.
  • With a single small sample the picture is noisy. Repeat the split with several seeds before you trust a "best degree".
  • To keep a flexible model in check, try more data, a simpler model or regularisation (ridge, lasso) before you give up flexibility entirely.

Go deeper in the Atlas

Encyclopedia entries on the ideas in this lesson: