Sub topic 6
Avoiding data leakage with pipelines
This chapter assumes you know scikit-learn's fit, transform and predict methods, and that you have run k-fold cross-validation with cross_val_score. You should also know what a scaler or feature selector does.
What leakage is
Data leakage happens when information from the test data influences training. The score then looks better than the model's real performance on new data.
The most common cause is preprocessing before splitting. Suppose you scale all rows, then run cross-validation. The scaler's mean and standard deviation were computed from rows that later serve as test rows. Each test fold has already influenced the model's inputs.
Steps that learn from data are the risky ones:
- Scaling and normalization (learn means, variances, ranges).
- Imputation (learns fill values).
- Feature selection (learns which columns correlate with the labels).
- Dimensionality reduction such as PCA.
- Target or frequency encoding.
Feature selection is the worst offender, because it uses the labels directly.
A leak you can measure
The example below uses pure noise: 2000 random features and random labels. No model can beat 50% accuracy on this data. The first score selects features on the full dataset before cross-validation. The second puts the selector inside a pipeline.
import numpy as np
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
rng = np.random.default_rng(0)
X = rng.normal(size=(60, 2000))
y = rng.integers(0, 2, size=60)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
# Leaky: the selector sees every label before the folds are made.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=cv)
# Honest: the selector is refit on each training fold only.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=cv)
print(f"leaky: {leaky.mean():.2f}")
print(f"honest: {honest.mean():.2f}")The leaky score is typically far above 0.5. The honest score stays near 0.5, which is correct for noise. The exact numbers depend on the random seed.
How a pipeline fixes it
A Pipeline chains transformers and a final estimator into one object with fit and predict. When you pass it to cross_val_score, scikit-learn clones it for every fold. In each fold it calls fit on the training rows only, so every step learns from training data alone. It then applies the fitted transformers to the test rows with transform.
The test rows never reach a fit call. This is the property you want to keep.
Practical rules
- Put every learned step in the pipeline, not only the scaler.
- Use
make_pipelinefor short pipelines. Step names are the lowercase class names, such asstandardscaler. - Pass the raw
Xtocross_val_score. Do not transform it first. - For mixed column types, use
ColumnTransformerinside the pipeline. - Fit the final model on all training data with the same pipeline. Use the same object in production, so serving applies the same preprocessing.
Common errors
- Leak through tuning. Choosing hyperparameters by looking at the same CV scores you report makes them optimistic. A later chapter covers nested cross-validation.
- Leak through duplicates. Repeated or near-identical rows can land in both train and test folds. Grouped splitting addresses this.
- Leak through time. Future rows in the training set make forecasting scores unrealistic. Forward-chaining splits address this.
Exercise
A colleague runs SimpleImputer(strategy="mean").fit_transform(X) on the full dataset, then calls cross_val_score on a classifier with the imputed data. Which part of this is leaky, and how do you fix it?
Show answer
The imputer computes column means using rows that later become test rows, so test data influences the fill values. Put the imputer in a pipeline, for example make_pipeline(SimpleImputer(strategy="mean"), clf), and pass the raw X with its missing values to cross_val_score. The means are then computed from each training fold only.