Chapter 4 // Learning from Data

Generalization.

If one model fits the data better than another, is it the better model?

Reading time
20 min
Data

So far “better” has meant “lower error on the data we have”. This chapter shows why that is the wrong target, and what to aim for instead. It contains the most practically useful idea in the book: how to tell whether a model has really learned something or has only memorised its examples.

A model that memorises

Imagine a model that is nothing but a lookup table. It stores every training example. Asked about a student it has seen, it returns that student’s exact score. Its training error is zero. No model can beat it.

Now ask it about a student it has not seen. It has nothing to say. A perfect score on the training data told us nothing about whether it could do the job.

This extreme case is a warning about every model. Training error measures how well a model matches examples it was shown. What we care about is how it does on examples it was not shown. The gap between the two is what this chapter is about.

Too simple, too flexible

A new dataset makes the problem visible. Twelve students recorded how long they slept the night before an exam, and their score. Too little sleep hurts. So, it turns out, does too much.

A straight line cannot follow a pattern that rises and then falls. So we let the model bend: instead of a line, fit a curve. The degree of the curve sets how many bends it is allowed. Degree 1 is a straight line, degree 2 has one bend, and degree 9 can wiggle through almost anything.

Figure

How flexible should the curve be?

3 h, score 453.1 h, score 503.9 h, score 585 h, score 755.5 h, score 675.9 h, score 756.6 h, score 697.3 h, score 808.5 h, score 788.6 h, score 749.7 h, score 7010.2 h, score 65
  • Students used for fitting
  • Fitted curve
Flexibility
degree 1: straight line
Error on fitted students
66.2
Error on new students
hidden
1
The dark dots are the twelve students used for fitting. Try it: raise the degree one step at a time and watch the error on the fitted students. At degree 9, press the button to show twenty new students.

Three things happen as you raise the degree.

At degree 1 the line misses the shape entirely. This is : the model is too simple for the pattern, and it is wrong about fitted and new students alike.

At degree 2 the curve follows the rise and fall. It does not pass through every dot, and it should not, because the dots include luck. That unpredictable part is called .

At degree 9 the curve bends to pass close to every fitted student. Its error on them is tiny. But it gets there by swinging wildly between the dots, and the new students land nowhere near it. This is : the model has learned the noise in these twelve students as if it were the pattern.

Training error always falls

Collect the two errors for every degree and plot them against each other.

Predict firstCommit to a guess, then use the figure below to check it.

As the degree rises from 1 to 9, the error on the fitted students keeps falling. What do you expect the error on new students to do?

Figure

Two errors, two stories

2, 11.922, 28.83new studentsfitted students
  • Error on fitted students
  • Error on new students
Degree
2
Fitted students
11.9
New students
28.8
Verdict
About right
2
The dark line is the error on the twelve fitted students. The orange line is the error on twenty new ones. Try it: move the slider from 1 to 9 and read the verdict at each step. Find where the two lines are closest.

The error on the fitted students only ever goes down: from 66 at degree 1, to 12 at degree 2, to 5 at degree 9. A more flexible model can always match its own data at least as well.

The error on new students tells the truth. It drops from 102 to 29 as the model becomes able to follow the pattern, stays roughly level for a while, then climbs steeply to 192 at degree 9.

The best model is at the bottom of the orange curve, not the dark one. Choosing by training error would pick degree 9, the worst model on the page.

Checkpoint

You train two models. Model A has training error 4 and error 60 on new data. Model B has training error 15 and error 18 on new data. Which do you ship?

Three piles of data

To choose a degree we looked at the new students. That is a problem. Once we have used them to make a decision, they are no longer “new”, and their error is no longer an honest estimate of real-world performance.

The fix is to split the data into three piles before doing anything else.

PileUsed forTypical share
Training setFitting the weights60 to 80%
Validation setChoosing between models and settings10 to 20%
Test setOne final, honest measurement10 to 20%

The is the one you are allowed to look at repeatedly. The test set is opened once, at the very end.

A setting like the degree, which you choose rather than learn, is called a . The learning rate from is another. Hyperparameters are tuned on the validation set.

One rule protects all of this. Nothing about the validation or test examples may influence training: not their labels, and not even their averages if you rescale features. When it does, the result is called , and the model will look better on paper than it is.

Cross-validation

