Sub topic 4
Validation, cross-validation, and avoiding leakage
This chapter assumes you can fit scikit-learn estimators and use pandas. It also assumes you know what a training set and a test set are. The earlier chapters framed the problem and chose a metric. Here you decide how to measure that metric so the number can be trusted.
Why training scores mislead
A model fitted on a dataset has seen those rows. Its score on them measures memory as well as skill. Flexible models such as deep trees and boosted ensembles can score close to perfect on their own training data and still do poorly on new rows.
Validation fixes this by scoring the model on rows it did not use for fitting. The score estimates how the model will behave on future data. That estimate is only valid if the held-out rows really are unseen in every sense, including how the preprocessing was fitted.
Train, validation, and test sets
Most projects use three roles for data:
- Training data is used to fit model parameters.
- Validation data is used to compare models and settings. You look at these scores many times.
- Test data is used once at the end, to report the final estimate.
Every time you pick a model because of its validation score, a little information about the validation data leaks into your choices. After many comparisons the validation score is optimistic. The test set stays clean only if you do not use it to make decisions.
A single validation split is noisy, especially with a few hundred rows. A different random split can change the ranking of two close models. Cross-validation reduces that noise.
K-fold cross-validation
In k-fold cross-validation you split the data into k folds. For each fold, you fit on the other k-1 folds and score on the held-out fold. You then report the mean and the standard deviation of the k scores.
The standard deviation matters as much as the mean. If two models differ by less than the spread across folds, you have no evidence that one is better. Chapter 13 returns to this.
Typical choices are k = 5 or k = 10. Larger k gives each model more training data per fold but costs more fits.
Pick a splitter that matches the data
The default splitter is only right when rows are independent and identically distributed. Pick the splitter that mirrors how the model will be used.
| Splitter | Use when | Watch for |
|---|---|---|
| `KFold` | Regression with independent rows | Set `shuffle=True` if the file is sorted |
| `StratifiedKFold` | Classification, especially imbalanced | Keeps the class ratio in every fold |
| `GroupKFold` | Several rows per customer, patient, or device | Needs a `groups` array; keeps each group in one fold |
| `TimeSeriesSplit` | Data ordered in time, predicting the future | Training always precedes validation |
cross_val_score uses stratified folds automatically for classifiers when you pass an integer cv. It does not shuffle, though. Pass an explicit splitter so the choice is visible and reproducible.
What data leakage is
Data leakage is any path by which information from the validation or test rows, or from the future, influences the fitted model. Leakage makes scores look better than real-world performance. It rarely raises an error. You usually find it when production results disagree with validation.
Preprocessing leakage
Fitting an imputer, scaler, encoder, or feature selector on the whole dataset before splitting lets the statistics of the held-out rows shape the transformation. The effect is small for a scaler. It can be severe for supervised steps such as feature selection, because those steps use the labels.
The next example uses pure noise. No model can predict y, so an honest score 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)
# Wrong: the selector sees every label before the folds are made.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=cv)
# Right: the selector is refitted on the training folds only.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=cv)
print("leaky ", leaky.mean().round(3))
print("honest", honest.mean().round(3))The leaky score is typically far above 0.5 on random noise. The pipeline score stays near 0.5, which is the truth. The fix is the pattern from the preprocessing chapter: put every fitted step inside a Pipeline and pass the pipeline to the cross-validation function. Scikit-learn then refits each step on the training folds only.
Target leakage
Target leakage happens when a feature contains information that would not be available at prediction time. Examples are a refund_issued column when predicting whether an order will be returned, or days_overdue when predicting default. These features score very well and fail in production.
Check each column with one question: at the moment of prediction, would I know this value? Be suspicious of any single feature that is almost as predictive as the label.
Group and duplicate leakage
If the same customer appears in several rows, a random split puts some of their rows in training and others in validation. The model can recognize the customer instead of learning a general pattern. Exact duplicates cause the same problem. Use GroupKFold and drop or group duplicates before splitting.
import numpy as np
from sklearn.model_selection import GroupKFold, TimeSeriesSplit
X = np.arange(100).reshape(-1, 1)
groups = np.repeat(np.arange(20), 5) # 20 customers, 5 rows each
for train_idx, test_idx in GroupKFold(n_splits=4).split(X, groups=groups):
assert set(groups[train_idx]).isdisjoint(groups[test_idx])
print("no customer appears on both sides of any split")
for train_idx, test_idx in TimeSeriesSplit(n_splits=4).split(X):
print("train up to row", train_idx.max(), "-> validate rows", test_idx.min(), "to", test_idx.max())Temporal leakage
With time-ordered data, a shuffled split lets the model train on the future and predict the past. A time-based split trains on earlier rows and validates on later ones. Features built from aggregates, such as a customer's average spend, must be computed using only data before each row's timestamp.
A leakage checklist
- Is every fitted transformation inside a pipeline passed to the cross-validation function?
- Does any feature depend on the label, or on information from after the prediction time?
- Can one entity appear in both training and validation rows? If so, use groups.
- Is the data time-ordered, and does the split respect that order?
- Was the test set touched only once?
Common errors
- Reporting only the mean. Report the standard deviation too. A mean of 0.84 with a deviation of 0.05 is weak evidence about a model that scores 0.85.
- Unshuffled folds on sorted data. If the file is sorted by class or date, plain
KFoldwithout shuffling produces folds with very different distributions. - Changing folds between models. Compare models on identical splits. Use one
cvobject for all candidates. - Using the validation score as the final report. After repeated model selection, it is biased upward. Report the test score.
- Refitting preprocessing on the test set. Fit on training data, then call
transformonly on test data. A pipeline does this for you. - Accepting a surprisingly high score. Scores far above what the problem plausibly allows are a sign of leakage. Investigate before celebrating.
Exercise
You are predicting monthly churn. The table has several rows per customer, one per month, and a column called cancellation_reason that is filled in only after a customer churns. A colleague runs shuffled StratifiedKFold and gets an AUC of 0.99. Name two separate leakage problems and the fix for each.
Show answer
First, cancellation_reason is target leakage. It is only known after the outcome, so it must be dropped. Second, the same customer appears in several rows, so a shuffled split puts that customer on both sides and the model can memorize customers. Use GroupKFold with customer ID as the groups. If the monthly rows are time-ordered and the goal is to predict future months, a time-based split is also appropriate.
Exercise
Why does cross_val_score(LogisticRegression(), StandardScaler().fit_transform(X), y) leak information, and how do you write it without leakage?
Show answer
The scaler computes its mean and standard deviation from all rows, including the rows later used for validation, so each validation fold influenced the transformation. The leak is usually mild for scaling. The correct form is cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()), X, y, cv=cv), which refits the scaler on the training folds in each split.