Sub topic 2
Splitting data: train, validation, and test
This chapter assumes you know supervised learning basics, can use scikit-learn's fit, predict, and score, and understand overfitting. Here you will learn what each data split is for and how to create the splits without leaking information between them.
Why one split is not enough
A model fit on some rows will usually score well on those same rows. That score says little about new data. You hold rows back and score the model on them, so the score estimates how the model will behave in production.
That estimate only holds if the held-out rows play no part in building the model. Every decision you make while looking at held-out scores uses up some of their independence. Data leakage often begins here, and a single holdout set cannot protect you from it.
The three roles
| Split | Used for | Who sees it |
|---|---|---|
| Training | Fitting model parameters | The learning algorithm |
| Validation | Comparing models, choosing hyperparameters, early stopping | You, many times |
| Test | One final estimate of performance | You, once |
The validation set absorbs your repeated decisions. If you try 50 settings and keep the best validation score, that score is optimistically biased, because you selected the maximum of 50 noisy numbers. The test set is untouched by that selection, so its score is still an honest estimate.
Creating a three-way split
train_test_split produces two parts, so call it twice. Split off the test set first. This makes the test set independent of every later step.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
X, y = make_classification(n_samples=1000, n_features=10, random_state=0)
# 1. Set the test set aside first: 20% of all rows
X_temp, X_test, y_temp, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
# 2. Split the remainder: 25% of 800 rows = 200 validation rows
X_train, X_val, y_train, y_val = train_test_split(
X_temp, y_temp, test_size=0.25, stratify=y_temp, random_state=0
)
print(len(X_train), len(X_val), len(X_test)) # 600 200 200
# Choose a hyperparameter using the validation set only
best_c, best_score = None, -1.0
for c in [0.01, 0.1, 1, 10]:
model = LogisticRegression(C=c, max_iter=1000).fit(X_train, y_train)
score = model.score(X_val, y_val)
if score > best_score:
best_c, best_score = c, score
# Refit with the chosen setting, then touch the test set exactly once
final = LogisticRegression(C=best_c, max_iter=1000).fit(X_train, y_train)
print(best_c, best_score, final.score(X_test, y_test))Three details matter in this code.
stratifykeeps the class proportions the same in every part. This matters most when one class is rare, because a random split could leave a small split with almost no positives.random_statemakes the split reproducible. Without it, two runs compare models on different rows, and you cannot tell a real improvement from a different draw.- The test set is scored once, after all choices are made. If the test score disappoints and you go back to change the model, the test set has become a second validation set.
Common mistakes
- Choosing split sizes by habit. 60/20/20 is a convention, not a rule. With few rows, a small validation set gives a noisy score, and cross-validation (covered in a later chapter) is usually a better fit. With millions of rows, a few percent is enough for each held-out part.
- Looking at the test set early. Plotting test-set distributions or checking its score "just to see" lets that information influence your choices.
- Splitting too late. Any step that learns from data, such as scaling, imputing, or selecting features, must happen after the split and use training rows only. The next chapters show how this goes wrong.
- Assuming rows are independent. A random split treats every row as interchangeable. Time-ordered data and repeated records of the same person or item break that assumption, and they need different splitting methods, also covered later.
Exercise
You have 2,000 rows. You split them 60/20/20 into training, validation, and test sets. You try 30 hyperparameter settings, pick the one with the best validation accuracy of 0.91, and then report 0.91 as your expected production accuracy. What is wrong, and what should you report instead?
Show answer
The validation score was used to select the best of 30 settings, so it is biased upward. It is not an honest estimate. Refit with the chosen setting (on the training rows, or on training plus validation rows), score the untouched test set once, and report that number.