Sub topic 2
The holdout split and its limits
This chapter covers the simplest way to estimate how well a model will do on new data: set some data aside and score the model on it. It assumes you know supervised learning basics, the idea of overfitting, basic Python and NumPy, and the scikit-learn fit, predict and score methods. By the end you should know what a holdout split gives you, how much noise it carries, and why using it for both tuning and final reporting breaks it. That last point is the motivation for the rest of this tutorial.
What a holdout split does
A holdout split divides your labeled data once into two disjoint parts:
- The training set is the part the model learns from.
- The test set (also called the holdout set) is the part the model never sees during fitting. You score the model on it once, and that score is your estimate of generalization performance.
The reasoning is simple. A model's score on its own training data is too flattering, because the model has had the chance to memorize it. Data the model has never touched behaves like the future data you actually care about, so its score is an honest estimate.
In scikit-learn the split is done with train_test_split:
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)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
print("train accuracy:", model.score(X_train, y_train))
print("test accuracy: ", model.score(X_test, y_test))Three details matter here:
test_size=0.25puts a quarter of the rows in the test set.stratify=ykeeps the class proportions the same in both parts. Without it, a small or imbalanced dataset can end up with a test set whose class mix differs noticeably from the training set. Later chapters cover splitters in more detail.random_state=0fixes the shuffle so the result can be reproduced.
The scaler sits inside a pipeline, so it is fitted only on the training rows. That keeps test-set statistics out of the training process. A later chapter treats this in depth.
Limit 1: the estimate depends on which rows landed in the test set
The test score is a single number computed from a single random split. A different shuffle gives a different test set, and therefore a different score, even though the model and the data have not changed.
You can measure this directly by repeating the split with different 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)
scores = []
for seed in range(30):
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=seed
)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
model.fit(X_train, y_train)
scores.append(model.score(X_test, y_test))
scores = np.array(scores)
print(f"min {scores.min():.3f} max {scores.max():.3f}")
print(f"mean {scores.mean():.3f} std {scores.std():.3f}")Run this and look at the spread between the minimum and maximum. For a dataset of this size it is typically a few percentage points. The model is the same in every iteration. Only the split changed.
You can predict the size of this noise without running anything. Accuracy on a test set of n rows behaves roughly like a proportion estimated from n Bernoulli trials, so its standard error is about sqrt(p * (1 - p) / n). With p = 0.97 and n = 143 (a quarter of the 569 rows in this dataset), that is about 0.014, or 1.4 percentage points. Two models whose true accuracies differ by one point cannot be told apart reliably with a test set this size.
Note that this formula covers only the noise from the finite test set. Part of the variation you see across seeds also comes from the training set changing, since each split trains on different rows.
Limit 2: data is spent twice
Every row in the test set is a row the model did not learn from. With a 25% test set, the final model has 75% of the data to work with. This costs more on small datasets or on problems where more data keeps improving the model.
You are stuck with a trade-off:
| Choice | Effect on the estimate | Effect on the model |
|---|---|---|
| Larger test set | Less noisy score | Trained on less data, so the score describes a weaker model |
| Smaller test set | Noisier score | Trained on more data, closer to the model you will deploy |
There is no test size that fixes both problems. Cross-validation, introduced in the next chapter, addresses this by letting every row serve in both roles across different rounds.
Limit 3: the split may not respect the data's structure
A random shuffle assumes the rows are independent and identically distributed. Several common situations break that assumption:
- Repeated measurements. If the same patient, customer or machine appears in many rows, a random split puts some of their rows in training and others in test. The model can then recognize the individual instead of learning the general pattern, and the score is inflated.
- Time order. If you will predict the future from the past, shuffling lets the model train on data from after the test rows. The score will look better than real use would.
- Rare classes. Without stratification, a rare class may be nearly absent from the test set.
Plain train_test_split with shuffling is the right tool only when rows really are exchangeable. A later chapter covers grouped and time-ordered splitters.
Limit 4: the test set can be used up
The most important limit is about how you use the split, not about statistics. A test set gives an honest score only if it plays no part in any decision about the model. Suppose you evaluate five model variants on the test set and keep the best. The reported score is now the maximum of five noisy numbers, and the maximum of noisy numbers is biased upward. The test set has become part of model selection.
The same thing happens more quietly. You look at the test score, change a setting, look again, and repeat. No single step feels like cheating, but each look leaks a little information from the test set into your choices.
The standard fix is a three-way split:
- Training set: fit the model's parameters.
- Validation set: compare candidates and choose settings.
- Test set: score the single chosen model once, at the end.
Here is the pattern in code. The setting being compared is the regularization strength C of a logistic regression. The next chapters explain what such settings are and how to tune them systematically.
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)
# First carve off the test set, then split the rest into train and validation.
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
X_train, X_val, y_train, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=0
)
best_C, best_val = None, -1.0
for C in [0.001, 0.01, 0.1, 1, 10, 100]:
model = make_pipeline(StandardScaler(), LogisticRegression(C=C, max_iter=1000))
model.fit(X_train, y_train)
val_score = model.score(X_val, y_val)
print(f"C={C:<6} validation accuracy={val_score:.3f}")
if val_score > best_val:
best_C, best_val = C, val_score
final = make_pipeline(StandardScaler(), LogisticRegression(C=best_C, max_iter=1000))
final.fit(X_train, y_train)
print("chosen C:", best_C)
print("validation score of chosen model (optimistic):", round(best_val, 3))
print("test score (touched once):", round(final.score(X_test, y_test), 3))Pay attention to the labels in the output. The validation score of the winner is optimistic, for the same reason as above: it is the best of several noisy scores. The test score is the one to report, because the test set made no choices.
Why this leads to cross-validation, and then to nesting
The limits above form a chain:
- One split gives one noisy score.
- Making the test set bigger removes training data.
- Tuning on any fixed set of rows makes the best score on those rows optimistic.
K-fold cross-validation, covered next, answers the first two by rotating which rows are held out and averaging. It does not answer the third. Once you use cross-validation scores to pick the best hyperparameters, the best score has the same optimism that the validation score has here. Nested cross-validation, the subject of this tutorial, is the repair for that problem.
Exercises
Exercise
A classifier scores 0.90 accuracy on a holdout test set of 100 rows. Using the standard error formula sqrt(p * (1 - p) / n), roughly how large is the noise in that score, and what does it imply about a second model that scores 0.92 on the same test set?
Show answer
The standard error is sqrt(0.9 * 0.1 / 100) = sqrt(0.0009) = 0.03, so about 3 percentage points. The 0.02 difference is smaller than one standard error, so the test set gives little evidence that the second model is better. (Comparing models on the same rows is somewhat less noisy than this formula suggests, but a gap this small is still weak evidence.)
Exercise
You compare ten model configurations on your test set and report the score of the best one. Why is the reported number not an honest estimate of how that configuration will perform on new data, and how would a three-way split change the procedure?
Show answer
The best of ten noisy scores is biased upward, because the winner is partly the configuration that got lucky on those test rows. The test set was used to make a decision, so it no longer measures performance on unseen data. With a three-way split, the ten configurations are compared on the validation set, and only the single chosen model is scored on the test set, once. The test score then reflects no selection. The validation score of the winner remains optimistic.
Exercise
A dataset has 20 rows per patient from 500 patients, and you want to predict outcomes for new patients. What is wrong with a shuffled traintestsplit on rows, and what should the split respect instead?
Show answer
Rows from the same patient will appear in both training and test sets, so the model can partly recognize patients instead of generalizing to new ones, which inflates the score. The split should keep all rows of a patient on the same side, using a grouped splitter, so that the test set contains only patients the model has never seen.