What learning is · lesson 6 of 13
Parts in this lesson
Afor k in ks: ... m.score(X_test, y_test)scoring a model at many settings
Bax.invert_xaxis()simple models on the left of the plot
Cfor seed in range(50): make_moons(..., random_state=seed)the same model trained on 50 different datasets

Overfitting and underfitting

Last updated

A model can be too simple to catch the pattern in the data, or so complex it catches the noise too. Both do badly on new data, for opposite reasons. This lesson turns one dial, k in k-NN, from one extreme to the other, watches training and test error move, and names what’s going on: underfitting, overfitting, and the bias and variance behind them.

By the end of this lesson you can

  • Spot overfitting and underfitting from training and test scores
  • Read a plot of training and test error against model complexity, and find the sweet spot
  • Explain bias and variance in words, and show them by retraining on fresh data

k = 1 against k = 151

The penguins are almost too easy: most settings do well on them. To see the problem clearly, this lesson uses two classes of points shaped like interlocking half-moons, with lots of noise, so they overlap. The figure trains k-NN on 200 of them and tests it on 100 more. Turn the dial from simple to complex:

Complexity dialk = 51
Error (share wrong)00.10.20.30.4k = 101, simplek = 1, complex

Working out the errors…

  • At k=1, every training point rules the space around it. The borders wrap round single noisy points, making islands. Training error is 0; test error is worse than it needs to be. The model has learned the noise. That's overfitting.
  • At k=101, half the training data votes on every point. The border is nearly straight and misses the moons' curve. It's poor on training and test data alike. The model is too simple for the pattern. That's underfitting.
  • Somewhere in between, it follows the curve without chasing every point.

Here are the same kinds of numbers from scikit-learn, with the data made by make_moons (the figure's moons are drawn the same way, but they aren't the identical points, so the numbers differ a little):

curve.ipynb

Error against model complexity

Plotting both errors for every k shows the shape you'll see again and again in this course:

curve.ipynb

Read it from left (simple) to right (complex):

  • Training error falls steadily as the model gets more complex, all the way to 0 at k=1. A complex enough model can fit its training data perfectly.
  • Test error falls at first, as the model gets flexible enough to follow the real pattern, then rises again as it starts fitting noise. It's roughly a U (noisy, because 90 test points is not many).
  • The best model is near the bottom of the U, not at the end of either curve. Here that's k around 51 to 101, with a test error of 10%.

The gap between the two curves is a warning light: small on the left, big on the right. Every kind of model has a dial like k: the depth of a tree (Stage 4), the size of a network (Stage 6), how strongly the weights are held back (regularisation, lesson 3.8). Finding the bottom of the U honestly is lesson 2.9.

Bias and variance

Two words explain the U. Imagine you could collect a fresh training set many times and train the same kind of model on each:

  • Variance is how much the model's predictions change from one training set to the next. A k=1 model changes a lot, because every noisy point moves its borders.
  • Bias is how far its predictions are from the truth on average, however many training sets you average over. A k=101 model is nearly the same every time, but its straight-ish border is wrong in the same way every time.

You can't collect fresh penguins, but you can make fresh moons. This trains each model on 50 different training sets and asks each version the same question: how likely is class 1 at the point (0.5,0.25)?

variance.ipynb

With k=1, the answer is 0 or 1, and it flips between training sets: a spread (standard deviation) of 0.48, the most a 0-or-1 answer can vary. With k=101, the answer barely moves (spread 0.03), and it sits at 0.50 every time. It's stable but has stopped saying anything about this point: that's bias. k=15 is in between on both.

For squared error there's an exact version, which Stage 3 uses:

𝔼[(y−fˆ(x))2]=Bias[fˆ(x)]2+Var[fˆ(x)]+σnoise2

In words: the expected squared error of a model's prediction at x, averaged over training sets, is its bias squared, plus its variance, plus noise in the data that no model can remove. Making a model more complex usually lowers the bias and raises the variance. The bottom of the U is where their sum is smallest.

Wrong way: picking the best training score

If you pick k by the training score, you'll always pick the most complex model:

best.ipynb

k=1 has a perfect training score, so it "wins". On the test set it gets 82.2%, against 87.8% for k=15. The training score can only tell you whether a model is able to fit the data. It can't tell you whether it fits the pattern or the noise, because the noise is in the training data too.

So choose settings by a score on data the model didn't train on. But not the test set either: if you try many settings on the test set and keep the best, the test set has helped choose the model, and its score is no longer an honest estimate. Lesson 2.9 shows how to choose without touching it.

Check what you learned

A model’s training error is 30% and its test error is 31%. What is most likely going on?
Predict, then check with the dial: as you move from k=101 towards k=1, what does the training error do?
A model gives very different predictions depending on which training set it’s given. Which does it have too much of?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Machine Learning