Sub topic 1
What We Are Really Trying to Estimate
Prerequisites
This chapter assumes you know the following:
- Supervised learning basics: features, labels, and the split between training and test data.
- Overfitting, at the level of "a model can memorize its training data".
- Basic Python and NumPy.
- scikit-learn estimators and their
fit,predict, andscoremethods.
You don't need to know cross-validation yet. The chapter after the next introduces it.
The question behind every evaluation
When you train a model, you rarely care how it does on the rows you already have. You care how it will do on rows you haven't seen: next month's customers, tomorrow's scans, the next batch of sensor readings. Every evaluation technique in this tutorial is an attempt to answer that one question without waiting for the future to arrive.
This quantity is the generalization error. It is the average loss of a model over new examples drawn from the same process that produced the training data.
Write the data-generating process as a distribution P over feature-label pairs (x, y). Write the fitted model as f and the loss function as L, for example 0 for a correct class and 1 for a wrong one. Then:
generalization error of f = E[ L(y, f(x)) ] with (x, y) drawn from PYou never see P. You only see a finite sample from it. So you can't compute this expectation. You can only estimate it from data you hold, and the rest of this tutorial is about doing that estimate honestly.
Training error is the wrong estimate
The obvious estimate is the error on the training set. It is also the worst one, because the model was fitted to minimize exactly that number.
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.3, stratify=y, random_state=0
)
model = DecisionTreeClassifier(random_state=0)
model.fit(X_train, y_train)
print("training accuracy:", model.score(X_train, y_train))
print("test accuracy: ", model.score(X_test, y_test))An unpruned decision tree can grow until every training row sits in its own pure leaf. Its training accuracy is 1.000 here. Its test accuracy is lower, typically in the low 0.90s. The gap between the two numbers is the optimism of the training score.
The test score is a better estimate because the model never saw those rows. They play the role of "new data".
Two things you can mean by "performance"
"How good is my model?" hides a distinction that matters later in the tutorial.
- A specific fitted model. This is one object, with particular learned parameters, trained on one particular training set. Its error on new data is a fixed number, though you can't observe it exactly.
- A learning procedure. This is the whole recipe: the algorithm, its settings, the preprocessing, and the way you choose among settings. Its performance is the average error you would get if you ran the recipe on many different training sets of the same size.
The two differ because a different training sample gives a different model. A held-out test score measures the first thing. It also gives a noisy hint about the second.
This tutorial argues that when the recipe includes hyperparameter tuning, the honest object to evaluate is the whole recipe, tuning included. Nested cross-validation estimates the performance of that procedure.
| Quantity | Computed on | What it tells you |
|---|---|---|
| Training error | The rows the model was fitted on | How well the model memorized. Optimistic. |
| Test error | Rows the model never touched | An estimate of the fitted model's generalization error. |
| Generalization error | Unlimited new rows from `P` | The target. You can never compute it exactly. |
Where the estimate can go wrong
Any estimate of generalization error can fail in two ways. They have different causes and different fixes.
- Bias. The estimate is wrong on average, usually too optimistic. The cause is almost always that information from the evaluation rows leaked into the model, directly or through a choice you made by looking at them.
- Variance. The estimate is right on average but noisy. A small test set, or an unlucky split, can move the number by several points.
The training-error problem above is bias. The remaining chapters of this tutorial deal with subtler sources of bias, and one chapter deals with variance.
The dashed lines show what you really care about. The solid path is the substitute you can afford.
What "honest" requires
An evaluation row gives an honest estimate only if it had no influence on the model. That influence can be sneaky. It includes:
- Fitting the model on it. This is the obvious case.
- Fitting a scaler or imputer on it before splitting.
- Choosing a hyperparameter because it scored well on that row.
- Choosing which features, which model family, or which preprocessing to keep by looking at it.
The last two are the ones people miss, because no single line of code visibly "trains on the test set". The model is fitted on training rows, yet the evaluation rows have still shaped the final pipeline through your decisions.
A small experiment: noise that looks like signal
You can see the problem directly. Generate data where the labels are pure coin flips, so no model can do better than 50% accuracy on new data. Then pick the best of many random models using the same rows you evaluate on.
import numpy as np
rng = np.random.default_rng(0)
n_eval = 100
y_eval = rng.integers(0, 2, size=n_eval)
n_candidates = 200
accuracies = []
for _ in range(n_candidates):
guesses = rng.integers(0, 2, size=n_eval)
accuracies.append((guesses == y_eval).mean())
print("mean candidate accuracy:", round(float(np.mean(accuracies)), 3))
print("best candidate accuracy:", round(float(np.max(accuracies)), 3))Every candidate is a random guesser, so its true accuracy is exactly 0.5. The mean over candidates lands near 0.5. The best one scores noticeably higher, around 0.6. If you reported that best score, you would claim skill that does not exist.
The best-of-many score is high because you took a maximum over noisy numbers. Taking a maximum always favors the candidates whose noise happened to be positive. Real hyperparameter search is less extreme, since real candidates differ in true quality and are correlated with one another. But the mechanism is the same, and the chapter titled "Why the best cross-validation score is too optimistic" returns to it with real data.
What each later chapter fixes
The outline of this tutorial follows the ways an estimate can go wrong.
- A single holdout split wastes data and is noisy. K-fold cross-validation reduces that noise.
- Tuning hyperparameters on the folds you also report turns the best score into a maximum over noisy numbers. Nested cross-validation separates the choosing from the reporting.
- Preprocessing fitted outside the folds leaks information. A scikit-learn
Pipelinekeeps it inside. - Splitters must respect the structure of the data: classes, groups, and time order.
- The estimate itself is noisy and costs many model fits. Later chapters cover how to read it, repeat it, and keep its cost under control.
Check your understanding
Exercise
A colleague tunes a random forest with 50 hyperparameter settings, picks the setting with the highest accuracy on a 200-row validation set, and reports that accuracy as the expected accuracy on new data. Is the report biased, and in which direction? Give the mechanism.
Show answer
Yes, it is biased upward (optimistic). The reported number is the maximum over 50 noisy accuracy values, all computed on the same 200 rows that were used to choose the setting. The setting that wins is partly the one whose noise on those rows happened to be favorable, so its score on fresh data will on average be lower. A cleaner estimate would score the chosen setting, or the whole tuning procedure, on rows that played no part in the choice.
Exercise
In the coin-flip experiment, why does the mean candidate accuracy sit near 0.5 while the best candidate scores noticeably higher? What would happen to the gap if you raised ncandidates to 2000, and what if you raised neval to 10000?
Show answer
Each candidate's accuracy is its true accuracy of 0.5 plus sampling noise. The mean averages the noise out, while the maximum picks the most favorable noise. With 2000 candidates the maximum is taken over more draws, so the best score rises and the gap widens. With 10000 evaluation rows the noise in each accuracy shrinks, so the best score falls toward 0.5 and the gap narrows.