Three piles are expensive when data is scarce. With twelve students, setting four aside leaves only eight to learn from, and a validation set of two or three students is mostly luck.

gets more out of the same data. Split the students into five groups. Hide the first group, fit on the other four, and score the fit on the hidden group. Then hide the second group instead, and so on. Every student is used for checking exactly once and for fitting four times. The average of the five scores is the model’s cross-validation score.

Figure

Five rounds, five different hold-outs

Used for fitting: 9.7 h, score 70Used for fitting: 3.9 h, score 58Used for fitting: 6.6 h, score 69Used for fitting: 8.6 h, score 74Used for fitting: 3.1 h, score 50Used for fitting: 10.2 h, score 65Used for fitting: 8.5 h, score 78Used for fitting: 5.9 h, score 75Used for fitting: 7.3 h, score 80Held out this round: 5.5 h, score 67Held out this round: 5 h, score 75Held out this round: 3 h, score 45
  • Fitted on these
  • Held out this round
  • Curve fitted without them
Error this round
25.7
All five rounds
26 · 6 · 1 · 37 · 2
Average (the CV score)
14.3
2
In each round the blue students are hidden while the curve is fitted, then used to score it. Try it: click through the five rounds at degree 2. Then switch to degree 1 and degree 6 and compare the average.

The averages come out at 85 for degree 1, 14 for degree 2, and 28 for degree 4, climbing fast after that. Cross-validation picks degree 2, the same answer the twenty new students gave, without ever touching them. They remain a true test set.

Bias and variance

There is a tidy way to describe the two ways of going wrong.

Suppose we could repeat the whole study with a different class of twelve students, again and again, fitting the same kind of model each time.

  • A rigid model would give nearly the same answer every time, and every time it would miss the real shape. That consistent miss is called .
  • A very flexible model would give a wildly different curve for each class, because it chases each class’s noise. That instability is called .
Figure

The same model, different classes

3 h, score 453.1 h, score 503.9 h, score 585 h, score 755.5 h, score 675.9 h, score 756.6 h, score 697.3 h, score 808.5 h, score 788.6 h, score 749.7 h, score 7010.2 h, score 65
  • Students used for fitting
  • Fitted curve
  • True pattern
Flexibility
degree 1: straight line
Error on fitted students
66.2
Error on new students
102.4
1
Each press draws twelve new students and refits. Earlier fits stay on screen, faded. The dashed line is the true pattern used to generate the data. Try it: at degree 1, draw six or seven new classes. Reset, set the degree to 8, and do the same.

At degree 1 the lines barely move, and all of them are wrong in the same way: high bias, low variance. At degree 8 the curves fly all over the plot: low bias, very high variance. Degree 2 or 3 gets both small at once.

Making a model more flexible lowers bias and raises variance. The skill is in finding the point between them, and more data helps too: the more students each class has, the less any flexible model can be fooled by their noise.

Checkpoint

A model has high error on its training data and almost the same high error on new data. What is the likeliest problem?

In code

scikit-learn does the splitting and the cross-validation. Here the degree is chosen by cross-validation on the training data, and the test set is used once at the end.

import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import cross_val_score, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler

# X: hours slept, one column. y: exam scores.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)

def model(degree):
    # The pipeline learns its scaling from the training folds only: no leakage.
    return make_pipeline(PolynomialFeatures(degree), StandardScaler(), LinearRegression())

scores = {}
for degree in range(1, 10):
    cv = cross_val_score(model(degree), X_train, y_train, cv=5,
                         scoring="neg_mean_squared_error")
    scores[degree] = -cv.mean()                 # average error over the five rounds

best = min(scores, key=scores.get)              # lowest cross-validation error
final = model(best).fit(X_train, y_train)
print(best, np.mean((final.predict(X_test) - y_test) ** 2))   # the one honest number

Key Takeaways

  • Training error always improves with a more flexible model. It cannot tell you when to stop.
  • Underfitting is being too simple for the pattern. Overfitting is fitting the noise.
  • Judge models on data they have not seen: tune on a validation set, report on a test set used once.
  • Cross-validation rotates the hold-out so that small datasets are used fully.
  • Flexibility trades bias for variance. The best model keeps both small.
You can now
  • Recognise underfitting and overfitting from a pair of errors.
  • Split data into training, validation and test sets, and say what each is for.
  • Describe what happens in each round of cross-validation.
  • Explain bias and variance in plain words.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exercisethink

