Sub topic 3
Why preprocessing outside a pipeline leaks information
This chapter assumes you can split data with train_test_split, fit a scikit-learn model, and call fit and transform on a scaler. It explains what data leakage is, how it enters through preprocessing, and why the next chapter's Pipeline prevents it.
What leakage means
Data leakage happens when information from data the model should not have seen influences training. A validation or test score then looks better than the model will perform on new data.
Preprocessing steps such as scalers, imputers, and feature selectors learn values from data. A StandardScaler learns a mean and a standard deviation per column. If it learns them from rows that later end up in the validation set, those rows have shaped the training inputs.
The common mistake
This code looks harmless:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
X_scaled = StandardScaler().fit_transform(X) # fitted on every row
scores = cross_val_score(LogisticRegression(max_iter=1000), X_scaled, y, cv=5)
print(scores.mean())The scaler saw all rows before cross-validation split them. Each validation fold was therefore scaled with a mean and variance that include its own values. The model never sees the labels this way, but the validation rows still affected the training features.
The sequence below shows where the information crosses over.
A leak you can measure
Scaling leaks only a little, so scores barely change. Feature selection shows the problem clearly. The data below is pure noise: random features and random labels. No model can do better than chance, which is about 0.5 accuracy.
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.RandomState(0)
X = rng.randn(100, 5000)
y = rng.randint(0, 2, size=100)
# Leaky: select the 20 best features using all labels, then cross-validate.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_selected, y, cv=5)
print("leaky: ", leaky.mean())
# Correct: selection is refit inside each training fold.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X, y, cv=5)
print("correct:", honest.mean())The leaky score is well above 0.5, because the selector picked features that happened to correlate with the validation labels. The correct score stays near 0.5, which is the true answer for noise.
The rule that prevents it
Every step that learns from data must be fitted on the training data only. It is then applied, without refitting, to validation and test data.
- Call
fitorfit_transformon the training part only. - Call
transformon the validation or test part. - Never call
fiton data you plan to evaluate on.
Doing this by hand works for a single train/test split. It becomes error-prone with cross-validation, where you must repeat the rule for each of the five or ten folds. A pipeline automates it: when cross_val_score receives a pipeline, it refits every step on each fold's training rows. The next chapter builds one.
Other places leaks hide
- Imputing missing values with the column mean computed on the full dataset.
- Fitting a
OneHotEncoderon all rows, so categories that appear only in the test set are known in advance. - Selecting features, or tuning a threshold, using the whole dataset.
- Tuning hyperparameters on the test set, which uses the test labels indirectly.
A high cross-validation score does not prove there is no leakage. If a result looks too good for the problem, check the order of your splitting and fitting steps first.Exercise
A colleague runs SimpleImputer(strategy="mean").fit_transform(X) on the whole dataset, then calls train_test_split and trains a model. Why is the test score unreliable, and what should change?
Show answer
The imputer learned the column means from all rows, including the test rows, so test data influenced the values filled into the training set. Split first, fit the imputer on the training part only, and apply transform to the test part. Putting the imputer and model in a pipeline enforces this automatically.