Sub topic 4
Train, validation, and test splits
This chapter assumes you can train a scikit-learn model and call predict. It also assumes you know what overfitting is. Here you will learn why tuning needs three data sets instead of two, and how to build them.
Why two sets are not enough
A model's score on its own training data is too optimistic, because the model has already seen those rows. So you hold some data back and score on it.
Tuning creates a second problem. Each time you try a setting and look at the held-out score, you use that data to make a choice. After dozens of trials, the best score is partly luck. The setting that won looks good on that data in particular. The held-out score is no longer an honest estimate of future performance.
The standard fix is three sets with three jobs:
| Set | Used for | How often you look at it |
|---|---|---|
| Training | Fitting the model's learned parameters | Every trial |
| Validation | Comparing hyperparameter settings | Every trial |
| Test | One final estimate of performance | Once |
The workflow
A worked example
This code makes a 60/20/20 split by calling train_test_split twice. The second call takes 25% of the remaining 80%, which is 20% of the total. The stratify argument keeps the class proportions the same in every set.
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_temp, X_test, y_temp, y_test = train_test_split(
X, y, test_size=0.2, random_state=0, stratify=y
)
X_train, X_val, y_train, y_val = train_test_split(
X_temp, y_temp, test_size=0.25, random_state=0, stratify=y_temp
)
best_depth, best_score = None, 0.0
for depth in [2, 4, 8, 16]:
model = RandomForestClassifier(max_depth=depth, random_state=0)
model.fit(X_train, y_train)
score = accuracy_score(y_val, model.predict(X_val))
print("max_depth", depth, "validation accuracy", round(score, 3))
if score > best_score:
best_depth, best_score = depth, score
final = RandomForestClassifier(max_depth=best_depth, random_state=0)
final.fit(X_temp, y_temp)
print("Chosen max_depth:", best_depth)
print("Test accuracy:", accuracy_score(y_test, final.predict(X_test)))The loop compares settings using only the validation set. After the best setting is chosen, the final model is refit on training plus validation data, since more data usually helps. The test set is touched once, on the last line.
Common errors
- Peeking at the test set. If a test score makes you change a setting and try again, the test set has become a second validation set. You then need fresh data to get an honest estimate.
- Fitting preprocessing on all the data. Computing scaling statistics or imputation values before splitting leaks information from validation and test rows into training. Fit these steps on training data only. Pipelines, covered later in this tutorial, do this for you.
- Random splits on dependent rows. If one patient or customer has several rows, split by group (for example with
GroupKFold). Otherwise near-duplicates land on both sides of the split. For time series, split by time so the model never trains on the future. - Small validation sets. With a few hundred rows, the validation score is noisy and small differences between settings mean little. The next chapter on cross-validation addresses this.
Exercise
You tune five settings on the validation set. Setting C scores highest, so you evaluate it on the test set and get a lower score than on validation. You then try setting B on the test set and it scores higher, so you report B. What went wrong?
Show answer
You used the test set to choose between settings, so it acted as a second validation set. The reported test score for B is optimistically biased. Choose the setting using validation data only, then score the test set once. If the test set was already used for selection, collect new data or hold out a fresh test set.