Sub topic 11
Detecting leakage in an existing project
This chapter assumes you can train scikit-learn models, read cross-validation scores, and use pandas. Earlier chapters covered how leakage gets in. Here you inherit a project and have to find out whether its scores can be trusted.
Leakage rarely raises an error. It shows up as indirect evidence, so detection is a set of checks that each look for one kind of evidence.
Start with the score
A score that is too good is the cheapest warning sign. Compare it with three reference points:
- A trivial baseline. Use
DummyClassifieror a one-feature model. If your model barely beats it, there is little to leak into. If it beats it by a huge margin on a hard problem, look closer. - Published or historical results. If the best known model on similar data gets 0.78 AUC and yours gets 0.99, assume leakage until shown otherwise.
- The gap between validation and production. A model that scores 0.95 offline and 0.65 after deployment is the classic symptom.
A high score does not prove leakage, because some problems are easy. It tells you where to look first.
Inspect feature importances
Target leakage usually hides in one or two features that were recorded after the outcome. Those features dominate the importances. The example below plants such a feature.
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 1000
df = pd.DataFrame({
"age": rng.integers(20, 70, n),
"balance": rng.normal(1000, 300, n),
})
df["churned"] = (rng.random(n) < 0.3).astype(int)
# Leaky: only filled in after a customer has already churned
df["cancellation_calls"] = df["churned"] * rng.integers(1, 4, n)
X = df.drop(columns="churned")
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
model = RandomForestClassifier(random_state=0).fit(X_train, y_train)
print("test accuracy:", model.score(X_test, y_test))
print(pd.Series(model.feature_importances_, index=X.columns).sort_values())cancellation_calls takes almost all of the importance, and accuracy is close to 1.0. For each dominant feature, ask the question from the target leakage chapter: would this value exist at the moment of prediction? If the honest answer is "only after the outcome," drop it.
Check for duplicates across the split
Duplicate rows on both sides of a split let the model memorize test answers. Hash each row and look for overlap.
import pandas as pd
from sklearn.model_selection import train_test_split
base = pd.DataFrame({"a": range(100), "b": range(100, 200)})
data = pd.concat([base, base.sample(20, random_state=0)], ignore_index=True) # 20 duplicates
train, test = train_test_split(data, random_state=0)
train_hashes = set(pd.util.hash_pandas_object(train, index=False))
test_hashes = pd.util.hash_pandas_object(test, index=False)
print("test rows also in train:", test_hashes.isin(train_hashes).sum())A nonzero count means exact duplicates cross the split. Near-duplicates, such as the same customer with a slightly different timestamp, need a group key instead. Check whether an ID column, such as patient or user, appears in both train and test.
Run a perturbation test
Retrain the same pipeline with the labels shuffled. A leak-free pipeline should fall to chance, about 0.5 for balanced binary classification. If the score stays high, information is reaching the model some way other than the labels. This is the same idea as the random-label experiment in the cross-validation chapter, applied to your real pipeline.
Two related checks:
- Remove the top suspicious feature and see how far the score drops. A fall from 0.98 to 0.70 points to leakage in that feature.
- Replace your random split with a time-based or group-based split. A large drop means the random split was leaking.
A triage order
Read the code, not only the results
Some leaks are visible only in the source. Search the project for these patterns:
fitorfit_transformcalled on the full dataset beforetrain_test_splitorcross_val_score.- Feature selection, imputation, or target encoding computed outside a
Pipeline. - Aggregates such as per-customer means built from the whole table.
- A test set used to pick thresholds, features, or hyperparameters.
Exercise
A fraud model scores 0.99 AUC. Feature importances show that chargeback_filed carries most of the signal. What is the likely problem, and what should you do?
Show answer
chargeback_filed is almost certainly recorded after fraud is discovered, so it would not exist at prediction time. This is target leakage. Remove the feature, retrain, and re-evaluate. Expect a lower and more realistic score.
Exercise
You shuffle the labels and retrain your full pipeline. The cross-validated accuracy is 0.80 on a balanced binary problem. What does that tell you?
Show answer
A pipeline with no leakage should score near 0.5 on shuffled labels. A score of 0.80 means information reaches the model by some route other than the real labels. Likely causes are preprocessing or feature selection fit on all the data, or duplicates across folds. Audit where each transform is fit.