Three models were trained on the same data. Their errors are:

ModelTraining errorValidation error
A4042
B1518
C355

Which model underfits, which overfits, and which would you choose?

Hint

Compare the two columns. Both high means too simple. A large gap means the model has fitted noise.

Solution

A underfits. Both errors are high and close together. The model is too simple to follow the pattern, so it is equally poor on old and new data.

C overfits. Its training error is tiny, and its validation error is the worst of the three. The large gap is the sign of a model that has fitted noise.

Choose B. It has the lowest validation error, and that is the only column that matters for the choice. Its small gap between the two errors is a good sign too.

Exerciseby hand

You have 20 examples and run 5-fold cross-validation. In each round, how many examples are trained on and how many are held out? How many models are trained in total, and how many times is each example held out? What would the answers be if every fold held just one example?

Hint

Five folds of equal size. Each fold takes one turn at being held out.

Solution

Five folds of 4 examples each. Every round trains on 16 and holds out 4. Five models are trained, and each example is held out exactly once.

With one example per fold there are 20 folds. Every round trains on 19 and holds out 1, and 20 models are trained. This is called leave-one-out cross-validation. It uses the data as fully as possible and costs the most computing.

Exercisethink

A friend trains 50 different models, measures each on the test set, and reports the best score, 91% accurate. What is wrong with that number, and what should they have done?

Hint

Ask whether the test set was still unseen data after it had been used to pick a winner.

Solution

The test set was used to choose among 50 models, so it is no longer unseen data. Some of those models scored well partly by luck on those particular examples, and picking the best one picks the luckiest. On fresh data the chosen model will probably score below 91%.

They should have compared the 50 models on a validation set, or by cross-validation, and then measured only the winner on the test set, once.

Exercisein code

Make 15 noisy training points from a sine curve, and 200 new points the same way. Fit curves of degree 1, 3 and 9 to the training points, and print the error of each on both sets.

Hint

np.polyfit fits the curve and np.polyval evaluates it. Compute the mean squared error on each set.

Solution
import numpy as np

rng = np.random.default_rng(0)

def sample(n):
    x = rng.uniform(0, 6, n)
    return x, np.sin(x) + rng.normal(0, 0.3, n)

x_train, y_train = sample(15)
x_new, y_new = sample(200)

for degree in (1, 3, 9):
    curve = np.polyfit(x_train, y_train, degree)
    train = np.mean((np.polyval(curve, x_train) - y_train) ** 2)
    new = np.mean((np.polyval(curve, x_new) - y_new) ** 2)
    print(degree, round(train, 3), round(new, 3))

With this seed the output is:

1 0.154 0.422
3 0.04 0.101
9 0.023 1.853

Training error falls every time the degree goes up. Error on new points falls from degree 1 to 3 and then explodes at degree 9. The noise has a variance of 0.32=0.090.3^2 = 0.09, so no model can do much better than 0.09 on new points, and degree 3 is already close.

Exercisewith the figure

In the figure “The same model, different classes”, draw six new classes at degree 1, then reset and draw six at degree 8. For each, describe how much the fitted curves differ from one another, and how far each set is from the true pattern.

Hint

One of the two is wrong in the same way every time. The other is wrong in a different way every time.

Solution

At degree 1 the six lines lie almost on top of each other, and all of them miss the rise and fall of the true curve in the same way. The model barely depends on which students it saw (low variance), and it is systematically wrong (high bias).

At degree 8 the six curves go everywhere. Each follows its own class closely and disagrees wildly with the others, especially near the edges. On average they are centred on the truth (low bias), but any single one is unreliable (high variance).

Going further

Splitting data that has structure

A random split assumes examples are independent. If the data is ordered in time, split by time, training on the past and testing on the future. If several rows belong to the same person, keep each person entirely in one pile. Otherwise the model is tested on something it has effectively already seen.

When more flexibility helps again

Very large neural networks behave in a way this chapter does not predict: past the point where they can memorise the training data, error on new data often starts falling again. This is called double descent. The classical picture here is still the right guide for the models in the first three parts of this book.

References and further reading

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 4.1A model that memorises
  3. 4.2Too simple, too flexible
  4. 4.3Training error always falls
  5. 4.4Three piles of data
  6. 4.5Cross-validation
  7. 4.6Bias and variance
  8. 4.7In code
  9. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in