Sub topic 8
Using the Test Set Only Once
This chapter assumes you can run train_test_split in scikit-learn, you know what a validation set is for, and you have seen cross-validation used to compare models. The earlier chapters cover those topics. Here the question is what happens to the test set once you start using it, and how to keep it useful.
The test set is a one-shot measurement
A test set exists to answer one question: how will the final model perform on data it has never influenced? The answer is only valid if nothing about the model, the features, or the settings was chosen with knowledge of the test rows.
Each time you look at a test score and then change something, you pass a little information from the test set into your decisions. One look does little harm. Many looks add up. The model is then partly fitted to the test set, even though it never trained on those rows. This effect is called adaptive overfitting. The test score becomes optimistic, and the test set no longer measures generalization.
How the test set gets used up
The effect is easy to see with a simulation where no model can have any skill. The labels below are random coin flips, and each "model" guesses at random. The true accuracy of every model is 0.5. We pick the best of 200 models by its score on one fixed test set.
import numpy as np
rng = np.random.default_rng(0)
n_test = 100
y_test = rng.integers(0, 2, size=n_test)
scores = []
for _ in range(200):
predictions = rng.integers(0, 2, size=n_test)
scores.append((predictions == y_test).mean())
print("Average model:", round(float(np.mean(scores)), 3))
print("Best model: ", round(float(np.max(scores)), 3))The average stays near 0.50. The best score is typically 0.62 to 0.65. Choosing the winner by test score turned pure noise into an apparent 12 to 15 point edge. A real tuning process is less extreme, but it has the same mechanism. The more candidates you compare on the test set, the more the winning score reflects luck.
A workflow that protects the test set
The fix is a fixed order of work. Everything that involves choosing happens on the training data. The test set is touched once, at the end.
- Split off the test set first, before any exploration or preprocessing.
- Do all development on the training portion. Use a validation set or cross-validation to compare models, features, and hyperparameters.
- Freeze the decisions. Refit the chosen configuration on all of the training data.
- Score the final model on the test set once.
- Report that number, whatever it is.
In scikit-learn, GridSearchCV follows steps 2 and 3 for you. It cross-validates every setting on the data you give it, then refits the best setting on all of that data. Pass it only the training portion.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, StratifiedKFold, 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.2, stratify=y, random_state=42
)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
param_grid = {"logisticregression__C": [0.01, 0.1, 1, 10, 100]}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
search = GridSearchCV(pipe, param_grid, cv=cv)
search.fit(X_train, y_train)
print("Best settings:", search.best_params_)
print("Cross-validated accuracy:", round(search.best_score_, 3))
# The only use of the test set in the whole script.
print("Test accuracy:", round(search.score(X_test, y_test), 3))The test data appears in one line, after the search has finished. Putting the scaler inside the pipeline also keeps it from learning statistics from validation folds, which the leakage chapters cover.
What counts as looking at the test set
Computing a test score is the obvious peek. There are less obvious ones. The rule is that no decision may depend on test data.
| Action | Counts as a peek? |
|---|---|
| Comparing two models by test accuracy and keeping the better one | Yes |
| Tuning a threshold until test recall looks good | Yes |
| Stopping training when test loss stops improving | Yes |
| Dropping a feature after seeing it behave oddly on test rows | Yes |
| Fitting a scaler or imputer on the test rows | Yes (leakage) |
| Running an exploratory plot on the full dataset before splitting | Yes, if it changes your choices |
| Checking that the test set has the expected number of rows | No |
| Calling `predict` on the test set to check the pipeline runs, without reading the score | Borderline, avoid it |
Early stopping is a common surprise. A training loop that monitors a held-out set and keeps the best epoch is selecting a model with that set. The monitored set must therefore be a validation set, not the test set.
If you have already peeked
If you tuned against the test set, the cleanest option is to treat it as what it has become: a validation set. Then get a new test set, either by collecting fresh data or by setting aside rows that nobody has looked at.
Do not re-split the same data randomly and call the new test portion clean. Some of those rows were in the old test set, and your choices already adapted to them. The information is in your decisions, not only in the rows.
If no fresh data exists, report the number with a note that it was also used for selection. A caveated score is more useful than one presented as clean.
When the data is too small for a fixed test set
With a few hundred rows, a single 20% test set is noisy, and spending it once leaves you with one number of uncertain quality. Nested cross-validation is the usual alternative. An outer loop holds out each fold in turn for evaluation. An inner loop runs the full tuning procedure on the remaining folds. The outer scores estimate how well the whole procedure, tuning included, will perform. No row is used for both selection and scoring within one outer round.
The trade-offs are cost and meaning. Nested cross-validation fits many models. It also evaluates the procedure rather than one final model. You still need to refit on all the data to get something to deploy.
Reading a single test score
A test score has sampling error, so a single number should come with a rough margin. For accuracy p on n test rows, the standard error is about sqrt(p * (1 - p) / n).
On the breast cancer example, 20% of 569 rows gives 114 test rows. At an accuracy of 0.97, the standard error is about sqrt(0.97 * 0.03 / 114), which is 0.016. A 95% interval is roughly 0.97 plus or minus 0.03. Two models that differ by half a point on this test set cannot be told apart. This is another reason not to chase small test differences: the gap you are tuning toward is smaller than the noise.
Reusing a test set across many projects
The same problem appears at larger scale. If a team evaluates many models over months on one shared benchmark, the benchmark is consumed gradually, even if each person evaluates only a few times. Some practical limits help:
- Keep a final holdout that only a designated person runs, rarely, at release time.
- Log every evaluation of the holdout. A count of how often it was used tells readers how much to trust it.
- Refresh the holdout when new labeled data arrives, and retire the old one into the validation pool.
Public and private leaderboards in competitions use this idea. The public part is scored often and gets overfit. The private part is scored once.
Summary of rules
- Split off the test set before any decisions.
- Select on validation data or cross-validation folds only.
- Freeze every choice, then evaluate once.
- Report the result with its uncertainty, even when it is disappointing.
- If you peeked, say so and replace the test set.
Exercise
A teammate trains five models, scores each on the test set, picks the one with the highest accuracy (0.94), and reports "expected accuracy on new data: 0.94". What is wrong, and what should they do instead?
Show answer
The test set was used to select among the models, so the reported 0.94 is the maximum of five noisy scores and is biased upward. They should compare the five models with cross-validation or a validation set on the training data, pick the winner there, refit it, and score the test set once. If the test set has already been used this way, they should say so and get fresh data for an honest estimate.
Exercise
In the GridSearchCV example, search.best_score_ and search.score(X_test, y_test) are different numbers. Which one is the estimate of performance on new data, and why is the other one not suitable for that purpose?
Show answer
The test score is the estimate, because the test rows played no part in choosing the settings or fitting the model. best_score_ is the highest cross-validated score among several candidate settings, so it is slightly optimistic: the setting was picked because it scored highest on those folds.