Sub topic 5
Using pipelines to keep preprocessing inside the training data
This chapter assumes you know how to split data into training and test sets and how scikit-learn estimators use fit, transform, and predict. You should also know why fitting a scaler on all rows leaks information, which the previous chapter covered. Here you will learn how a pipeline makes the correct behavior automatic.
Why a pipeline helps
A pipeline is an object that chains preprocessing steps and a final model into one estimator. When you call fit on it, each step is fitted on the data you pass in and only that data. When you call predict or score, each step only transforms.
This removes the manual bookkeeping that causes leakage. You cannot forget to fit the scaler on training rows only, because the scaler never sees any other rows.
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) # scaler.fit_transform, then model.fit
print(pipe.score(X_test, y_test)) # scaler.transform, then model.scoreThe scaler's mean and variance come from X_train alone. The test rows are only transformed with those stored values.
What happens inside the pipeline
The dotted line is the only connection between the two paths. Statistics learned from training data flow to the test path. Nothing flows the other way.
Mixed column types
Real tables mix numeric and categorical columns. ColumnTransformer applies a different preprocessing chain to each group of columns. Wrap it in a Pipeline with the model, and every learned value is still fitted on training data only. That includes imputation values, scaling statistics, and the set of categories.
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
X = pd.DataFrame({
"age": [25, 32, 47, 51, 62, 23, 36, 44, 58, 29, 41, 53],
"income": [40, 52, None, 80, 75, 38, 61, 70, 66, 45, 58, 72],
"city": ["a", "b", "a", "c", "b", "c", "a", "b", "c", "a", "b", "c"],
})
y = [0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1]
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())])
print(cross_val_score(model, X, y, cv=3).mean())Passing the whole pipeline to cross_val_score is the important move. Each fold refits every step on that fold's training part, which the next chapter builds on.
Common errors
- Fitting the preprocessor outside the pipeline. Calling
scaler.fit_transform(X)and then passing the result intocross_val_scorebrings the leak back. Put the scaler inside the pipeline instead. - Using
fit_transformon test data. Inside a pipeline this cannot happen. With manual steps, calltransformonly on held-out rows. - Transforming the target with the features. Standard pipelines transform
Xonly. If you scale or encodey, useTransformedTargetRegressorso the target transform is also fitted on training rows. - Row-dropping steps. Standard scikit-learn pipelines cannot remove rows, so dropping outliers or duplicates has to happen before the split. Decide those rules without looking at test labels. Use
imblearn.pipeline.Pipelineif you need resampling inside folds. - Caching with stale data. If you use the
memoryoption to cache fitted steps, clear the cache when the data changes.
Exercise
A teammate writes X_s = StandardScaler().fit_transform(X) and then runs cross_val_score(LogisticRegression(), X_s, y, cv=5). Why does this leak, and how do you fix it?
Show answer
The scaler is fitted on every row before cross-validation splits the data, so each validation fold's mean and variance influence the training features. Fix it by passing the raw X to cross_val_score with make_pipeline(StandardScaler(), LogisticRegression()), so the scaler is refitted on the training part of each fold.
Exercise
In the ColumnTransformer example, why is handle_unknown="ignore" set on the OneHotEncoder?
Show answer
A validation fold can contain a category that never appeared in that fold's training rows. The encoder learned its categories from training data only, so without this setting it would raise an error. With it, the unseen category becomes all zeros.