Sub topic 12
A leakage prevention checklist
This chapter turns the earlier chapters into a review you can run on any modeling project. It assumes you can read scikit-learn code (fit, transform, predict, Pipeline, cross_val_score). It also assumes you know why a held-out score estimates performance on new data. The chapter does not re-teach each kind of leakage. It tells you where to look, what to ask, and what evidence to collect.
How to use the checklist
Leakage is easiest to stop at the point where data first enters the workflow. Fixing it after you have a good score is harder, because a good score makes you want to believe the result. Run the checklist at three moments:
- Before you write any modeling code, when you define the prediction task and the split.
- Before you trust any score, when you review preprocessing, features, and tuning.
- Before you ship, when you check the result against what the model will face in production.
Each item below is a yes/no question. A "no" or "I don't know" is a finding to resolve. It is not a note to revisit later.
Stage 1: Define the task and the prediction moment
Most target leakage is a failure of definition. Write down one sentence: "At the moment the model makes a prediction, we know X, and we want to predict Y." Every later check refers back to it.
- Is the prediction time explicit? For a churn model, is it the first day of the month, or the day a customer calls support? Features are only valid if they exist at that moment.
- Is each feature available at prediction time? Go through the columns one at a time. Ask when each value is written, by which system, and whether it is ever updated afterward. A column such as
refund_issuedordays_in_hospitalis usually filled in after the outcome. - Is any feature derived from the label? Look for status codes, flags, and aggregates that are produced by the process you are trying to predict.
- Does the training data match the production population? If production will score new customers but the training data includes years of history for the same customers, the setup is not what it looks like.
If a column fails these checks, drop it or rebuild it as a value "as of" the prediction time. Do not keep it because it improves the score.
Stage 2: Split the data correctly
The split decides what "unseen" means. Choose it from how the data was generated and how the model will be used, not from convenience.
- Are rows independent? If one patient, user, device, or document produces several rows, use a group-aware split such as
GroupKFoldorGroupShuffleSplit. - Does time matter? If the model predicts the future, split by time, with test rows after training rows.
TimeSeriesSplitdoes this for cross-validation. Shuffled splits on time-ordered data let the model train on the future. - Are there duplicates or near-duplicates? Exact duplicates are easy to count. Near-duplicates (the same image resized, the same text with a typo fixed, the same customer under two IDs) need a similarity check or a grouping key.
- Is the split done before anything is fit? Scaling, imputing, encoding, resampling, and feature selection all come after the split. This includes oversampling: if you duplicate minority rows before splitting, copies land on both sides.
- Is the final test set set aside and recorded? Fix the split with a seed or saved indices so it cannot drift between runs.
| Data property | Split to use | Common leak if ignored |
|---|---|---|
| Independent rows | `KFold`, `StratifiedKFold` | Little, if preprocessing is fitted correctly |
| Repeated entities | `GroupKFold` | Same entity on both sides |
| Time-ordered rows | `TimeSeriesSplit` or a cutoff date | Training on the future |
| Duplicated records | Deduplicate, or group by a key | Memorized rows scored as "generalization" |
Stage 3: Build features and the pipeline
After the split, every operation that learns something from data must learn it from training rows only.
- Is every learned step inside a
Pipeline? Scalers, imputers, encoders, PCA,SelectKBest, and resamplers all learn from data. Put them in aPipelineorColumnTransformerwith the model. Thenfitand cross-validation refit them on the training portion each time. - Are statistics computed after the split? Watch for
df.fillna(df.mean()),df["x"] / df["x"].max(), andpd.get_dummies(df)run on the whole frame before splitting. Each one uses test rows. - Are target-based encodings fitted out of fold? Target encoding and mean encoding use the label. Compute them inside each training fold, or use a cross-fitted encoder. Otherwise a row's own label is part of its own feature.
- Do aggregate features respect time and group boundaries? A "customer's average spend" computed over all history includes spending after the prediction date. Compute rolling or expanding aggregates that only look backward.
- Is the same code used in training and production? Keep one fitted pipeline object and persist it. Re-implementing the transforms for serving is a common source of mismatch.
Stage 4: Tune and evaluate
Tuning reuses the data you score on. Every time you look at a score and change something, information moves from that data into your choices.
- Is the test set used once? Use it for a single final estimate. If you looked at it, tried another model, and looked again, it has become a validation set.
- Is tuning inside the training data? Use
GridSearchCVorRandomizedSearchCVon the training split, with the pipeline as the estimator. - Do you need nested cross-validation? When data is small and you report the cross-validation score as the final estimate, the score of the best configuration is optimistically biased. Wrap the search in an outer
cross_val_score. - Are model choices counted? Comparing thirty models and reporting the best one is also tuning. Count the number of things you tried.
- Do inner and outer splits use the same rules? If the outer split is grouped or temporal, the inner split must be too. A shuffled inner split inside a temporal outer split leaks within each outer fold.
A reference implementation
The following code puts several checklist items together. It makes a grouped holdout split, builds a pipeline with a ColumnTransformer, tunes with grouped cross-validation on the training portion only, and scores the test set once. It also runs a shuffled-label control: if the pipeline scores well above chance on random labels, something is leaking.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import (
GridSearchCV,
GroupKFold,
GroupShuffleSplit,
cross_val_score,
)
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n_patients, rows_each = 100, 6
n = n_patients * rows_each
groups = np.repeat(np.arange(n_patients), rows_each)
patient_effect = rng.normal(size=n_patients)[groups]
X = pd.DataFrame(
{
"age": rng.normal(50, 10, size=n),
"lab": patient_effect + rng.normal(size=n),
"clinic": rng.choice(["a", "b", "c"], size=n),
}
)
y = (patient_effect + rng.normal(size=n) > 0).astype(int)
# 1. Hold out whole patients for the final test.
splitter = GroupShuffleSplit(n_splits=1, test_size=0.2, random_state=0)
train_idx, test_idx = next(splitter.split(X, y, groups))
X_train, X_test = X.iloc[train_idx], X.iloc[test_idx]
y_train, y_test = y[train_idx], y[test_idx]
g_train = groups[train_idx]
# 2. Every learned step lives in the pipeline.
prep = ColumnTransformer(
[
(
"num",
Pipeline(
[
("impute", SimpleImputer()),
("scale", StandardScaler()),
]
),
["age", "lab"],
),
("cat", OneHotEncoder(handle_unknown="ignore"), ["clinic"]),
]
)
pipe = Pipeline([("prep", prep), ("model", LogisticRegression(max_iter=1000))])
# 3. Tune with grouped CV on the training portion only.
search = GridSearchCV(
pipe,
{"model__C": [0.01, 0.1, 1, 10]},
cv=GroupKFold(n_splits=5),
)
search.fit(X_train, y_train, groups=g_train)
print("best C:", search.best_params_["model__C"])
print("CV score:", round(search.best_score_, 3))
# 4. Score the untouched test set once.
print("test score:", round(search.score(X_test, y_test), 3))
# 5. Control: shuffled labels should score near chance.
y_shuffled = rng.permutation(y_train)
control = cross_val_score(
pipe, X_train, y_shuffled, groups=g_train, cv=GroupKFold(n_splits=5)
)
print("shuffled-label score:", round(control.mean(), 3))The CV score and test score should be close to each other. The shuffled-label score should be near 0.5. A gap in either direction is worth investigating before you read anything into the numbers.
Stage 5: Audit before shipping
Run these checks on a finished model, even when nothing seemed wrong.
- Is the score plausible? Compare it with a trivial baseline (majority class, last value, simple heuristic) and with published or historical results for the task. A score far above what experts achieve usually means a leak, not a breakthrough.
- Do the top features make sense? Look at feature importances or coefficients. If one feature dominates and it is something like an ID, a timestamp, a status field, or a post-outcome measurement, inspect it.
- Does a single-feature model score too well? Fit a model on each feature alone. One feature that nearly solves the task deserves a question about where it came from.
- Does the shuffled-label control give chance? The code above shows the pattern. It catches leaks in the pipeline itself, such as selection outside folds.
- Do train and test overlap? Count shared IDs, hashes of rows, or nearest-neighbor distances between test and training rows.
- Does performance hold on a later time window? If you can, score data collected after the whole project's data cutoff. This is the most realistic check you have.
- Is the CV score close to the test score? A large drop from CV to test often means tuning leakage or a mismatch between the two splits.
What the checklist cannot catch
Some leakage is not visible in your code.
- Upstream data preparation. If the dataset was cleaned, deduplicated, or labeled by someone else, ask how. Labels produced using features from the full dataset are a quiet source of optimism.
- Public benchmarks and pretrained models. A pretrained model may have seen your test data during its own training. Check what its training corpus covered.
- Social leakage through iteration. Even without code errors, repeated rounds of "look at test error, tweak, retry" make the test score less meaningful. Keep a record of how many times it was used.
- Distribution shift. A clean evaluation can still fail in production because the production data differs. That is a different problem from leakage, and the audit stage should surface both.
Common mistakes when applying the checklist
- Treating a clean pipeline as proof that there is no leakage. Pipelines handle learned preprocessing and nothing else.
- Fixing only the step that was caught. If scaling was done before the split, selection and encoding were probably done the same way.
- Using a grouped outer split and a plain inner split.
- Keeping a suspicious feature because the score dropped when it was removed. A drop in score is often what removing a leak looks like.
- Running the checklist once, then adding new features later without running it again.
Exercise
A teammate reports 0.97 AUC on a loan default model. The features include loan_amount, income, credit_score, and collections_calls_last_90d, where the last column counts calls made after the loan was issued. The data is split with a shuffled train_test_split, and a StandardScaler is fitted on all rows. List the checklist items this setup fails and the fix for each.
Show answer
Three problems. (1) Feature availability: collections_calls_last_90d is only known after the loan is issued and is caused by default, so it is target leakage. Drop it or rebuild it as of the application date. (2) Split: loans are time-ordered and a shuffled split trains on later loans to predict earlier ones. Split by issue date, or use TimeSeriesSplit. (3) Preprocessing: the scaler is fitted on all rows, so test statistics enter training. Split first, then fit the scaler on training rows, ideally inside a Pipeline. Also run the shuffled-label control and a single-feature check, which would flag the collections column.
Exercise
In the reference implementation, why is groups=g_train passed to search.fit and to cross_val_score, and what would go wrong if GroupKFold were replaced by KFold(shuffle=True)?
Show answer
GroupKFold needs the group labels to keep all rows from one patient in the same fold. Without grouping, rows from the same patient appear in both the training and validation folds. The model can then use patient-specific signal (here, the shared patient effect in lab) to score well on validation rows, so the CV score is inflated and the chosen C favors weaker regularization than is justified. The shuffled-label control would also drift above 0.5 for the same reason.