Sub topic 15
One final evaluation on the test set
This chapter assumes you can split data with train_test_split, build a scikit-learn Pipeline, and run GridSearchCV. The test set is the last data you touch, and it gets one use.
What the test set is for
Cross-validation and tuning give you many scores, and you use them to make choices. You pick a model type, a feature set, and a value for C. Each choice is made by looking at validation scores. After enough choices, the best validation score is slightly optimistic, because you selected it for being high.
The test set is the fix. It was never used for training, scaling, imputing, or choosing. Its score estimates how the chosen model performs on new data.
Running the final evaluation
The code below tunes on the training data only. It then scores the test set a single time.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report, confusion_matrix
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)),
])
search = GridSearchCV(model, {"clf__C": [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))By default GridSearchCV refits the best configuration on the whole training set (refit=True). So search.predict already uses the final model. The pipeline applies the scaler fitted on training rows to the test rows.
Reading the result
Compare the test score with the cross-validation score.
- Close together: the estimate is trustworthy. Small differences of a point or two are normal noise, especially on a small test set.
- Test much lower: suspect leakage, overfitting to the validation folds through too much tuning, or a test set that differs from the training data.
- Test higher: this can happen by luck on a small test set. Don't treat it as proof the model is better than expected.
Use the metric you chose during problem framing. Also look at the confusion matrix, since a single number can hide which kind of error the model makes.
Common errors
- Peeking and retrying. If the test score disappoints and you go back to change the model, the test set has become a validation set. Its score is no longer an honest estimate.
- Tuning on the test set. Calling
GridSearchCV.fiton test rows, or choosing a threshold from test predictions, uses it for selection. - Fitting preprocessing on all data. Fit scalers and imputers on training rows only. A pipeline does this for you.
- Retraining after the test. Refitting on train plus test before deployment is common and acceptable, but only after you've reported the test score. The refit model has no untouched score of its own.
Exercise
You tune three model families using 5-fold cross-validation on the training set. The best one scores F1 = 0.96 in cross-validation and 0.91 on the test set. Which number do you report as the expected performance on new data, and why?
Show answer
Report the test-set score of 0.91. The cross-validation score was used to select the model, so it is biased upward. The test set played no part in any choice, so it gives an unbiased estimate. You may mention the gap, and check for leakage or over-tuning if it is large.