Sub topic 7
Adding a validation set for model selection
This chapter assumes you can run a train_test_split, know what a hyperparameter is (a setting you choose before training, such as the regularization strength C), and understand why training accuracy overstates real performance.
The problem with one test set
Suppose you train five candidate models and pick the one with the best test score. The test set has now influenced your choice. The winning score is partly luck: among several candidates, the best one on a given sample tends to look better than it really is. If you report that score, it is optimistic.
The fix is a third slice of data, the validation set. You use it to compare models and tune hyperparameters. The test set stays closed until you have made your final choice.
| Split | Used for | How often you look |
|---|---|---|
| Training | Fitting model parameters | Constantly |
| Validation | Comparing models, tuning hyperparameters | Many times |
| Test | Final performance estimate | Once |
Splitting three ways
train_test_split only makes two parts, so call it twice. Separate the test set first so nothing you do later can touch it. Then split the remainder into training and validation parts.
With test_size=0.2 and then test_size=0.25 on the remaining 80%, you get 60% training, 20% validation and 20% test, because 0.25 × 0.8 = 0.2.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train_full, X_test, y_train_full, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
X_train_full, y_train_full, test_size=0.25, stratify=y_train_full, random_state=42
)
print(len(X_train), len(X_val), len(X_test))This prints 341 114 114. Both cal so each part keeps the same class proportions, and both use a fixed random_state so the split repeats exactly.
Selecting a model
The loop below trains one model per value of C, scores each on the validation set, and keeps the best. Only then does it touch the test set.
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_full, X_test, y_train_full, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
X_train, X_val, y_train, y_val = train_test_split(
X_train_full, y_train_full, test_size=0.25, stratify=y_train_full, random_state=42
)
best_c, best_score = None, -1.0
for c in [0.001, 0.01, 0.1, 1, 10]:
model = make_pipeline(StandardScaler(), LogisticRegression(C=c, max_iter=1000))
model.fit(X_train, y_train)
score = model.score(X_val, y_val)
print(f"C={c}: validation 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_full, y_train_full)
print("Chosen C:", best_c)
print("Test accuracy:", final.score(X_test, y_test))The final model is refit on training plus validation data. Once the hyperparameters are fixed, the validation rows are no longer needed for comparison, and extra data usually helps. The pipeline refits the scaler on those rows too, so no statistics come from the test set.
Common errors
- Checking the test set "just to see". Each peek lets the result steer your decisions. If you peek and then change anything, the test set is no longer a clean estimate.
- Splitting the validation set off before the test set. Do the test split first so the held-out rows are fixed early.
- Trusting a small validation set. With 114 rows, one extra correct prediction moves accuracy by about 0.9 points. Differences that small between candidates are noise. Cross-validation, covered later, reduces this problem.
- Forgetting stratification. On imbalanced classes, a random validation set may contain very few positives.
Exercise
You tune a model with a validation set, see a test accuracy of 0.91, and are disappointed. You adjust the model and check the test set again, getting 0.94. Why is 0.94 not a trustworthy estimate of performance on new data?
Show answer
The second test evaluation came after a decision based on the first test score. The test set influenced the model, so the 0.94 is optimistic. The adjustment should have been judged on the validation set, and the test set should have been scored once.