Sub topic 6
Data leakage: how results get inflated
This chapter assumes you can split data with scikit-learn, know what a scaler does, and have seen a train/test split. Data leakage happens when information from outside the training data influences the model. Your test score then looks better than the model will perform on new data.
What leakage looks like
A model is only useful if it works on rows it has never seen. A held-out test set simulates those rows. If any step used the test rows to make a decision, the simulation is broken. The model is not wrong in an obvious way. The score is simply too high, and you find out after deployment.
There are two common sources:
- Preprocessing leakage. You fit a scaler, imputer, or encoder on the full dataset before splitting. The mean and standard deviation then include test rows.
- Target leakage. A feature contains information that would not exist at prediction time. An example is a "refund issued" column when predicting whether an order will be returned.
Other sources include duplicate rows that land in both train and test, and tuning choices made by repeatedly checking the test score.
Fitting on the wrong data
The code below shows the leaky order next to the correct one. It also fits a baseline that always predicts the most frequent class.
from sklearn.datasets import load_breast_cancer
from sklearn.dummy import DummyClassifier
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
# Leaky: the scaler sees the test rows before the split.
X_scaled_all = StandardScaler().fit_transform(X)
X_tr_bad, X_te_bad, y_tr, y_te = train_test_split(
X_scaled_all, y, test_size=0.2, stratify=y, random_state=0
)
# Correct: fit the scaler on training rows only, then reuse it.
X_tr, X_te, y_tr, y_te = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
scaler = StandardScaler().fit(X_tr)
clf = LogisticRegression(max_iter=1000).fit(scaler.transform(X_tr), y_tr)
print("test accuracy:", clf.score(scaler.transform(X_te), y_te))
# Baseline: always predict the most frequent class.
baseline = DummyClassifier(strategy="most_frequent").fit(X_tr, y_tr)
print("baseline accuracy:", baseline.score(X_te, y_te))In the correct version, fit is called only on X_tr. The test rows pass through transform with statistics learned from training data. On this dataset the leaky score differs only slightly, because scaling is a mild leak. With imputation based on the target, feature selection, or target encoding, the gap can be large.
Habits that prevent leakage
- Split first. Do this before any step that learns from the data.
- Put every learned step inside a
Pipeline. Cross-validation then refits each step on each training fold. - Ask of every feature: "Will I know this value at prediction time?"
- For time-ordered data, split by time. A random split lets the model train on the future.
- Check for duplicates across the splits.
- Touch the test set once, at the end.
Exercise
A teammate imputes missing values with the column median computed on the whole dataset, then calls traintestsplit. What is wrong, and how do you fix it?
Show answer
The medians include test rows, so information from the test set reaches the training data. Split first, fit the imputer on the training rows only, and apply it to the test rows. Better, put the imputer in a Pipeline so it is refit on each training fold automatically.
Exercise
You predict customer churn and one feature is "account closed date". Why is this target leakage?
Show answer
The date exists only after the customer has churned, so it would not be available when you make a real prediction. The model would learn to read the answer from the feature and fail on live data.