Sub topic 15
One final evaluation on the test set
This chapter assumes you can build a scikit-learn Pipeline, run cross_val_score or GridSearchCV, and read a classification report. It covers how to spend your test set exactly once, how to read the number you get, and what to do when the number disappoints.
Why the test set is used once
Every time you look at a score and then change something, you fit your choices to that score. Choosing a model family, picking features and tuning hyperparameters all count. If the score came from the test set, it stops being an independent estimate. The test set then behaves like a second validation set, and the reported number is optimistic.
The test set exists to answer one question: how will the chosen model perform on data it has never influenced? That answer is only trustworthy if no decision was based on the test rows.
The division of labor looks like this:
| Data | Used for | How often |
|---|---|---|
| Training rows | Fitting parameters, fitting preprocessing | Many times |
| Validation folds (inside cross-validation) | Comparing models and hyperparameters | Many times |
| Test rows | Reporting final performance | Once |
The procedure
Do the following in order. Do not skip ahead.
- Split off the test set at the start and put it aside.
- Compare models and tune hyperparameters with cross-validation on the training rows only.
- Freeze the decision: the pipeline, its hyperparameters, the decision threshold and the metric.
- Fit the final pipeline on all training rows.
- Score it on the test set once and report the result.
A complete example
The code tunes a regularization strength with cross-validation. Only then does it evaluate on the test set. It also compares against a baseline and estimates how uncertain the test score is.
import numpy as np
from sklearn.datasets import load_breast_cancer
from sklearn.dummy import DummyClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix, f1_score
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
# Tuning sees training rows only. refit=True (the default) refits the
# best configuration on all training rows when the search ends.
search = GridSearchCV(
model, {"clf__C": [0.01, 0.1, 1, 10]}, cv=5, scoring="f1"
)
search.fit(X_train, y_train)
print("best params:", search.best_params_)
print("CV F1 (training data):", round(search.best_score_, 3))
# The one and only test-set evaluation.
y_pred = search.predict(X_test)
print(classification_report(y_test, y_pred))
print(confusion_matrix(y_test, y_pred))
# Baseline on the same test rows, for context.
dummy = DummyClassifier(strategy="most_frequent").fit(X_train, y_train)
print("baseline F1:", round(f1_score(y_test, dummy.predict(X_test)), 3))
# Bootstrap the test rows to see how much the score could vary.
rng = np.random.default_rng(0)
y_true = y_test.to_numpy()
boot = []
for _ in range(1000):
idx = rng.integers(0, len(y_true), len(y_true))
boot.append(f1_score(y_true[idx], y_pred[idx]))
low, high = np.percentile(boot, [2.5, 97.5])
print(f"test F1 95% interval: {low:.3f} to {high:.3f}")GridSearchCV.predict delegates to the refitted best pipeline, so the scaler and classifier are both fitted on training rows only. The test rows pass through the already-fitted scaler and are never used to fit anything.
Reading the result
Compare three numbers: the cross-validation score, the test score and the baseline.
- Test score close to the cross-validation score. This is the normal, healthy outcome. Expect small differences in either direction, because both are noisy estimates.
- Test score clearly lower. Suspect leakage into the cross-validation step, an over-wide hyperparameter search, or a test set that differs from the training data in distribution.
- Test score barely above the baseline. The model has learned little. The metric may also be hiding a problem. Accuracy on imbalanced data is a common case, so look at the confusion matrix.
- Test score higher than the cross-validation score. A small gap can be luck. A large gap suggests a mistake, for example duplicated rows shared between train and test.
Report the metric you named during problem framing. Do not switch to whichever metric looks best after the fact.
How much to trust one number
A test score is a sample statistic. With 114 test rows, one more or one fewer correct prediction moves accuracy by about 0.9 percentage points. The bootstrap interval in the code resamples the test rows with replacement and recomputes the metric, which gives a rough range. Use it as a guide to the size of the noise, not as an exact guarantee.
Some consequences follow:
- Two models whose test scores differ by less than the interval width are not meaningfully different on this evidence.
- A rare class makes the problem worse. If only 20 test rows are positive, recall rests on 20 outcomes.
- If the interval is too wide to support a decision, collect more data or use a larger test fraction. Do not repeat the evaluation with new random seeds until the number looks better.
Edge cases
Time-ordered data
If rows are ordered in time and the model will predict the future, the test set must be the latest period. A random split lets the model see the future during training. Use TimeSeriesSplit for cross-validation and keep the final chronological block as the test set.
Grouped rows
When several rows belong to the same patient, customer or device, put each group entirely in one side of the split. Use GroupShuffleSplit for the split and GroupKFold inside tuning. Otherwise the model is scored on entities it has already seen.
Choosing a threshold
A classification threshold is a decision. Choose it on validation data, for example from out-of-fold predictions made with cross_val_predict. Then apply that fixed threshold to the test set. Sweeping the threshold on the test set to find its best value uses the test labels for tuning.
Refitting on all the data
After you report the test score, you may refit the same frozen pipeline on training plus test rows for deployment, since more data usually helps. The reported score then describes the earlier model rather than the final one. This is acceptable when the procedure is fixed and stable, and the refit model should not be reported as having that exact score.
When the score disappoints
The temptation is to adjust the model and score again. Doing so turns the test set into a validation set. You have three honest options:
- Accept and report the result, including its weaknesses.
- Go back to training data, make changes using cross-validation, and report the new model's test score as one that has been looked at more than once. State that plainly.
- If you have fresh data, for instance a newly collected batch, use it as a new test set.
If you have already looked at the test score and changed something, say so in your report. An undisclosed second look is the common way final scores become inflated.
What to report
A useful final report includes the metric and its definition, the test score with an uncertainty range, the baseline score, the cross-validation score for comparison, the sizes of the training and test sets, and the confusion matrix or per-class results. It should also state the date of the data and any known differences between the data and what the model will see in use.
Exercise
A teammate tunes hyperparameters with 5-fold cross-validation, gets CV F1 of 0.95, and scores 0.91 on the test set. They are unhappy and try three more model types, scoring each on the test set. The best gets 0.94, and they report it as the expected performance. What is wrong, and what should they do instead?
Show answer
Selecting among several models by their test scores uses the test set for model selection, so the 0.94 is optimistically biased, because it is the best of several noisy draws. They should compare the extra model types with cross-validation on the training rows, freeze the winner, and evaluate it on the test set once. If the test set has already been used this way, they should report that it was looked at multiple times, or obtain fresh data for an untouched evaluation. The original 0.91 versus 0.95 gap is itself normal noise and does not signal a problem.