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.
How flexible should the curve be?
- Students used for fitting
- Fitted curve
- Flexibility
- degree 1: straight line
- Error on fitted students
- 66.2
- Error on new students
- hidden
Three things happen as you raise the degree.
At degree 1 the line misses the shape entirely. This is
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
Training error always falls
Collect the two errors for every degree and plot them against each other.
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?
Two errors, two stories
- Error on fitted students
- Error on new students
- Degree
- 2
- Fitted students
- 11.9
- New students
- 28.8
- Verdict
- About right
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.
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.
| Pile | Used for | Typical share |
|---|---|---|
| Training set | Fitting the weights | 60 to 80% |
| Validation set | Choosing between models and settings | 10 to 20% |
| Test set | One final, honest measurement | 10 to 20% |
The
A setting like the degree, which you choose rather than learn, is called a
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
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.
Five rounds, five different hold-outs
- 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
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
.
The same model, different classes
- 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
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.
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.
- 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.
Three models were trained on the same data. Their errors are:
| Model | Training error | Validation error |
|---|---|---|
| A | 40 | 42 |
| B | 15 | 18 |
| C | 3 | 55 |
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.
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.
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.
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.853Training 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 , so no model can do much better than 0.09 on new points, and degree 3 is already close.
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
- G. James, D. Witten, T. Hastie and R. Tibshirani, An Introduction to Statistical Learning, chapters 2 and 5. Free at statlearning.com.
- H. Kinsley and D. Kukieła, Neural Networks from Scratch in Python, chapters 11 to 13, nnfs.io.
- MLU-Explain, The Bias Variance Tradeoff and Cross-Validation.