Sub topic 5
Using pipelines to keep preprocessing inside the training data
This chapter assumes you know scikit-learn estimators (fit, transform, predict), how a train/test split works, and why fitting a scaler on all rows leaks test statistics into training. If that last point is new, review the previous chapter on preprocessing leakage first.
Why manual preprocessing is fragile
The fix for preprocessing leakage is simple to state: fit every transform on training rows only, then apply it to held-out rows. Doing this by hand works for one split. It breaks down quickly:
- Each new step (imputer, encoder, scaler, feature selector) adds another
fitandtransformpair to keep in sync. - Cross-validation multiplies the problem. You would need to refit every step inside every fold yourself.
- One forgotten
fit_transformon the full dataset reintroduces leakage, and nothing warns you.
A Pipeline removes this class of mistake. It chains transformers and a final estimator into one object that behaves like a single estimator. Calling fit on the pipeline fits each step in order on whatever data you pass in. Calling predict or score only calls transform on the earlier steps. The pipeline cannot refit a scaler on test data, because the test data only ever reaches transform.
The working model
A pipeline is an ordered list of named steps. All steps except the last must implement fit and transform. The last step can be any estimator.
The scaler stores its mean and variance during fit. At prediction time it reuses them. The test rows never change what the scaler knows.
A first pipeline
This example builds a pipeline and evaluates it on a held-out split. It is the pipeline version of the "correct" branch from the preprocessing chapter.
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = make_classification(n_samples=500, n_features=10, random_state=0)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
pipe = make_pipeline(StandardScaler(), LogisticRegression())
pipe.fit(X_train, y_train)
print(pipe.score(X_test, y_test))
print(pipe.named_steps["standardscaler"].mean_[:3])make_pipeline names each step after its lowercase class name. The last line shows that the scaler's mean_ comes from the training rows. You can confirm this by comparing it with X_train.mean(axis=0)[:3].
If you want explicit names, use Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression())]). Explicit names matter once you tune parameters, as shown below.
Pipelines inside cross-validation
The main benefit shows up when you pass a pipeline to cross_val_score. For each fold, scikit-learn clones the pipeline, calls fit on that fold's training rows, and scores on that fold's validation rows. Every step is refit per fold.
The second example from the topic is the clearest demonstration. Labels are pure noise, so an honest score must sit near 0.5.
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.default_rng(0)
X = rng.normal(size=(100, 5000))
y = rng.integers(0, 2, size=100) # labels are pure noise
# Leaky: feature selection sees every label before cross-validation splits the data
X_sel = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_sel, y, cv=5).mean()
# Correct: selection is refit on the training part of each fold
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=5).mean()
print(leaky, honest)In the leaky version, SelectKBest picks the 20 columns that correlate best with y across all 100 rows. With 5000 random columns, some correlate with the labels by chance. Cross-validation then evaluates a model on columns that were chosen using the validation labels. The score comes out well above 0.5 even though there is no signal. In the pipeline version, selection sees only each fold's training rows, so the chosen columns have no real relationship to the validation labels and the score stays near chance.
Mixed column types with ColumnTransformer
Real tables mix numeric and categorical columns. ColumnTransformer applies different transformers to different columns and concatenates the results. Placed inside a pipeline, it is fit on training rows only, like any other step.
import numpy as np
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 cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 300
df = pd.DataFrame({
"age": rng.normal(40, 10, n),
"income": rng.normal(50_000, 12_000, n),
"city": rng.choice(["A", "B", "C"], n),
})
df.loc[rng.choice(n, 30, replace=False), "age"] = np.nan
y = (df["income"] + rng.normal(0, 8_000, n) > 50_000).astype(int)
numeric = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
prep = ColumnTransformer([
("num", numeric, ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore"), ["city"]),
])
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
print(cross_val_score(model, df, y, cv=5).mean())Three details matter here:
- The imputer learns the median from training rows only. Filling missing values with a median computed on the full table is a common leak.
handle_unknown="ignore"lets the encoder cope with a category that appears in a validation fold but not in the training fold. Without it, scoring raises an error.- The pipeline receives the raw DataFrame. Column selection happens inside, so there is no pre-processed copy of the data for someone to misuse.
Tuning a pipeline
Pass a pipeline to GridSearchCV and the whole chain is refit for every candidate and every fold. Parameter names use the step name, two underscores, then the parameter name.
from sklearn.datasets import make_classification
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
X, y = make_classification(n_samples=300, random_state=0)
pipe = Pipeline([("scale", StandardScaler()), ("svc", SVC())])
grid = GridSearchCV(pipe, {"svc__C": [0.1, 1, 10]}, cv=5)
grid.fit(X, y)
print(grid.best_params_)
print(grid.best_score_)This keeps preprocessing leak-free during tuning. It does not make best_score_ an unbiased final estimate, because the same folds both chose the parameters and scored them. A later chapter covers nested cross-validation for that problem.
What pipelines do not protect you from
A pipeline guards one specific thing: statistics learned by fit stay inside the training rows. Several other leaks pass straight through it.
| Leak | Why a pipeline does not help | Where it is covered |
|---|---|---|
| Target leakage | A feature that encodes the label is still a valid column | Target leakage chapter |
| Temporal leakage | The pipeline does not choose splits, so random folds still mix past and future | Temporal leakage chapter |
| Group and duplicate leakage | Related rows can still land on both sides of a split | Group and duplicate chapter |
| Preprocessing done before the pipeline | Anything you do to the full data first is outside its protection | This chapter |
| Row-wise steps that use other rows | Some operations, such as rolling means over the full table, compute values from neighbouring rows | Feature engineering chapter |
Common errors
- Calling
fit_transformon the test set. Inside a pipeline this cannot happen. Outside one, always usetransformfor held-out rows. - Splitting after the pipeline. Writing
pipe.fit_transform(X)and then splitting the output defeats the purpose. Split first, then fit. - Stateless steps are not the problem. A function such as a log transform applied row by row learns nothing, so it cannot leak by itself. Wrap it in
FunctionTransformerif you want it in the pipeline. Check that it does not read statistics from the full column. - Fitting outside, scoring inside. Fitting a transformer on all the data and then putting the fitted object in a pipeline is a leak.
Pipeline.fitrefits the step, but only if the step is not wrapped in something that skips refitting. Do not pass pre-fitted transformers and assume they are safe. - Caching surprises. The
memoryargument ofPipelinecaches fitted transformers to speed up grid searches. The cache key includes the training data, so it stays correct, but it fills disk. Use it only when transformers are slow. - Using a fitted pipeline on new splits without refitting. Cloning in
cross_val_scorehandles this. In a manual loop, callsklearn.base.clone(pipe)for each fold so state from one fold cannot carry into the next.
When a pipeline is not enough
For time-ordered or grouped data, combine the pipeline with the right splitter. cross_val_score(pipe, X, y, cv=TimeSeriesSplit(5)) or cv=GroupKFold(5) with groups=... keeps both protections active at once. The pipeline handles what the model learns from the training rows. The splitter handles which rows count as training.
Exercise
A teammate writes X_imp = SimpleImputer(strategy="mean").fit_transform(X), then calls cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()), X_imp, y, cv=5). The pipeline contains a scaler. Is the evaluation leak-free, and how would you fix it?
Show answer
No. The imputer ran on the full dataset before cross-validation, so each fold's imputed values use the mean of rows that later become validation rows. Putting the scaler in a pipeline does not cover the imputer. Fix it by adding the imputer as the first pipeline step, make_pipeline(SimpleImputer(strategy="mean"), StandardScaler(), LogisticRegression()), and passing the raw X with its missing values to cross_val_score.
Exercise
In a pipeline with steps named scale and svc, what key do you use in a GridSearchCV parameter grid to tune the SVC's gamma value?
Show answer
svc__gamma, which is the step name, two underscores, and the parameter name.