Sub topic 3
Data leakage: the rule that shapes everything else
This chapter assumes you know the scikit-learn fit and transform workflow, train and test splits, and basic statistics such as mean and variance. Every later chapter on imputing, scaling, encoding and selecting features depends on the rule given here.
What leakage is
Data leakage means the model sees information during training that it would not have when making real predictions. The validation score then looks better than the model's true performance. The model seems to work, but it fails once it is deployed.
There are two common sources:
- Target leakage: a feature contains information about the label that is only known after the outcome. An example is a
refund_issuedcolumn used to predict whether an order is fraudulent. - Train-test contamination: information from the validation or test rows influences how training is done. This usually happens in preprocessing.
The rule
Every step that learns something from data must learn it from the training data only. This includes imputers, scalers, encoders and feature selectors. Learn the values with fit on training rows, then apply them to other rows with transform.
import numpy as np
from sklearn.preprocessing import StandardScaler
X = np.array([[1.0], [2.0], [3.0], [100.0]])
X_train, X_test = X[:3], X[3:]
scaler = StandardScaler().fit(X_train) # mean and std from training rows only
print(scaler.transform(X_test))The scaler never sees the value 100 while fitting. If you called fit_transform on all four rows before splitting, the test row would change the mean and standard deviation that the training rows are scaled with.
Leaky and safe versions
The leaky version preprocesses everything first.
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# Leaky: statistics include the future test rows
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, y, random_state=0)The safe version splits first and fits only on the training portion.
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler().fit(X_train)
X_train_s = scaler.transform(X_train)
X_test_s = scaler.transform(X_test)Leakage inside cross-validation
Cross-validation repeats the train and validation split several times. If you scale the whole dataset first, every validation fold has already influenced the scaler. The fix is to place all learned steps inside a Pipeline, so each fold refits them on its own training rows. The later chapter on pipelines shows this in full.
Other places leakage hides
| Source | Example | Prevention |
|---|---|---|
| Imputation | Filling gaps with the median of the full dataset | Fit the imputer on training rows |
| Feature selection | Choosing the top features using all labels, then cross-validating | Put the selector inside the pipeline |
| Target encoding | Encoding a category with its mean label on the same rows | Compute inside folds |
| Time series | Random split of data ordered in time | Split by time so training precedes validation |
| Duplicates | Same record in train and test | Deduplicate before splitting |
| Post-outcome columns | A field recorded after the event | Ask when each column becomes known |
A checklist
- For every column, ask: would I know this value at prediction time?
- Split the data before any fitting step.
- Keep every learned transformation inside a pipeline.
- For time-ordered data, validate on later periods than you train on.
- Be suspicious of one feature that dominates importance or of near-perfect scores.
Exercise
A colleague standardizes the full dataset with StandardScaler().fit_transform(X), then runs cross_val_score on a logistic regression. Why is the score unreliable, and how do you fix it?
Show answer
The scaler's mean and standard deviation were computed using rows that later act as validation rows, so each validation fold leaks into preprocessing. Wrap the scaler and model in a Pipeline and pass the pipeline to cross_val_score. The scaler is then refit on the training rows of each fold.
Exercise
A model predicting customer churn includes a column cancellation_reason, filled in only when a customer leaves. What kind of leakage is this, and what should you do?
Show answer
It is target leakage, because the value exists only after the outcome is known. Remove the column from the features, since it would not be available when predicting for active customers.