Sub topic 4
Validation, cross-validation, and avoiding leakage
This chapter assumes you know how to split data into training and test sets, and that you can use scikit-learn's fit, predict, and Pipeline. The goal is an evaluation you can trust, because every model comparison later in this tutorial depends on it.
Why a single training score is not enough
A model scored on the rows it learned from looks better than it will on new data. Validation fixes this by scoring on rows the model never saw. The score is an estimate of future performance, so it must be computed without any information from the held-out rows.
Hold-out and cross-validation
A hold-out split keeps one slice, for example 20%, for scoring. It is fast, but the score depends on which rows landed in that slice. With a few hundred rows, that noise can be larger than the gap between two models.
K-fold cross-validation splits the data into k folds. Each fold is the validation set once, while the other k-1 folds train the model. You get k scores, and their mean and standard deviation show both the level and the noise.
Choose the splitter to match the data:
| Situation | Splitter |
|---|---|
| Classification, imbalanced classes | `StratifiedKFold` |
| Rows grouped by customer, patient, or device | `GroupKFold` |
| Rows ordered in time | `TimeSeriesSplit` |
| Regression with independent rows | `KFold` with `shuffle=True` |
What leakage is
Leakage means information from outside the training fold influenced the model. The validation score then looks better than real performance. The common sources are:
- Fitting a scaler, imputer, encoder, or feature selector on the full dataset before splitting.
- Duplicate or near-duplicate rows on both sides of a split.
- Several rows from the same group (one customer) in both training and validation.
- A feature that is only known after the outcome, such as "refund issued" when predicting churn.
- Random splits on time-ordered data, which let the model train on the future.
Leakage in code
Feature selection is a strong example. The data below is pure noise, so honest accuracy should be near 0.5.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2000))
y = rng.integers(0, 2, 100)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
# Leaky: the selector sees every label before cross-validation starts.
X_leaky = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_leaky, y, cv=cv)
# Safe: the selector is refitted on the training folds of each round.
safe_model = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
safe = cross_val_score(safe_model, X, y, cv=cv)
print("leaky:", leaky.mean().round(3))
print("safe: ", safe.mean().round(3))The leaky score comes out well above 0.5 on data with no signal. The pipeline score stays near 0.5, which is correct.
Keep a final test set
Cross-validation scores guide your choices, so each choice leaks a little information about those folds. Set aside a test set at the start. Use it once, after you have chosen a model, to report the final estimate. If you tune on it, it stops being a test set.
Common errors
- Reporting only the mean and ignoring the standard deviation. A 0.01 gap with a 0.02 spread is not a difference.
- Using different folds for different models. Share one
cvobject, as the later comparison chapters do. - Shuffling time series, or splitting grouped data by row.
Exercise
You standardize all columns with StandardScaler().fit_transform(X), then run 5-fold cross-validation on the scaled data. Which fold's information leaked, and how do you fix it?
Show answer
The scaler's mean and standard deviation were computed using the validation rows of every fold, so each validation fold influenced the training transformation. Wrap the scaler and the model in one pipeline with make_pipeline(StandardScaler(), model) and pass that pipeline to cross_val_score, so the scaler is fitted on the training folds only.