Sub topic 10
Avoiding data leakage
Data leakage happens when information from outside the training data influences the model during training. The model then looks better in evaluation than it will be on new data. This chapter assumes you know train_test_split, the fit and transform methods of a transformer, and the basic shape of X and y.
What leakage is
A model is only useful if it works on data it has never seen. The test set stands in for that future data. If anything computed from the test set reaches the training process, the test score no longer measures what you think it measures.
Leakage rarely raises an error. The code runs and the score looks good. You usually find the problem only when the model fails in production.
There are two common forms:
- Preprocessing leakage. A transformer learns statistics (a mean, a vocabulary, category lists) from data that includes the test rows.
- Target leakage. A feature contains information that would not be available at prediction time, such as a column derived from the label.
This chapter focuses on preprocessing leakage, because the estimator API is designed to prevent it. Target leakage is described briefly at the end.
Why fitted transformers can leak
A transformer such as StandardScaler learns values in fit. For the scaler, these are mean_ and scale_. If you call fit on all of the data before splitting, those values include the test rows. The test data has shaped the transformation applied to the training data.
The effect is often small for a scaler. It can be large for steps that learn more from the data, such as feature selection, target encoding, or imputation based on many columns.
The leaking version looks like this:
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
# Wrong: the scaler sees every row, including 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 order of operations is the bug. The scaler was fitted before the split.
The correct order
Split first. Fit the transformer on the training portion only. Then apply the already-fitted transformer to the test portion.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
print(scaler.mean_)fit_transform runs on the training data and stores mean_ and scale_ from those rows alone. transform on the test data reuses the stored values without learning anything new. The test features are scaled with the training mean, which is exactly what will happen to new data in production.
The following diagram shows which data each call may touch.
Common mistakes
The most common errors are easy to make and hard to see.
- Calling
fit_transformon the test set. This refits the scaler on test rows. The test data is then scaled with its own mean, which hides any distribution shift. Usetransformon test data. - Fitting on the full dataset before the split. This is the example shown earlier.
- Fitting a selector on all rows. Feature selection that uses
y, such asSelectKBest, can pick features that happen to correlate with the test labels. This inflates scores more than scaling does. - Imputing or encoding before the split. Filling missing values with a column mean or building a category list from all rows leaks in the same way as scaling.
- Duplicated rows across the split. If the same record appears in both sets, the model has effectively seen the test row. Deduplicate before splitting when duplicates are possible.
Leakage inside cross-validation
Cross-validation repeats the train and validation split several times. Preprocessing must be refitted inside each repetition. If you scale the whole dataset once and then cross-validate only the model, every validation fold has influenced the scaler.
The fix is to put the preprocessing inside a Pipeline and pass the pipeline to the evaluation function.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
scores = cross_val_score(pipe, X, y, cv=5)
print(scores.mean())For each fold, cross_val_score clones the pipeline and fits it on the training part only. It then scores it on the validation part. The scaler is refitted five times, each time on different rows. No validation data reaches fit.
Comparing the leaking and safe approaches
| Approach | Where the scaler is fitted | Leaks? |
|---|---|---|
| Scale all data, then split | Full dataset | Yes |
| Split, then `fit_transform` on train and `transform` on test | Training rows only | No |
| `fit_transform` on both splits separately | Each split on its own | No leak, but wrong: the test data is scaled differently from the training data |
| Pipeline passed to `cross_val_score` | Training part of each fold | No |
The third row shows a related error. It does not leak information into training, but it breaks the model. The model learned on data scaled one way, and the test features are scaled another way, so predictions are unreliable.
Why the estimator API helps
The scikit-learn conventions make the safe path the natural one:
fitis the only method that learns.transformandpredictonly apply whatfitlearned.- Learned values are stored in attributes ending with an underscore, such as
mean_. You can check these attributes to see what the transformer learned and from which rows. - A
Pipelinecallsfitandtransformon each step in the right order, andcross_val_scoreclones it for each fold.
If you stay inside this interface, leakage requires an explicit mistake. Most leaks come from code written outside it, such as pandas operations that compute statistics on the full DataFrame before the split.
A check you can run
You can confirm that a scaler learned from training data only by comparing its stored mean with the training mean and the full-data mean.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
scaler = StandardScaler().fit(X_train)
print(np.allclose(scaler.mean_, X_train.mean(axis=0))) # True
print(np.allclose(scaler.mean_, X.mean(axis=0))) # FalseThe first comparison is true because the scaler used the training rows. The second is false because the test rows would have changed the mean.
Target leakage
Target leakage is a different problem. It cannot be fixed by reordering steps, because the issue is in the features themselves.
Examples:
- Predicting whether a customer will cancel, using a column recording the date the account was closed.
- Predicting a hospital outcome, using a feature recorded after treatment began.
- A feature computed from the label, such as an average of
yper group, calculated over the whole dataset.
Ask one question of every feature: would this value be known at the moment the model makes a prediction? If not, remove it. Suspiciously high scores, such as near-perfect accuracy on a hard problem, are a common sign.
For time-ordered data, a random split can also leak, because the model trains on rows from after the test period. Split by time instead, so the training rows come before the test rows.
Summary of rules
- Split before any step that learns from data.
- Call
fitorfit_transformon training data only. Calltransformon everything else. - Put preprocessing and model in one
Pipeline, and evaluate the pipeline. - Check each feature for information that is unavailable at prediction time.
- Deduplicate and split by time where the data requires it.
Exercise
A colleague writes X_scaled = StandardScaler().fit_transform(X), then runs cross_val_score(LogisticRegression(), X_scaled, y, cv=5). Explain why the score may be too optimistic, and rewrite the code to avoid the problem.
Show answer
The scaler was fitted on every row, so each validation fold has already influenced the mean and scale used to transform the training folds. The validation data is not fully unseen. Put the scaler in a pipeline and evaluate that: pipe = make_pipeline(StandardScaler(), LogisticRegression()); cross_val_score(pipe, X, y, cv=5). Now the scaler is refitted on the training part of each fold only.
Exercise
After scaler = StandardScaler().fit(X_train), which call is correct for the test set: scaler.transform(X_test) or scaler.fit_transform(X_test)? Give the reason.
Show answer
scaler.transform(X_test). It applies the mean and scale learned from the training data. fit_transform(X_test) would refit the scaler on the test rows and scale them with their own statistics, so the test features would no longer match what the model was trained on.