Sub topic 1
Why we need to estimate generalization error
A model is trained on data it has seen, but it is used on data it has not seen. This chapter explains why the first number tells you little about the second. It also explains why you need a deliberate way to estimate the second number. Later chapters build cross-validation on this foundation.
Prerequisites
This chapter assumes you know the following:
- Supervised learning basics: features, labels, and what it means to train a model.
- Overfitting and underfitting at a conceptual level.
- Common metrics such as accuracy.
- Basic Python and NumPy.
- scikit-learn's
fit,predict, andscoremethods.
What generalization error means
A supervised model learns a function from a finite sample. You care about how it behaves on new samples drawn from the same process. That quantity is the generalization error (also called the true risk or expected prediction error). It is the average loss the model would incur over every example the data source could produce.
You can never compute it exactly, because you do not have every possible example. You can only estimate it from the data you have. Everything in cross-validation is about producing that estimate and knowing how far to trust it.
Two related quantities are easy to confuse with it:
- Training error is the loss measured on the data used to fit the model.
- Test error is the loss measured on data the model never saw during fitting. It is an estimate of generalization error, not the thing itself.
Why training error is optimistic
A model is fitted to minimize loss on its training set. Any pattern in that set, including noise, can be absorbed into the parameters. The more flexible the model, the more noise it can memorize. Training error therefore sits below generalization error, and the gap grows with model flexibility.
The following example makes the gap visible. An unconstrained decision tree can grow until every training sample sits in a pure leaf.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
print(f"train accuracy: {tree.score(X_train, y_train):.3f}")
print(f"test accuracy: {tree.score(X_test, y_test):.3f}")The training accuracy is 1.000, because the tree has memorized the training set. The test accuracy is lower, usually by several points. If you had reported the first number, you would have overstated the model's quality.
Bias in the estimate versus noise in the estimate
An estimate of generalization error can be wrong in two different ways. Keep them separate, because different techniques fix each one.
- Bias is a systematic tendency to be too optimistic (or, less often, too pessimistic). Scoring on training data is biased. So is scoring on data that influenced any modeling choice.
- Variance is random scatter. A different sample of test data would have given a different number, even if the estimate is unbiased on average.
A held-out test set removes the first problem. It does not remove the second, and the next section shows why.
Why a small test set gives a noisy number
Suppose the true accuracy of a model is p, and you score it on n independent test samples. The measured accuracy has a standard error of about sqrt(p * (1 - p) / n). Plugging in numbers for p = 0.9:
| Test samples (`n`) | Standard error | Rough 95% interval (±1.96 SE) |
|---|---|---|
| 50 | 0.042 | ±0.083 |
| 100 | 0.030 | ±0.059 |
| 1,000 | 0.0095 | ±0.019 |
| 10,000 | 0.0030 | ±0.006 |
With 100 test samples, a reported accuracy of 0.90 is compatible with a true value anywhere from about 0.84 to 0.96. Two models that differ by two points cannot be told apart at that size.
This formula covers only the noise from the test sample. A second source of noise comes from which samples ended up in the training set. You can see both at once by repeating a holdout split with different random seeds.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
accs = []
for seed in range(20):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=seed, stratify=y
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
accs.append(model.score(X_test, y_test))
accs = np.array(accs)
print(f"min={accs.min():.3f} max={accs.max():.3f} std={accs.std():.3f}")The model and the data are the same in all 20 runs. Only the split changes. Expect the best and worst scores to differ by a few percentage points. If you had run only one seed, you would not have known which end of that range you landed on.
Ways the estimate gets spoiled
Most real-world failures come from the evaluation setup, not from the model. These are the common ones.
- Scoring on training data. Described above. It is the simplest error and still very common, for example when someone calls
model.score(X, y)on the same arrays used infit. - Tuning against the test set. If you try ten hyperparameter settings and report the best test score, the test set has influenced your choice. The reported number is now biased upward. You have picked the setting that happened to suit those specific test samples.
- Leakage through preprocessing. Fitting a scaler, imputer, or feature selector on all the data before splitting lets information from the test samples reach training. Chapter 6 covers this in detail.
- Related samples on both sides of the split. If several rows come from one patient, one user, or one device, a random split puts siblings in both sets. The model can recognize the patient instead of learning the disease.
- Ignoring time order. If you predict the future, a random split lets the model train on data that is later than some of its test data.
The first two items are about bias that you can see coming. The last three are about leakage, which makes an estimate look good for reasons that will not hold in production.
What a good estimate needs
Putting this together, a useful estimate of generalization error should have these properties:
- It is computed on data that played no part in fitting, tuning, or preprocessing.
- It uses enough data that the noise is small relative to the differences you care about.
- It comes with a measure of its own uncertainty, not a single bare number.
- Its splits respect the structure of the data (classes, groups, time) so that the test conditions resemble deployment conditions.
A single holdout split satisfies the first property and little else. Setting aside 20% of the data for testing wastes that data for training, and the result still depends on one random draw. Cross-validation addresses this by repeating the train and test procedure across several splits, so that every sample is used for testing once and the scores can be averaged.
Summary of the key ideas
| Term | Meaning | Common failure |
|---|---|---|
| Generalization error | Expected loss on new data from the same source | Cannot be computed exactly, only estimated |
| Training error | Loss on the data used for fitting | Too optimistic for flexible models |
| Test error | Loss on data unseen during fitting | Noisy when the test set is small |
| Bias of an estimate | Systematic over- or under-estimate | Tuning or preprocessing on the test set |
| Variance of an estimate | Scatter across different splits or samples | Trusting a single split |
The next chapter examines the holdout split in detail and shows where it falls short. After that, k-fold cross-validation is introduced as the remedy.
Exercise
You train a random forest on 1,000 rows and score it with model.score(X_train, y_train), getting 0.99. You then score it on 200 held-out rows and get 0.86. Which number estimates generalization error, and roughly how much noise should you expect in it if the true accuracy is about 0.86?
Show answer
The held-out score of 0.86 is the estimate. The training score of 0.99 is optimistic because the forest has fit the training rows. The standard error of the held-out score is about sqrt(0.86 * 0.14 / 200), which is about 0.025, so a rough 95% interval is 0.86 ± 0.05, or about 0.81 to 0.91. This covers only test-sample noise, not the extra noise from the choice of training rows.
Exercise
A colleague evaluates eight hyperparameter settings on the same test set and reports the best test accuracy as the model's expected real-world accuracy. What is wrong with this, and in which direction is the error?
Show answer
The test set was used to select the setting, so it is no longer independent of the modeling choices. The best of eight noisy scores is biased upward, so the reported accuracy is likely higher than what the model will achieve on new data. A separate validation set or cross-validation should be used for selection, with a final test set (or nested cross-validation) used only for the final estimate.