Sub topic 11
Chaining steps with Pipeline
This chapter assumes you know how fit, transform, and predict work on single estimators, and that you understand why fitting on test data causes leakage. Here you will combine those pieces into one object.
Why chain steps
A typical workflow scales the features, then trains a model. Done by hand, you must remember to fit the scaler on training data only, transform both sets, and repeat every step at prediction time. Each manual step is a chance to leak data or to forget a step.
A Pipeline is an estimator that runs a list of steps in order. All steps except the last must be transformers. The last step can be a transformer or a predictor. The pipeline then exposes the methods of that last step.
Building and using a pipeline
Pipeline takes a list of (name, estimator) pairs. make_pipeline builds the names for you from the class names.
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))
print(pipe.named_steps["scale"].mean_)What happens on each call
When you call pipe.fit(X_train, y_train), the pipeline calls fit_transform on the scaler and passes the result to the model's fit. When you call pipe.predict(X_test), it calls only transform on the scaler, using the means and variances learned earlier, and then predict on the model.
The scaler never sees test data during fit. That is the leakage protection you get for free.
Accessing steps
You can reach a step by name with pipe.named_steps["model"], or by position with pipe[0]. Slicing such as pipe[:-1] returns a new pipeline with every step except the last. This is useful for inspecting transformed features.
Parameters of inner steps use the step name, a double underscore, and the parameter name. For example, pipe.set_params(model__C=0.1) changes the regularization of the model. You will use this naming again when searching over hyperparameters.
| Task | Call |
|---|---|
| Get a step by name | `pipe.named_steps["scale"]` |
| Get a step by position | `pipe[0]` |
| Drop the final step | `pipe[:-1]` |
| Set a nested parameter | `pipe.set_params(model__C=0.1)` |
Common errors
- A non-transformer in the middle. Every step before the last needs a
transformmethod. Putting a classifier in the middle raises aTypeErrorwhen you fit. - Fitting the scaler outside the pipeline. If you scale the full dataset first and then pass it to the pipeline, leakage is back. Put the scaler inside.
- Wrong step name in
set_params. A misspelled name such asmodle__Craises an error. Check names withpipe.get_params().keys(). - Duplicate step names. Names must be unique, and they cannot contain double underscores.
Exercise
You call pipe.predict(X_new) on a fitted pipeline made of a StandardScaler and a LogisticRegression. Which method of the scaler runs, and why is it not fit_transform?
Show answer
The scaler's transform runs. It reuses the mean and variance learned from the training data during fit. Calling fit_transform would relearn them from the new data, which would make predictions inconsistent with the trained model.
Exercise
How would you change the C parameter of the model step named "model" in an existing pipeline pipe to 0.5?
Show answer
pipe.set_params(model__C=0.5). The step name, a double underscore, and the parameter name form the key.