Sub topic 1
What it means for a model to generalise
Prerequisites
This chapter assumes you have the following:
- Basic Python and NumPy.
- Supervised learning vocabulary: features, labels, and a loss function.
- Linear regression and the idea of fitting parameters by minimising a loss.
- Familiarity with scikit-learn's
fitandpredictworkflow.
The goal is performance on data the model has not seen
A model is trained on a finite sample, but it is used on data that does not exist yet. A spam filter sees tomorrow's emails, and a price model sees next month's listings. Generalisation is a model's ability to perform well on new data drawn from the same source as the training data.
Training data is only a means to that end. A model that reproduces its training labels perfectly has shown that it can store them. It has not shown that it can predict anything.
Training error and generalisation error
Two quantities matter, and they are easy to confuse.
- Training error is the average loss on the examples used to fit the model. You can compute it exactly. It is also called empirical risk.
- Generalisation error is the expected loss on a fresh example drawn from the true data distribution. It is also called true risk or expected risk. You can never compute it exactly, because you do not have the whole distribution.
Since the true quantity is out of reach, you estimate it. You hold out examples that the fitting procedure never touched and measure the loss on them. The held-out loss is an estimate of generalisation error. The estimate is only valid if the held-out data was truly unused during fitting.
The difference between the two is the generalisation gap:
generalisation gap = held-out error − training error
A small gap means the model behaves on new data much as it does on training data. A large gap means the training score is misleading. A small gap does not mean the model is good. A model can have a small gap and a high error on both sides, which is the underfitting case covered later in this tutorial.
Why training error is optimistic
Training error is biased downward as an estimate of generalisation error. The parameters were chosen to minimise exactly that number on exactly those examples. Any quirk of the sample that lowers the loss, including random noise in the labels, gets rewarded during fitting. A new sample has different quirks, so the fitted parameters help less there.
The more freedom the model has to bend to the sample, the larger this effect. That freedom is called capacity, and the next chapter covers it. For now, keep one rule: a model's score on its own training data tells you little about how it will do in use.
A concrete demonstration
A 1-nearest-neighbour regressor makes the effect easy to see. Each training point is its own nearest neighbour, so it is predicted exactly.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsRegressor
from sklearn.metrics import mean_squared_error
rng = np.random.default_rng(0)
X = rng.uniform(-3, 3, size=(60, 1))
y = np.sin(X).ravel() + rng.normal(0, 0.3, size=60)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0
)
model = KNeighborsRegressor(n_neighbors=1).fit(X_train, y_train)
train_mse = mean_squared_error(y_train, model.predict(X_train))
test_mse = mean_squared_error(y_test, model.predict(X_test))
print("train MSE:", round(train_mse, 3))
print("test MSE: ", round(test_mse, 3))The training MSE is exactly 0.0. The test MSE is clearly above zero. The labels contain Gaussian noise with standard deviation 0.3, and the model copied that noise into its predictions. On new points it repeats the noise of the nearest training example, and that noise is unrelated to the new label. The result is a large generalisation gap even though the training score looks perfect.
The noise floor
You should not expect held-out error to reach zero, even for an ideal model. Real labels contain variation that the features cannot explain: measurement error, missing inputs, and plain randomness. This part is called irreducible error.
In the example above, the best possible predictor is sin(x). Its expected squared error is the noise variance, 0.3² = 0.09. No model can reliably beat that on fresh data. Two practical consequences follow:
- A held-out error close to the noise floor means there is little left to gain from modelling.
- A training error far below the noise floor is a warning sign. It means the model has fitted noise.
In real projects you rarely know the noise floor. Estimates come from repeated measurements, inter-annotator disagreement on labels, or the best error that any model reaches.
What generalisation assumes
Held-out error predicts future error only under assumptions. The usual one is that training and future examples are independent and identically distributed (i.i.d.) draws from one distribution. Three situations break it.
- Distribution shift. The world changes after training, for example seasonal demand or a new camera sensor. Held-out error from the old distribution then understates real error.
- Dependent samples. Several rows from the same patient, user, or session end up on both sides of a split. The held-out set is then no longer independent of the training set, and the estimate is too good.
- Repeated peeking. You evaluate many models or settings on the same held-out set and keep the best. The winner's score is then partly luck, so the estimate is optimistic.
Summary of the vocabulary
| Term | Meaning | Can you compute it? |
|---|---|---|
| Training error | Average loss on fitted data | Yes, exactly |
| Held-out error | Average loss on unused data | Yes, as an estimate |
| Generalisation error | Expected loss on new data from the source | No, only estimate it |
| Generalisation gap | Held-out error minus training error | Yes, as an estimate |
| Irreducible error | Loss no model can remove | Rarely |
Later chapters build on these terms. They cover how flexibility changes the gap, how to split data properly, and how to shrink the gap with regularisation.
Exercise
A classifier reaches 99% accuracy on its training set and 71% on a held-out set drawn from the same source. Name the generalisation gap in accuracy points, and explain why the 99% figure should not be reported as the expected performance in use.
Show answer
The gap is 99 − 71 = 28 accuracy points (equivalently, error of 1% on training versus 29% held out). The 99% figure is optimistic because the parameters were chosen to fit exactly those examples, including their noise, so it overstates performance on new data. The held-out 71% is the better estimate of generalisation, provided that set was not used for fitting or for choosing among many models.
Exercise
In the 1-nearest-neighbour example, labels have noise with standard deviation 0.3. Roughly what MSE would the ideal predictor sin(x) achieve on fresh data, and what does a training MSE of 0.0 tell you relative to that value?
Show answer
The ideal predictor's expected MSE is the noise variance, 0.3² = 0.09. A training MSE of 0.0 is far below this noise floor, which is impossible for a model that only captured the true signal. It shows the model has fitted the noise in the training labels, so its error on new data will be higher.