Sub topic 11
Chaining steps with Pipeline
This chapter assumes you know the fit, transform, and predict methods, the difference between hyperparameters and fitted attributes (names ending in an underscore), and why a scaler must learn its statistics from training data only. It builds on those ideas to show how Pipeline enforces them for you.
Why chain steps at all
Preprocessing followed by a model is the most common scikit-learn workflow. Written by hand, it looks like this:
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
scaler = StandardScaler().fit(X_train)
model = LogisticRegression(max_iter=200)
model.fit(scaler.transform(X_train), y_train)
print(model.score(scaler.transform(X_test), y_test))This code is correct, but it depends on you. You must call transform with the same fitted scaler everywhere, in the same order, every time you predict. If you forget once, the model receives unscaled data and returns poor predictions with no error. If you fit the scaler on the full dataset before splitting, you leak test information into training.
A Pipeline packages the scaler and the model into one estimator. You call fit and predict once, and the pipeline applies each step in the right order.
Building a Pipeline
A Pipeline takes a list of (name, estimator) pairs.
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0, stratify=y
)
pipe = Pipeline([
("scale", StandardScaler()),
("model", LogisticRegression(max_iter=200)),
])
pipe.fit(X_train, y_train)
print(pipe.predict(X_test[:5]))
print(pipe.score(X_test, y_test))Two rules govern the list:
- Every step except the last must be a transformer, meaning it has
fitandtransform. - The last step can be anything. It is usually a predictor, but it can also be a transformer.
The names are labels you choose. They must be unique and must not contain a double underscore, because that sequence has a special meaning later in this chapter.
What happens during fit and predict
The pipeline behaves differently in fit than in predict, and the difference is where its leakage protection comes from.
During fit, each transformer calls fit_transform on the data it receives, and the output goes to the next step. The final step then calls fit with that output and y. During predict, score, predict_proba, and similar methods, each transformer calls only transform. The scaler never learns anything from the data you predict on.
Transformers inside a pipeline never see y as something to change. They may use it, as supervised feature selectors do, but they cannot modify it. A step that resamples rows or transforms the target does not fit in a standard Pipeline.
The pipeline exposes only the methods the last step has. If the final step is a LogisticRegression, then predict_proba and decision_function work. If it is a transformer, the pipeline has transform but not predict. Calling a missing method raises AttributeError.
Shorthand and inspection
make_pipeline builds the same object without explicit names. It lowercases each class name and uses that as the step name.
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
print([name for name, _ in pipe.steps])
print(pipe.named_steps["standardscaler"])
print(pipe[0] is pipe.named_steps["standardscaler"])
print(pipe[-1])The output shows the names standardscaler and logisticregression. You can reach a step by name through named_steps or by position with indexing. Slicing returns a new Pipeline, so pipe[:-1] is the preprocessing part alone. Because it holds the same fitted step objects, you can call transform on it once the full pipeline is fitted.
If you use the same class twice, make_pipeline appends a number (standardscaler-1, standardscaler-2). Choose explicit names with Pipeline when you plan to tune or inspect steps, because the names appear in parameter strings.
Reading fitted attributes
Fitting the pipeline fits its steps in place. The learned attributes sit on the individual steps.
import numpy as np
from sklearn.datasets import load_iris
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 = load_iris(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0)
pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=200))
pipe.fit(X_train, y_train)
scaler = pipe[0]
print(np.allclose(scaler.mean_, X_train.mean(axis=0))) # True
print(pipe[-1].coef_.shape) # (3, 4)
X_test_scaled = pipe[:-1].transform(X_test)
print(X_test_scaled.shape) # (38, 4)The scaler's mean_ equals the training mean, which confirms that the pipeline fitted it on training data only. Slicing off the last step is a practical way to inspect what the model actually receives.
Setting hyperparameters through the pipeline
A pipeline is itself an estimator, so get_params, set_params, and clone all work on it. Parameters of inner steps are addressed as stepname__parametername, with two underscores.
from sklearn.base import clone
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
pipe = Pipeline([
("scale", StandardScaler()),
("model", LogisticRegression(max_iter=200)),
])
print(pipe.get_params()["model__C"]) # 1.0
other = clone(pipe).set_params(model__C=0.1, scale__with_mean=False)
print(pipe.get_params()["model__C"], other.get_params()["model__C"]) # 1.0 0.1
try:
pipe.set_params(clf__C=0.1)
except ValueError:
print("no step named clf")clone copies the whole pipeline, including a fresh unfitted copy of every step, so changing other does not touch pipe. This naming convention is what later lets a search tool vary preprocessing and model settings in one grid, such as model__C and scale__with_mean.
You can also replace a whole step. Passing scale="passthrough" to set_params makes that step do nothing, which is useful for comparing a model with and without scaling.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `TypeError` mentioning `fit` and `transform` at construction or fit | A non-final step is a predictor, such as a classifier, with no `transform` | Move it to the last position or remove it |
| `AttributeError: ... has no attribute 'predict'` | The last step is a transformer | Add a predictor as the final step, or use `transform` |
| `ValueError: Invalid parameter 'x' for estimator Pipeline` | A step name in `set_params` or in a parameter string is wrong | Check `pipe.get_params().keys()` for the real names |
| Test score looks too good | A scaler or encoder was fitted on all rows before splitting | Split first, then fit the whole pipeline on the training part only |
| `NotFittedError` on `pipe[0].transform` | Slicing was used before calling `fit` | Fit the full pipeline first |
Two further points matter in practice:
- If your data has column names, a pipeline passes through whatever its first step accepts. A pandas DataFrame works as input to
fitandpredict, but later steps usually receive NumPy arrays. A custom step that selects columns by name must therefore be placed first, or you must use a column-aware transformer. - Fitting a pipeline repeatedly with a slow transformer repeats the slow work. The
memoryargument caches fitted transformers on disk. Use it only when preprocessing is expensive, because it adds complexity and disk use.
Summary of the model
A pipeline is a sequence of fitted steps behind one estimator interface. fit runs fit_transform through the transformers and fit on the last step. Every other method runs transform through the transformers and then the last step's method. Parameters are reachable with step__param. Because the pipeline is a single estimator, it can be passed anywhere scikit-learn expects one, including evaluation tools that refit it many times on different subsets of the data.
Exercise
A pipeline is built with Pipeline([("prep", StandardScaler()), ("clf", LogisticRegression())]). Write a call that returns an unfitted copy with the regularization strength C set to 5 and leaves the original pipeline unchanged. Then explain why Pipeline([("clf", LogisticRegression()), ("prep", StandardScaler())]) fails to fit.
Show answer
Use clone(pipe).set_params(clf__C=5). The clone call makes an independent unfitted copy, and clf__C addresses the C parameter of the step named clf. The reordered pipeline fails because every step except the last must be a transformer, and LogisticRegression has no transform method, so scikit-learn raises a TypeError when you call fit.
Exercise
After pipe.fit(X_train, y_train) on a pipeline made with make_pipeline(StandardScaler(), LogisticRegression()), how do you get the scaled version of X_test that the model would see, and which attribute on the scaler shows the training means?
Show answer
Use pipe[:-1].transform(X_test) to apply every step except the model. The training means are in pipe[0].mean_, or equivalently pipe.named_steps["standardscaler"].mean_.