Lab: Hunt the Leak
Take a late-payment model that scores 0.99 ROC-AUC, find its four planted leaks (a field written after the outcome, a total that includes future bills, the same customers on both sides of the split, and feature selection on every row), fix them one at a time, and confirm the honest score on customers the model has never seen.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Generate the billing data
- Step 2: Reproduce the headline score
- Step 3: Audit single columns and their timelines
- Step 4: Check whether customers appear on both sides
- Step 5: Fix the leaks one at a time
- Step 6: Confirm on customers the model has never seen
- Check your understanding
- Apply it
- Review prompt
Lessons of Model Evaluation & Validation
- Metrics That Match the Decision Concept · 25 min
- Worked Example: Picking a Threshold from Error Costs Worked example · 20 min
- Validation Schemes That Mirror Production Concept · 25 min
- Lab: Hunt the Leak Lab · 30 min
- Lab: Honest Tuning and Slice-Based Error Analysis Lab · 30 min
- Check: Would You Trust This Score? Knowledge check · 8 questions
What you will learn
- Detect and fix data leakage, including preprocessing fit on all rows, target leakage, the same entity in several splits and information from the future.
Prerequisites: Machine Learning Fundamentals
01. Goal and setup
Data leakage means that the model, during training or validation, gets information it will not have when it makes real predictions. The score then measures that extra information, not the model. Leaks are rarely dramatic bugs. They hide in a convenient warehouse column, a default split or a preprocessing step that runs one line too early.
In this lab you inherit a model that predicts whether a customer's next bill will be paid late, so that the collections team can send a friendly reminder before the due date. The notebook reports a ROC-AUC of 0.99. You will reproduce that number, find four leaks, fix them one at a time while watching the score, and check the final estimate on 800 new customers that played no part in any decision.
Production works like this: when a bill is issued, the model scores it, using what is known on that day. The model will mostly score customers who joined after it was trained, so a validation customer must be a new customer.
You need: Python 3.12, scikit-learn 1.9 and pandas 3. The data is generated with fixed seeds, so your numbers should match. The longest script runs in under a minute on a laptop.
leak-lab/
├── make_data.py step 1: writes bills.csv and new_customers.csv
├── notebook.py step 2: the leaky notebook, condensed
├── audit.py step 3: single-column scores and one timeline
├── overlap.py step 4: customers on both sides of a split
├── pipeline.py step 5: features and the leak-free pipeline
├── ladder.py step 5: the score after each fix
└── final.py step 6: the check on new customersmkdir leak-lab && cd leak-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "scikit-learn==1.9.*" "pandas==3.1.*"02. Step 1: Generate the billing data
Each of 800 customers gets six monthly bills. A hidden reliability trait, which the model never sees, makes some people pay late more often; age and income are weakly related to it. The script also adds the columns that the notebook author pulled from the warehouse: a reminder flag, a count of late bills, and 300 answers from a sign-up survey that have nothing to do with payments. Read it as the ground truth: it tells you exactly which columns are leaks, which a real project never does.
"""Writes bills.csv: six monthly bills per customer. Label: this bill is paid late."""
import numpy as np
import pandas as pd
def make(n_customers, seed, first_id=0):
rng = np.random.default_rng(seed)
rows = []
for cid in range(first_id, first_id + n_customers):
reliability = rng.normal() # hidden from the model
age = int(np.clip(rng.normal(40 + 6 * reliability, 12), 18, 85))
income = round(float(rng.lognormal(10.3 + 0.1 * reliability, 0.4)), -2)
autopay = int(rng.random() < 0.4)
plan = rng.choice(["basic", "plus", "family"], p=[0.5, 0.3, 0.2])
for month in range(1, 7):
size = 1.6 if plan == "family" else 1.0
amount = round(float(rng.gamma(4, 12) * size), 2)
logit = -1.4 - 2.2 * reliability + 0.012 * amount - 1.6 * autopay
late = int(rng.random() < 1 / (1 + np.exp(-logit)))
# the reminder letter goes out when a bill becomes overdue
reminder_sent = int(late and rng.random() < 0.92)
rows.append([cid, month, age, income, autopay, plan, amount,
reminder_sent, late])
df = pd.DataFrame(rows, columns=["customer_id", "month", "age", "income", "autopay",
"plan", "amount", "reminder_sent", "late"])
# warehouse field: late bills over the customer's whole history
df["late_count_total"] = df.groupby("customer_id")["late"].transform("sum")
survey = rng.normal(size=(len(df), 300)).round(2) # 300 unrelated survey answers
names = [f"q{i:03d}" for i in range(300)]
return pd.concat([df, pd.DataFrame(survey, columns=names)], axis=1)
if __name__ == "__main__":
df = make(800, seed=0)
df.to_csv("bills.csv", index=False)
make(800, seed=1, first_id=800).to_csv("new_customers.csv", index=False)
print(f"bills.csv: {len(df)} rows, {df.customer_id.nunique()} customers, "
f"{df.shape[1]} columns, late rate {df.late.mean():.3f}")python make_data.pybills.csv: 4800 rows, 800 customers, 310 columns, late rate 0.32003. Step 2: Reproduce the headline score
Start by reproducing the number you were given; if you cannot, the rest of the investigation has no fixed point. The condensed notebook uses every column, keeps the 30 survey questions most related to the label, and runs shuffled 5-fold CV with a gradient-boosted tree model.
"""The notebook as it was handed over, condensed into one script."""
import pandas as pd
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import KFold, cross_val_score
df = pd.read_csv("bills.csv")
y = df["late"]
X = df.drop(columns=["customer_id", "late"])
X["plan"] = X["plan"].map({"basic": 0, "plus": 1, "family": 2})
survey = [c for c in X.columns if c.startswith("q")]
best = SelectKBest(f_classif, k=30).fit(X[survey], y) # chosen using every row
X = X.drop(columns=survey).join(X[best.get_feature_names_out()])
cv = KFold(5, shuffle=True, random_state=0) # rows shuffled
auc = cross_val_score(HistGradientBoostingClassifier(random_state=0), X, y,
cv=cv, scoring="roc_auc")
print(f"notebook ROC-AUC: {auc.mean():.3f} ± {auc.std():.3f}")python notebook.pynotebook ROC-AUC: 0.992 ± 0.002Predicting human payment behaviour from a few account fields with 0.99 ROC-AUC would be remarkable. A score far above what similar problems reach is a classic symptom of leakage, so treat it as a question, not a result.
04. Step 3: Audit single columns and their timelines
A quick first pass: score each column on its own. ROC-AUC works for this even though a column is not a model, because it only asks whether higher values go with late bills. A single column that almost separates the classes deserves a close look. Then print one customer over time and ask, for every suspicious column, when its value is written.
import pandas as pd
from sklearn.metrics import roc_auc_score
df = pd.read_csv("bills.csv")
skip = ("customer_id", "late")
core = [c for c in df.columns if not c.startswith("q") and c not in skip]
print("single-column ROC-AUC (0.5 = no signal):")
for col in core:
values = df[col]
if col == "plan":
values = values.map({"basic": 0, "plus": 1, "family": 2})
auc = roc_auc_score(df["late"], values)
print(f" {col:<17} {max(auc, 1 - auc):.3f}")
print("\none customer over time:")
cols = ["customer_id", "month", "late", "reminder_sent", "late_count_total"]
print(df.loc[df.customer_id == 3, cols].to_string(index=False))python audit.pysingle-column ROC-AUC (0.5 = no signal):
month 0.521
age 0.648
income 0.593
autopay 0.619
plan 0.529
amount 0.554
reminder_sent 0.962
late_count_total 0.922
one customer over time:
customer_id month late reminder_sent late_count_total
3 1 1 1 4
3 2 0 0 4
3 3 0 0 4
3 4 1 1 4
3 5 1 0 4
3 6 1 1 4Two columns stand out. reminder_sent (0.962) is 1 almost only on late bills. Ask the collections team and you learn why: the letter is sent after a bill becomes overdue. On the day a new bill is issued it is always 0, so it is target leakage, information created by the outcome itself. Drop it.
late_count_total (0.922) shows a different pattern in the timeline: customer 3 has the value 4 on every row, including month 1, when no earlier bill existed. The warehouse computed it over the whole history, so each row contains the outcomes of later months, and of the row itself. This is information from the future. The same leak hides in a centred rolling average such as rolling(7, center=True), whose window includes the days after each row. The idea behind it, past behaviour predicts future behaviour, is sound, so the fix is to rebuild it from earlier bills only, which you will do in step 5.
A high single-column score is a reason to investigate, not a proof: a genuinely strong feature can score high too. The timeline question, "is this value known when the prediction is made?", is what decides.
05. Step 4: Check whether customers appear on both sides
Each customer has six rows. Shuffled KFold splits rows, not customers, so most customers end up with some bills in training and others in validation. The model can then learn, from age and income, which person it is looking at and recall how that person behaved, a shortcut that does not exist for a new customer.
import pandas as pd
from sklearn.model_selection import GroupKFold, KFold
df = pd.read_csv("bills.csv")
ids = df["customer_id"].to_numpy()
schemes = [("KFold", KFold(5, shuffle=True, random_state=0)),
("GroupKFold", GroupKFold(5))]
for name, cv in schemes:
train, val = next(cv.split(df, groups=ids if name == "GroupKFold" else None))
shared = len(set(ids[train]) & set(ids[val]))
print(f"{name:<10} fold 1: {len(set(ids[val]))} validation customers, "
f"{shared} of them also in training")python overlap.pyKFold fold 1: 590 validation customers, 590 of them also in training
GroupKFold fold 1: 160 validation customers, 0 of them also in trainingWith row shuffling, every one of the 590 customers in the first validation fold also has bills in training. GroupKFold with the customer ID as the group puts all six bills of a customer in the same fold, so the 160 validation customers are new to the model, as in production. This kind of overlap count belongs in your split manifest: write it down and check it is zero.
06. Step 5: Fix the leaks one at a time
The fourth leak is the survey selection. The notebook picks the 30 survey questions most correlated with the label using every row, then cross-validates. Among 300 random columns, some correlate with the validation labels by chance, and selecting them bakes those labels into the features. The fix is to make the selector part of the model: inside a Pipeline, cross_val_score refits it on each fold's training rows only. A ColumnTransformer applies the selector to the survey columns and passes the others through.
The file pipeline.py holds the honest version, so that step 6 can reuse it. Its late_before feature counts late bills strictly before the current one, which is known when the current bill is issued, assuming each bill is due before the next one goes out. The ladder script applies the fixes cumulatively and prints the score after each one.
"""Shared by ladder.py and final.py: features and the leak-free pipeline."""
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.ensemble import HistGradientBoostingClassifier
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.pipeline import make_pipeline
LEAKS = ["reminder_sent", "late_count_total"]
def prepare(df, drop=LEAKS, past_count=True):
df = df.sort_values(["customer_id", "month"]).copy()
if past_count: # late bills BEFORE this one: known when this bill is issued
df["late_before"] = df.groupby("customer_id")["late"].cumsum() - df["late"]
X = df.drop(columns=["customer_id", "late", *drop])
X["plan"] = X["plan"].map({"basic": 0, "plus": 1, "family": 2})
return X, df["late"], df["customer_id"]
def model(survey_columns):
pick = ColumnTransformer([("survey", SelectKBest(f_classif, k=30), survey_columns)],
remainder="passthrough")
return make_pipeline(pick, HistGradientBoostingClassifier(random_state=0))import pandas as pd
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.model_selection import GroupKFold, KFold, cross_val_score
from pipeline import model, prepare
df = pd.read_csv("bills.csv")
def score(drop, grouped, inside, past_count=False):
X, y, ids = prepare(df, drop=drop, past_count=past_count)
survey = [c for c in X.columns if c.startswith("q")]
if inside:
est = model(survey)
else: # the notebook's way: pick survey columns once, using every row
top = SelectKBest(f_classif, k=30).fit(X[survey], y).get_feature_names_out()
X = X.drop(columns=survey).join(X[top])
est = model([])
cv = GroupKFold(5) if grouped else KFold(5, shuffle=True, random_state=0)
auc = cross_val_score(est, X, y, groups=ids if grouped else None, cv=cv,
scoring="roc_auc")
return f"{auc.mean():.3f} ± {auc.std():.3f}"
L = ["reminder_sent", "late_count_total"]
print("fix applied (cumulative) CV ROC-AUC")
print(f"none (the notebook) {score([], False, False)}")
print(f"1. drop reminder_sent {score(L[:1], False, False)}")
print(f"2. drop late_count_total {score(L, False, False)}")
print(f"3. GroupKFold by customer {score(L, True, False)}")
print(f"4. survey selection inside pipeline {score(L, True, True)}")
print(f"5. add late_before (past bills only) {score(L, True, True, past_count=True)}")python ladder.pyfix applied (cumulative) CV ROC-AUC
none (the notebook) 0.992 ± 0.002
1. drop reminder_sent 0.916 ± 0.007
2. drop late_count_total 0.727 ± 0.023
3. GroupKFold by customer 0.689 ± 0.016
4. survey selection inside pipeline 0.674 ± 0.016
5. add late_before (past bills only) 0.772 ± 0.016Read the ladder from the top. The target leak was worth 0.08 of ROC-AUC and the future total another 0.19. Grouping by customer removes 0.04 more: the model had been recognising people. Moving the selection inside the pipeline costs 0.015 here; with 4,800 rows the chance correlations of 300 noise columns are small, but the same mistake on a few hundred rows can create a strong score from pure noise. Finally, the legitimate version of the late-bill history adds real signal back, to 0.772.
Two cautions. The size of each step depends on the order of the fixes, because leaks overlap; do not read the ladder as a ranking of how bad each leak is. And every number here comes from five folds, so differences of about 0.01 are within the fold spread.
07. Step 6: Confirm on customers the model has never seen
The final check plays the role of an untouched test set: fit the honest pipeline on all 800 development customers and score the 800 new ones generated in step 1. Nothing about them influenced any choice in this lab.
import pandas as pd
from sklearn.metrics import roc_auc_score
from pipeline import model, prepare
X, y, _ = prepare(pd.read_csv("bills.csv"))
X_new, y_new, _ = prepare(pd.read_csv("new_customers.csv"))
fitted = model([c for c in X.columns if c.startswith("q")]).fit(X, y)
auc = roc_auc_score(y_new, fitted.predict_proba(X_new)[:, 1])
print(f"800 new customers, ROC-AUC: {auc:.3f}")python final.py800 new customers, ROC-AUC: 0.781The new customers score 0.781, within one fold standard deviation of the honest CV estimate (0.772 ± 0.016) and far from the notebook's 0.992. That agreement is the real result of the lab: the validation scheme now predicts what production will see.
08. Check your understanding
09. Apply it
The practice project hands you a notebook with planted leaks. Use the same method.
- Reproduce the reported score exactly, then list every column with the moment its value is written. Mark each one as known at prediction time, written after the outcome, or computed over a period that includes the future.
- Count entities shared across your splits, switch to a grouped or time-based scheme that matches production, and put every fitted preprocessing step inside a pipeline.
- Present a ladder like the one in step 5 and confirm the final estimate on a held-out set, with a bootstrap interval.
10. Review prompt
Without looking back, name the four leaks of this lab and say for each one how you detected it and how you fixed it; explain why a high single-column score is a reason to investigate rather than a proof of leakage; and describe the check that showed the final cross-validation estimate could be trusted.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.