Sub topic 7
Adding a validation set for model selection
This chapter assumes you can split data with train_test_split, know what overfitting is, and have fit a scikit-learn model before. It covers why two sets are not enough once you start making choices, how to build a three-way split, and how to use the middle set without damaging the final test.
The problem with two sets
A train/test split gives you one honest number: the score on data the model never saw. That number is only honest if you look at it once. Real projects involve many decisions:
- Which algorithm to use (logistic regression, random forest, gradient boosting).
- Which hyperparameters to set, such as regularization strength or tree depth.
- Which features to keep.
- Which decision threshold to use for a classifier.
Each decision needs a score to compare options. You cannot use the training score, because it rewards memorization. If you use the test score, you start tuning the model to the test set. After a few rounds, the test score is no longer an estimate of performance on new data. It is the score of the option that happened to do best on those particular rows.
The fix is a third set. The validation set is a portion of labeled data used to compare candidate models and settings. The test set is held back until the choices are finished.
| Set | Used for | How often you look at it |
|---|---|---|
| Training | Fitting model parameters | Constantly |
| Validation | Comparing models, tuning hyperparameters, choosing thresholds | Many times |
| Test | One final estimate of performance on new data | Once |
Why the validation score gets optimistic
Selecting the best of many candidates is a form of fitting. Suppose you try 50 hyperparameter combinations, and each has a true accuracy of 90%. On a validation set of 100 rows, each measured score has random noise of a few percentage points. The best of 50 noisy scores will be above 90% by chance alone. The winner's validation score is biased upward, and the bias grows with the number of candidates and shrinks with the size of the validation set.
This is why the validation score cannot be your final report. The test set exists to give an unbiased number for the one model you chose, because the test set had no part in the choice.
Building a three-way split
train_test_split only makes two parts, so you call it twice. Separate the test set first. That way the test rows are fixed before any modeling decision exists, and nothing you do afterward can influence them.
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))The second call uses test_size=0.25, not 0.2. After the first split, 80% of the data remains. A quarter of 80% is 20% of the original, so you get a 60/20/20 split. On this dataset of 569 rows, that prints 341 114 114.
Both calls pass stratify so the class proportions match across all three sets, and both fix random_state so the split can be repeated. Both ideas were covered in earlier chapters. They matter more here because small validation sets are noisy, and a validation set that happens to have a different class balance makes the noise worse.
Using the validation set to choose
With the split in place, model selection is a loop. Fit each candidate on the training set only. Score each on the validation set only. Keep the best.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
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
)
candidates = {
"logreg C=0.01": make_pipeline(StandardScaler(), LogisticRegression(C=0.01, max_iter=1000)),
"logreg C=1": make_pipeline(StandardScaler(), LogisticRegression(C=1.0, max_iter=1000)),
"logreg C=100": make_pipeline(StandardScaler(), LogisticRegression(C=100.0, max_iter=1000)),
"forest depth=3": RandomForestClassifier(max_depth=3, random_state=0),
"forest depth=None": RandomForestClassifier(max_depth=None, random_state=0),
}
val_scores = {}
for name, model in candidates.items():
model.fit(X_train, y_train)
val_scores[name] = model.score(
print(f"{name:20s} train={model.score(X_train, y_train):.3f} val={val_scores[name
best_name = max(val_scores, key=val_scores.get)
print("Selected:", best_name)Notice thatop prints both training and validation scores. A model with a training score near 1.000 and a noticeably lower validation score is overfitting. A model with low scores on both is underfitting. The gap between the two columns is the diagnostic that the two-set workflow could not give you without spending the test set.
The scaler sits inside each pipeline, so it is fit on training rows only when you call fit. The forests do not need scaling.
Ties are common on small validation sets. When two candidates differ by one or two rows, prefer the simpler model, because the difference is within noise.
The final step: evaluate once
After you pick best_name, you have two decisions to make about the final model.
- Refit or keep. You can keep the model trained on the 60% training set, or refit the same configuration on training plus validation (80%) before testing. Refitting uses more data and usually helps a little, especially with small datasets. It is safe because the configuration is already fixed, so the validation rows are no longer needed for choosing. The cost is that you can no longer check the refit model on validation data, since it has seen those rows.
- Score on test, once. Report that number and stop.
best_model = candidates[best_name]
# Option A: score the model as trained on the 60% training set.
print("Test accuracy:", best_model.score(X_test, y_test))If the test score comes out worse than you hoped, resist the urge to go back and try more candidates. Any change you make in response to the test score turns the test set into a second validation set. The next chapter covers this discipline in detail.
Choosing what to put in each role
Several practical points affect whether the three-way split works.
- Split before anything else. Feature scaling, imputation, encoding, and feature selection that use statistics from the data must be fit on the training set only. Fitting them on all rows before splitting lets validation and test information leak into training.
- Keep the validation set large enough to discriminate. With 100 validation rows, one row is a full percentage point of accuracy. Differences smaller than the standard error, roughly
sqrt(p * (1 - p) / n), are not meaningful. For accuracy near 0.95 with n = 114, that is about 0.02, so two models at 0.947 and 0.956 cannot be separated. - Match the split style to the data. If rows come in groups (several samples per patient) or have an order in time, a random split puts near-duplicates on both sides. Use grouped or time-ordered splits for the outer test split and for the validation split. Later chapters cover both.
- Do not use the validation set for training afterward without saying so. Refitting on training plus validation is fine, but then you have no unbiased validation score for that refit model. Your only honest estimate is the test set.
- Be careful with very small datasets. If a 60/20/20 split leaves a few dozen rows in each part, any single validation score is too noisy to trust. Cross-validation addresses this by rotating which rows serve as validation, so every training row is used for validation exactly once.
Common mistakes
| Mistake | What goes wrong | Fix |
|---|---|---|
| Tuning on the test set | Test score is biased upward and no longer measures new-data performance | Tune on the validation set only |
| Splitting validation from test first, then training | Order does not matter for correctness, but forgetting to separate the test set before experiments does | Always carve out the test set first |
| Using `test_size=0.2` in the second split | Validation is 16% and training is 64% of the total, not the intended 20% and 60% | Compute the fraction relative to the remainder |
| Forgetting `stratify` on the second call | Validation class balance drifts from the training set | Pass `stratify=y_train_full` |
| Reporting the best validation score | Winner's curse inflates the number | Report the test score |
Where the validation set stops being enough
A single validation split is simple and cheap, and it is the right default for large datasets where 20% is thousands of rows. Its weakness is variance: the choice of model depends on which rows landed in validation. A different random_state might pick a different winner. If you notice the ranking of your candidates changes when you change the seed, the validation set is too small or the candidates are too close to separate. That is the signal to move to cross-validation, which averages over several validation folds and is the topic of a later chapter. The test set stays untouched either way.
Exercise
You split a 1,000-row dataset with train_test_split(X, y, test_size=0.2) to get the test set, then call train_test_split again on the remaining rows with test_size=0.2 to get a validation set. How many rows are in each of the three sets, and what would you change to get a 60/20/20 split?
Show answer
The first call gives 800 remaining rows and 200 test rows. The second call takes 20% of 800, so 160 validation rows and 640 training rows. That is 64/16/20. To get 60/20/20 (600/200/200), set test_size=0.25 in the second call, because 25% of 800 is 200.
Exercise
You compare 40 hyperparameter settings on a validation set and the best one scores 0.93. You then score it on the test set and get 0.90. Is this a sign that something went wrong? Explain, and say which number you should report.
Show answer
Not necessarily. Picking the maximum of 40 noisy validation scores biases the winner's score upward, so a drop on fresh data is expected. The test set was not involved in the selection, so 0.90 is the unbiased estimate and is the number to report. A large gap, or a gap that grows as you try more settings, suggests the validation set is too small or too heavily searched.