Sub topic 7
Keeping preprocessing inside the folds
This chapter assumes you know how k-fold cross-validation works and how GridSearchCV tunes hyperparameters. You should also know scikit-learn's fit/transform convention and have used make_pipeline at least once. The chapter is about one rule: every step that learns something from data must be fitted only on the training part of each split.
What data leakage is
Data leakage means information from the evaluation data influences the model or its preprocessing before the model is scored. The score then measures how well the model remembers something about the test rows, not how it handles new data.
Leakage is easy to introduce because preprocessing looks harmless. A typical script scales or selects features on the full dataset, then calls cross_val_score. Each fold's test rows have already contributed to the scaler's mean, the selected columns, or the imputed values. The model never saw the test labels directly, but the pipeline did.
Which steps need to be inside the folds
A step must be inside the folds if it has a fit that learns from the data. Common examples:
- Scaling (
StandardScaler,MinMaxScaler): learns means, variances, or ranges. - Imputation (
SimpleImputer,KNNImputer): learns fill values from the data. - Feature selection (
SelectKBest,RFE): learns which columns to keep, and often uses the labels. - Dimensionality reduction (
PCA): learns directions from the data. - Encoders (
OneHotEncoder, target encoding): learn the category set, or label-dependent statistics. - Resampling (oversampling such as SMOTE): creates synthetic rows from training rows.
A step with no learned state is safe to run before splitting. Examples are taking a logarithm, converting units, or parsing a date string into a number. The same function is applied to every row no matter which rows are present.
The most damaging leaks involve the labels. Feature selection that uses y can make a model look good on data with no signal at all, as the next section shows.
A demonstration with pure noise
The data below is random noise: 100 rows, 5000 features, and random labels. No honest model can beat 50% accuracy. The leaky version selects the 20 best features using all rows and all labels, then cross-validates.
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, 5000))
y = rng.randint(0, 2, size=100)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
model = LogisticRegression(max_iter=1000)
# Leaky: selection sees every label, including those of future test folds.
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(model, X_selected, y, cv=cv)
# Honest: selection is refitted on the training rows of each fold.
pipe = make_pipeline(SelectKBest(f_classif, k=20), model)
honest = cross_val_score(pipe, X, y, cv=cv)
print(f"leaky accuracy: {leaky.mean():.3f}")
print(f"honest accuracy: {honest.mean():.3f}")The leaky accuracy is typically well above 0.5, often by 0.3 or more. The honest accuracy stays near 0.5, which is the correct answer for noise. With 5000 candidate columns, some correlate with the random labels purely by chance. Selecting them with all the labels bakes that chance into the features, and cross-validation then rewards it.
How a pipeline fixes it
A Pipeline bundles preprocessing and the model into a single estimator. When cross_val_score or GridSearchCV fits that estimator on a training fold, each step is fitted in order on that fold only. The test fold is then pushed through the already-fitted steps with transform, never with fit.
The dotted arrows are the only connection between the two sides of the diagram. Statistics flow from the training fold to the test fold, never the other way.
Pipelines inside nested cross-validation
Nested cross-validation has two levels of splitting, so a leak can happen at either level. Put the pipeline inside the GridSearchCV, and put the GridSearchCV inside cross_val_score. Then:
- For each outer split, the search receives only the outer training rows.
- For each inner split, the pipeline is refitted on the inner training rows only.
- The outer test rows are never seen by any
fitcall until the final scoring of that outer fold.
Preprocessing choices can also be tuned. Parameter names in a pipeline use the step name, two underscores, then the parameter name.
from sklearn.datasets import load_breast_cancer
from sklearn.feature_selection import SelectKBest, f_classif
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV, StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
pipe = make_pipeline(
StandardScaler(),
SelectKBest(f_classif),
LogisticRegression(max_iter=2000),
)
param_grid = {
"selectkbest__k": [5, 10, 20],
"logisticregression__C": [0.1, 1, 10],
}
inner_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=1)
outer_cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=2)
search = GridSearchCV(pipe, param_grid, cv=inner_cv)
scores = cross_val_score(search, X, y, cv=outer_cv)
print("outer scores:", scores.round(3))
print(f"nested CV accuracy: {scores.mean():.3f} +/- {scores.std():.3f}")Here the number of selected features k is a hyperparameter like any other. The inner loop chooses it using only the outer training rows. This is the honest way to ask "how many features should I keep?"
Mixed column types
Real tables mix numeric and categorical columns. ColumnTransformer applies different preprocessing to different columns and still behaves as one estimator, so it belongs inside the pipeline.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
df = pd.DataFrame({
"age": [25, 32, None, 51, 46, 23, 38, 60, 29, 41, 35, 52],
"income": [40, 52, 61, None, 88, 35, 70, 95, 48, 66, 58, 90],
"city": ["a", "b", "a", "c", "b", "a", "c", "b", "a", "c", "b", "c"],
"bought": [0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 1],
})
X = df[["age", "income", "city"]]
y = df["bought"]
numeric = make_pipeline(SimpleImputer(strategy="median"), StandardScaler())
categorical = OneHotEncoder(handle_unknown="ignore")
preprocess = ColumnTransformer([
("num", numeric, ["age", "income"]),
("cat", categorical, ["city"]),
])
model = make_pipeline(preprocess, LogisticRegression())
cv = StratifiedKFold(n_splits=3, shuffle=True, random_state=0)
print(cross_val_score(model, X, y, cv=cv))The median used for imputation is computed from each training fold only. handle_unknown="ignore" keeps the encoder from failing when a test fold contains a category that the training fold lacked.
Leaks that a Pipeline does not catch
A pipeline only protects the steps you put in it. Watch for these:
- Preprocessing before the split. Any
fit_transformon the fullXbefore callingcross_val_scoreorGridSearchCVis a leak, however small. - Duplicates and near-duplicates. If the same customer, image, or patient appears in several rows, one copy can land in the training fold and another in the test fold. Use a grouped splitter, covered in a later chapter.
- Features built from the future or from the label. A column computed using the outcome, or using events after the prediction time, is a leak that no pipeline can detect.
- Resampling outside the pipeline. Oversampling before splitting puts copies or interpolations of test rows into the training data. The
imbalanced-learnpackage provides a pipeline that applies resampling to training folds only. The standard scikit-learnPipelinedoes not support samplers. - Reusing the test fold to make decisions. Looking at outer scores and then changing the grid, the features, or the model family makes the outer score optimistic again.
Cost and caching
Putting preprocessing inside the pipeline means it is refitted for every inner fold of every outer fold. With a slow transformer this adds up. If a step does not depend on any hyperparameter being tuned, you can cache its fitted result with make_pipeline(..., memory="cache_dir"). The cache is keyed on the step's parameters and the input data, so it is reused only when both match. This keeps correctness: the cache stores fits made on training rows only.
Summary of the rule
- Identify every step that learns from data, especially those that use
y. - Put all of them, and the model, into one
Pipeline. - Pass the pipeline, or a
GridSearchCVwrapping it, to the cross-validation function. - Never call
fitorfit_transformon data that includes rows you will later evaluate on.
Exercise
A colleague runs X_scaled = StandardScaler().fit_transform(X) and then runs nested cross-validation on X_scaled with a GridSearchCV over an SVM. They say that this is fine because the scaler never sees the labels. Is the nested score still fully honest? How would you change the code?
Show answer
It is not fully honest. The scaler's means and standard deviations were computed using every row, including the outer test rows, so information about the test rows reaches the model before it is scored. The effect is usually small for scaling, but it is still a leak, and the habit does not stay harmless for label-aware steps. Fix it by building make_pipeline(StandardScaler(), SVC()), passing that pipeline to GridSearchCV with parameter names like svc__C, and passing the raw X to cross_val_score. The scaler is then refitted on the training rows of every inner and outer split.
Exercise
You run the noise experiment from this chapter with SelectKBest inside a pipeline and still see an accuracy of 0.7. List two places to look for the cause.
Show answer
First, check whether anything was fitted on all the data before the pipeline, such as another selection or scaling step run earlier in the script. Second, check for duplicated or near-duplicated rows that a plain splitter can place in both train and test folds. Also check that y is not derived from or correlated with a feature by construction, and that the random data was not generated with a shared structure.