Pipelines
A real model is rarely a single estimator. You impute missing values, scale, maybe select features, and then fit a classifier. Done by hand, each step must be fitted on the training data and applied — in the same order, with the same fitted statistics — to validation data, test data and every future prediction. That is tedious and error-prone. A pipeline chains the steps into one object that behaves like a single model.
Without a pipeline
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
scaler = StandardScaler().fit(X_tr)
pca = PCA(n_components=5, random_state=0).fit(scaler.transform(X_tr))
model = LogisticRegression(max_iter=1000).fit(pca.transform(scaler.transform(X_tr)), y_tr)
# every prediction must repeat the chain exactly
print("test accuracy:", round(model.score(pca.transform(scaler.transform(X_te)), y_te), 3))test accuracy: 0.944
It works, but forget one transform anywhere and you get silently wrong results.
With a pipeline
Pipeline takes a list of (name, step) pairs. All steps except the last must be transformers (they have fit/transform); the last step can be any estimator:
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
X, y = load_wine(return_X_y=True)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
pipe = Pipeline([
("scale", StandardScaler()),
("pca", PCA(n_components=5, random_state=0)),
("clf", LogisticRegression(max_iter=1000)),
])
pipe.fit(X_tr, y_tr) # fits every step in order
print("test accuracy:", round(pipe.score(X_te, y_te), 3))
print("predictions:", pipe.predict(X_te[:5]))
print("steps:", list(pipe.named_steps))test accuracy: 0.944
predictions: [0 1 0 0 1]
steps: ['scale', 'pca', 'clf']
pipe.fit fits the scaler, transforms, fits PCA, transforms, and fits the classifier. pipe.predict and pipe.score only transform through the first steps — never refit — which is exactly right.
make_pipeline is a shortcut that names the steps automatically after their classes (lower-case):
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.svm import SVC
pipe = make_pipeline(StandardScaler(), SVC())
print(pipe)
print(list(pipe.named_steps))Pipeline(steps=[('standardscaler', StandardScaler()), ('svc', SVC())])
['standardscaler', 'svc']
Pipelines prevent data leakage
Here is a subtle bug. We generate pure noise — there is nothing to learn — then select the "best" 20 of 2 000 features and cross-validate a model:
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=(60, 2000))
y = rng.integers(0, 2, size=60) # random labels
# WRONG: selection sees all rows, including future validation folds
X_selected = SelectKBest(f_classif, k=20).fit_transform(X, y)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_selected, y, cv=5).mean()
# RIGHT: selection is refit inside every training fold
pipe = make_pipeline(SelectKBest(f_classif, k=20), LogisticRegression(max_iter=1000))
honest = cross_val_score(pipe, X, y, cv=5).mean()
print(f"leaky CV accuracy: {leaky:.3f}")
print(f"honest CV accuracy: {honest:.3f} (labels are random, so ~0.5 is the truth)")leaky CV accuracy: 0.950
honest CV accuracy: 0.500 (labels are random, so ~0.5 is the truth)
The leaky version reports an impressive accuracy on random noise because the feature selection had already peeked at the validation labels. With the pipeline, cross_val_score refits every step inside each fold, and the score drops to coin-flip level — the honest answer.
Tuning a whole pipeline
Hyperparameters of any step can be tuned with GridSearchCV using the step__parameter naming convention. You can even tune whether to use a step, by putting "passthrough" in the grid:
from sklearn.datasets import load_wine
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.neighbors import KNeighborsClassifier
X, y = load_wine(return_X_y=True)
pipe = Pipeline([("scale", StandardScaler()), ("pca", PCA(random_state=0)), ("knn", KNeighborsClassifier())])
grid = {
"pca": ["passthrough", PCA(n_components=3, random_state=0), PCA(n_components=6, random_state=0)],
"knn__n_neighbors": [3, 7, 15],
}
search = GridSearchCV(pipe, grid, cv=5).fit(X, y)
print("best:", search.best_params_)
print("CV accuracy:", round(search.best_score_, 3))best: {'knn__n_neighbors': 7, 'pca': PCA(n_components=6, random_state=0)}
CV accuracy: 0.972
Inspecting a fitted pipeline
Steps are accessible by name or by index, so you can look inside after training:
from sklearn.datasets import load_wine
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.linear_model import LogisticRegression
X, y = load_wine(return_X_y=True)
pipe = make_pipeline(StandardScaler(), PCA(n_components=3, random_state=0),
LogisticRegression(max_iter=1000)).fit(X, y)
print("scaler means (first 3):", pipe.named_steps["standardscaler"].mean_[:3].round(2))
print("PCA variance kept:", pipe["pca"].explained_variance_ratio_.sum().round(3))
print("classifier coef shape:", pipe[-1].coef_.shape)
print("transformed first row:", pipe[:-1].transform(X[:1]).round(2))scaler means (first 3): [13. 2.34 2.37]
PCA variance kept: 0.665
classifier coef shape: (3, 3)
transformed first row: [[ 3.32 1.44 -0.17]]
pipe[:-1] is a pipeline of all steps but the last — handy to see what the final model actually receives.
Tip: A whole pipeline can be saved and loaded as one object (see Saving & Loading Models), so the preprocessing always travels with the model.
Go further: The Leakage Rules measures how much three common leaks inflate a score and ends with a checklist.
Test yourself
What must all pipeline steps except the last one provide?
predictfitandtransformscorecoef_
How do you refer to the C parameter of a step named svc in a grid search?
Csvc.Csvc__Csvc[C]
Why does putting preprocessing inside a pipeline make cross-validation more honest?
- It runs faster
- Preprocessing is refit on each training fold, so validation data never leaks into it
- It removes outliers
- It increases accuracy