Sub topic 12
A leakage prevention checklist
This chapter assumes you know scikit-learn pipelines, cross-validation, and the leakage types covered earlier: target, preprocessing, temporal, group and duplicate, tuning, and feature engineering. It turns them into a checklist you can run through at the start of a project, before each evaluation, and before shipping.
How to use the checklist
Leakage is easiest to prevent at three points. Each point has its own questions.
Stage 1: Design
Decide these before you write any modeling code.
- Fix the prediction moment. Write down when the model will be called and what data exists at that moment. Every feature must come from before that moment.
- Choose the split rule from the data's structure. Use a random split only if rows are independent. Use a time-ordered split for temporal data, and a group-aware split when several rows share a patient, user, device, or document.
- Set the test set aside. Split off the final test set first. Do not look at it, plot it, or compute statistics on it until the end.
- Check for duplicates. Look for exact and near-duplicate rows before splitting, and assign duplicates to the same side.
Stage 2: Build
- Put every learned step in a pipeline. Scalers, imputers, encoders, feature selectors, and resamplers must all be fitted on training rows only. This includes target encodings and any feature built from group statistics.
- Audit each feature. Ask whether the feature would exist at prediction time. A column recorded after the outcome, such as a cancellation reason in a churn model, is target leakage.
- Tune inside the training data. Run hyperparameter search on the development set only. Use nested cross-validation if you want an unbiased estimate of the whole tuning procedure.
- Score the test set once. If you tune again after seeing the test score, the test set becomes a validation set.
The following code combines these rules. The test set is split off first. The pipeline holds the scaler and feature selector. The grid search runs inside each outer fold, and the test set is scored exactly once.
from sklearn.datasets import make_classification
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import (
GridSearchCV,
StratifiedKFold,
cross_val_score,
train_test_split,
)
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=600, n_features=30, n_informative=5, random_state=0)
# 1. Hold out the final test set before anything else
X_dev, X_test, y_dev, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
# 2. Every learned step lives in the pipeline
pipe = make_pipeline(
StandardScaler(),
SelectKBest(f_classif),
LogisticRegression(max_iter=1000),
)
grid = {"selectkbest__k": [5, 10, 20], "logisticregression__C": [0.1, 1, 10]}
# 3. Tuning happens inside each outer fold
inner = StratifiedKFold(n_splits=3, shuffle=True, random_state=1)
outer = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(pipe, grid, cv=inner)
nested = cross_val_score(search, X_dev, y_dev, cv=outer)
print("nested CV accuracy:", nested.mean())
# 4. Refit on all development data and score the test set once
search.fit(X_dev, y_dev)
print("test accuracy:", search.score(X_test, y_test))The nested score and the test score should be close. A large gap in either direction means the procedure needs another look.
Stage 3: Evaluate
- Be suspicious of high scores. A score far above a simple baseline or published results usually points to leakage before it points to a good model.
- Inspect feature importances. If one feature dominates, check how it is produced and when it becomes available.
- Run a shuffled-label check. Fit the full procedure on randomly permuted labels. Scores well above chance mean information is leaking through the procedure.
- Compare splits. If a random split scores much higher than a time-based or group-based split on the same data, rows are not independent.
- Search for overlap. Count the groups, IDs, and duplicate rows that appear on both sides of any split.
Stage 4: Ship
- Build features for live data with the same code path used in training. Separate implementations drift apart.
- Compare live performance with the test estimate. A persistent drop is a sign of leakage that earlier checks missed. It can also come from distribution shift, so check both.
- Record the split rule, the tuning procedure, and the feature availability notes with the model, so a reviewer can repeat the audit.
Quick reference
| Leakage type | Main guard |
|---|---|
| Target | Feature availability audit at prediction time |
| Preprocessing | Fit transforms on training rows only, inside a pipeline |
| Cross-validation | Pipeline passed to the cross-validation function |
| Temporal | Time-ordered splits such as TimeSeriesSplit |
| Group and duplicate | Group-aware splits and duplicate removal |
| Tuning | Nested cross-validation and a single test evaluation |
Exercise
A teammate reports 97% accuracy. Their code imputes missing values with the column mean on the full dataset, then runs 5-fold cross-validation on a tuned model, and the same folds were also used to pick the hyperparameters. Name two checklist items they violated and how you would fix each.
Show answer
First, the imputer was fitted on all rows, so held-out folds influenced the training features. Fix it by placing the imputer in a pipeline that cross-validation refits on each training fold. Second, the same folds were used to tune and to report the score, so the estimate is optimistic. Fix it with nested cross-validation, or tune on a development set and score a separate untouched test set once.