Sub topic 7
Keeping preprocessing inside the folds
This chapter assumes you know k-fold cross-validation, scikit-learn's fit and transform pattern, and the basics of Pipeline. It covers data leakage, one of the most common ways an evaluation score ends up too good.
What leakage is
Data leakage happens when information from the evaluation data influences the training of the model. Preprocessing is a frequent source. Scalers, imputers, and feature selectors all learn something from data: means, medians, or which columns correlate with the label.
If you fit one of these steps on the full dataset and then cross-validate, every test fold has already shaped the transformation. The model never sees test labels directly, but the score is still optimistic.
A leaky example
Feature selection on the labels is the clearest case. The data below is pure noise, so no honest method can beat 50% accuracy.
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.RandomState(0)
X = rng.normal(size=(100, 2000))
y = rng.randint(0, 2, size=100)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
# Leaky: features are chosen using all labels, then cross-validated.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(), X_selected, y, cv=cv)
# Correct: selection is refit on the training part of each fold.
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression())
honest = cross_val_score(pipe, X, y, cv=cv)
print(f"leaky: {leaky.mean():.2f}")
print(f"honest: {honest.mean():.2f}")The leaky score lands well above 0.5 on data with no signal. The pipeline score stays near 0.5, which is the correct answer.
Why a Pipeline fixes it
A Pipeline bundles preprocessing and the model into one estimator. When cross_val_score or GridSearchCV fits it, the following happens for each split:
- The pipeline is cloned.
- Every step is fit on the training indices only.
- The fitted steps transform the test indices, without refitting.
- The score is computed on those transformed test rows.
Pipelines inside nested cross-validation
Nested cross-validation has two levels of splitting, so leakage can enter at two levels. Putting the pipeline inside GridSearchCV protects both:
- In the inner loop, each candidate is fit on inner-training rows only, so the inner validation rows never influence preprocessing.
- In the outer loop, the whole search, pipeline included, is refit on each outer training set.
The svc__C style of parameter name is how the grid reaches steps inside the pipeline. The name is the lowercase step name, two underscores, then the parameter.
from sklearn.model_selection import GridSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
pipe = make_pipeline(StandardScaler(), SVC())
param_grid = {"svc__C": [0.1, 1, 10]}
search = GridSearchCV(pipe, param_grid, cv=5)Common mistakes
- Calling
fit_transformon the fullXbefore any split. - Imputing missing values with a global mean.
- Selecting features by their correlation with
ybefore cross-validation. - Fitting a
PCAor an encoder on train and test together.
Anything that learns from the data belongs in the pipeline. Fixed transformations that learn nothing, such as a log transform, can safely stay outside.
Exercise
You standardize all of X with StandardScaler, then run GridSearchCV with 5 folds on the scaled data. Which rows influenced the scaler's mean and variance, and how do you fix this?
Show answer
Every row did, including rows that later land in the validation folds. Fix it by putting the scaler and the model in a Pipeline, such as make_pipeline(StandardScaler(), SVC()), and passing that pipeline to GridSearchCV. The scaler is then refit on the training rows of each split.