Sub topic 11
Detecting leakage in an existing project
This chapter assumes you know the leakage types from earlier chapters: target leakage, preprocessing leakage, temporal leakage, group and duplicate leakage, and tuning leakage. It also assumes you can read scikit-learn pipelines and cross-validation code.
Earlier chapters showed how to avoid leakage when you build a project. Often, though, you inherit a notebook or a trained model and have to decide whether its numbers can be trusted. This chapter gives you an audit routine. Each check is cheap, and each targets a specific kind of leakage.
Start with the symptoms
Leakage rarely raises an error. It shows up as results that look better than the problem allows. These patterns are worth investigating:
| Symptom | Likely cause |
|---|---|
| Near-perfect score on a hard problem | Target leakage, or duplicates across the split |
| One feature dominates importance | A feature derived from or recorded after the label |
| Cross-validation score far above the score on newly collected data | Preprocessing, selection, or tuning done outside the folds |
| Test score higher than training score | Test rows overlap with training rows, or the scores come from different procedures |
| Score drops sharply in production | Temporal or group leakage that the random split hid |
| Score keeps rising as you reuse the same test set | Tuning leakage through repeated evaluation |
A symptom is evidence, not proof. A strong feature can be legitimate. The checks below turn suspicion into something you can test.
Check 1: Compare with a baseline
Run a trivial model first. scikit-learn's DummyClassifier and DummyRegressor predict from the label distribution alone. Then ask what a domain expert would expect from a good model. If the project reports 0.99 AUC on a task where published work reaches 0.75, treat the 0.99 as a bug until you can show otherwise.
A baseline also exposes class imbalance. A model with 95% accuracy on data that is 95% one class has learned nothing. Leakage and weak evaluation often appear together.
Check 2: Screen each feature alone
Target leakage usually comes from one or two columns. To find them, score every feature alone with a small model. Any single column that predicts the label almost perfectly needs an explanation.
import numpy as np
import pandas as pd
from sklearn.model_selection import cross_val_score
from sklearn.tree import DecisionTreeClassifier
rng = np.random.default_rng(0)
n = 1000
y = (rng.random(n) < 0.3).astype(int)
df = pd.DataFrame({
"age": rng.integers(20, 70, n),
"balance": rng.normal(1000, 300, n),
"collections_calls": y * rng.integers(1, 5, n), # logged after the outcome
})
tree = DecisionTreeClassifier(max_depth=3, random_state=0)
for col in df.columns:
auc = cross_val_score(tree, df[[col]], y, cv=5, scoring="roc_auc").mean()
print(f"{col:18s} {auc:.3f}")Here age and balance score near 0.5, which is chance. collections_calls scores 1.0, because a customer only receives collection calls after defaulting. The column is real data, but you would not have it when predicting. The test for each flagged feature is the one from the target leakage chapter: would this value exist at prediction time?
A tree catches non-linear relationships that a correlation table misses. It will not catch leakage that needs several features together, such as a sum of two columns that reconstructs the label. For that case, move on to importances.
Check 3: Read the feature importances
Fit the model and inspect which features it relies on. Tree models expose feature_importances_. For any model, sklearn.inspection.permutation_importance measures how much the score drops when one column is shuffled. Compute it on held-out rows, because importances computed on training rows reward features the model memorized.
Look for these:
- One feature carrying most of the importance.
- Identifier-like columns (row IDs, order numbers, file names) with high importance. They often encode time or label order.
- Columns whose names contain words like
status,outcome,result,flag, orfinal. - Features that are missing in a pattern that matches the label. A missing value can leak, for example a lab value that is only recorded when a disease is suspected.
Ask the data owner when a feature's origin is unclear. A column's name rarely tells you when it was recorded.
Check 4: Look for duplicates across the split
Random splits assume rows are independent. Repeated rows, repeated entities, and near-copies break that assumption and let the model memorize test rows.
Start with exact duplicates. df.duplicated() finds repeats inside one table. To find rows shared between splits, merge test rows onto training rows on all feature columns. Then check entity columns such as customer, patient, device, or session. If an entity appears on both sides of the split, you have group leakage, and GroupKFold (covered earlier) is the fix.
Near-duplicates need a distance check. These include a re-encoded image, a retyped record, or a sensor reading taken a moment later.
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.neighbors import NearestNeighbors
rng = np.random.default_rng(0)
base = rng.normal(size=(300, 4))
# each row appears twice with tiny noise, like repeated captures of one item
X = np.vstack([base, base + rng.normal(scale=0.01, size=base.shape)])
y = np.tile(rng.integers(0, 2, 300), 2)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
nn = NearestNeighbors(n_neighbors=1).fit(X_train)
test_dist = nn.kneighbors(X_test)[0][:, 0]
print("test rows with a near-copy in train:", np.mean(test_dist < 0.05))About three quarters of the test rows have a near-copy in the training set, so the test score would measure memorization. On a clean split, the fraction would be close to zero for data with this spread. Choose the threshold from the scale of your features. Standardize the features first, using statistics from the training rows only, or distances will be dominated by whichever column has the largest units.
For text and images, compare embeddings or hashes instead of raw values.
Check 5: Shuffle the labels
This check detects leakage in the procedure, whatever its source. Take the exact evaluation code and replace the labels with a random permutation. A procedure without leakage must score at chance, because the labels no longer relate to the features. A score above chance means information is reaching the model from somewhere it should not.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(100, 2000))
y = (X[:, 0] + rng.normal(size=100) > 0).astype(int)
def leaky(X, y):
X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
return cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=5).mean()
def honest(X, y):
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
return cross_val_score(pipe, X, y, cv=5).mean()
def shuffled_score(evaluate, X, y, repeats=5, seed=1):
r = np.random.default_rng(seed)
return float(np.mean([evaluate(X, r.permutation(y)) for _ in range(repeats)]))
print("real labels: ", leaky(X, y), honest(X, y))
print("shuffled labels:", shuffled_score(leaky, X, y), shuffled_score(honest, X, y))With real labels, both procedures look decent. With shuffled labels, the leaky version typically stays well above 0.5, because feature selection saw every label before cross-validation split the data. The pipeline version stays near 0.5. The label shuffle works the same way on any evaluation function you can wrap, so you can apply it to a legacy project without understanding all of its code first.
Average over several shuffles. A single permuted run is noisy on small datasets. scikit-learn's permutation_test_score automates this and reports a p-value.
Check 6: Read the code for ordering errors
Some leakage is easier to find by reading than by running. Search the project for these patterns:
fitorfit_transformcalled on a fullXbeforetrain_test_splitor before the cross-validation call. This covers scalers, imputers, encoders, PCA, and feature selectors.- Target encoding, or any aggregate computed with
groupbyon the label, built on the full table. - Random splits (
train_test_split,KFold(shuffle=True)) applied to time-ordered data. - A test set passed to
GridSearchCV, to early stopping, or to any code that picks a threshold, an architecture, or a feature list. - A model compared on the test set many times, with the best one reported.
- Lag, rolling, or expanding features computed across the whole table without respecting the split boundary.
For each match, trace what data reaches the fit call. The rule from earlier chapters is the test: anything that learns from data must learn only from the training rows of the current fold.
Also check the notebook's execution order. A cell that refits a scaler after the test set was loaded, or a variable that is reused between runs, can leak even when the code reads correctly.
Reading the results
Not every failed check means a bug, and not every pass means safety.
- A strong feature can be legitimate. If the screen flags
previous_purchasesfor predicting repeat buyers, confirm when the value is computed. A feature built from history before the prediction date is fine. - Clean checks do not prove absence. Checks 2 to 5 find common leaks. They miss subtle temporal leakage, such as a feature whose definition quietly changed after the label was known.
- Duplicates are sometimes unavoidable. If production data will contain the same customers, a split that allows customer overlap may match deployment. Decide on purpose, and document it.
- Small datasets give noisy audits. With 100 rows, a single-feature AUC of 0.65 can be chance. Use repeated cross-validation or more shuffles before reaching a conclusion.
After you fix a leak, re-run the evaluation and expect the score to fall. A lower, honest number is the correct result of the fix.
What to record
Write down the checks you ran and what they showed. A short audit log helps the next reader decide how far to trust the score. It should include the baseline score, the features removed and why, the duplicate and group overlap found, the label-shuffle result, and the date of the last evaluation on data that was not used for tuning.
Exercise
A teammate reports 0.97 AUC for predicting hospital readmission. The single-feature screen shows discharge_summary_length alone reaches 0.93 AUC. Name the likely problem, and describe two follow-up checks before dropping the feature.
Show answer
The likely problem is target leakage. A discharge summary is written when the patient leaves, and its length may depend on complications that also drive readmission, or on notes added after readmission. First, find out when the column is populated and whether it exists at the moment the prediction would be made. Second, retrain without the feature, or restrict the data to values recorded before the prediction time, and compare the score. If the score falls sharply, the feature was carrying the result. You can also run the label-shuffle test on the full pipeline to check for other leaks.
Exercise
You run the shuffled-label test on an inherited evaluation. Over ten shuffles, accuracy averages 0.62 on a balanced binary problem. What does this tell you, and where do you look first?
Show answer
Chance is about 0.5, so 0.62 averaged over ten shuffles suggests the procedure leaks label information. Look first for any step that sees all labels before the cross-validation split: feature selection, target encoding, imputation based on the label, or hyperparameter tuning on the same data. Check for near-duplicate rows too, since the model can still match a row to a copy it has seen. Then move the suspected step into a pipeline so it is refit inside each fold, and repeat the test. The score should return to about 0.5.