Sub topic 8
Using the test set only once
This chapter assumes you can already split data with train_test_split, know what a validation set or cross-validation is for, and have read the earlier chapter on overfitting. It covers why the test set must stay untouched until the end, and how that rule gets broken in practice.
What the test set is for
The test set answers one question: how well will the final model do on data it has never seen? That answer is only trustworthy if nothing about the model was shaped by the test rows. Each time you look at a test score and then change something, the test set becomes part of your selection process. It then behaves like a second validation set, and the score is no longer an unbiased estimate.
The bias is usually small for one extra look. It grows with the number of looks, because picking the best of many candidates by their test scores selects partly for luck.
The workflow
All choices are made on training data, using a validation set or cross-validation. The test set is scored once, at the end, on the single model you have committed to.
Example
The code below tunes the regularization strength C of a logistic regression using only cross-validation on the training set. The test set appears in the last line only.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score, 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
)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
best_c, best_score = None, -1.0
for c in [0.01, 0.1, 1, 10]:
model = make_pipeline(StandardScaler(), LogisticRegression(C=c, max_iter=1000))
score = cross_val_score(model, X_train, y_train, cv=cv).mean()
print(f"C={c}: CV accuracy {score:.3f}")
if score > best_score:
best_c, best_score = c, score
final = make_pipeline(StandardScaler(), LogisticRegression(C=best_c, max_iter=1000))
final.fit(X_train, y_train)
print("Chosen C:", best_c)
print("Test accuracy:", final.score(X_test, y_test))The pipeline refits the scaler inside each cross-validation round, so the held-out fold never influences the scaling. The final model is refit on the whole training set before the single test evaluation.
Common ways the rule gets broken
- Tuning on the test score. You try a few settings, print the test accuracy for each, and keep the best. The reported number is now optimistic.
- Peeking during exploration. Looking at test-set statistics, plots or feature distributions can steer feature choices, even without training on those rows.
- Retrying after a disappointing result. If the test score is lower than expected and you go back and change the model, the test set is spent.
- Sharing one test set across many experiments. A team that reuses a single test set for months is effectively tuning against it, even if each person looks only occasionally.
What to do when the test set is spent
If you have looked and changed things, treat the old score as a validation score. Report it honestly as such. If you can, collect or hold out fresh data and use that as a new test set. Otherwise, state how many times the test set was used.
Practical habits
- Split off the test set first, before any exploration or preprocessing.
- Keep it in a separate variable or file, and do not pass it to any function until the final step.
- Write down which model and settings are final before you score on it.
- Log every time the test set is evaluated.
Exercise
A colleague trains five models, scores each on the test set, and reports the best one's test accuracy as the expected real-world performance. What is wrong, and how should the process change?
Show answer
The test set was used to choose among models, so the best score is biased upward by selection. Compare the five models with cross-validation or a validation set on the training data, pick one, refit it on the full training set, and score the test set once for the reported number.