Sub topic 4
Building your first Pipeline
This chapter assumes you can fit a scikit-learn model with fit and predict, split data into train and test sets, and read basic pandas and NumPy code. You should also know why a scaler learns its statistics from data (the previous chapters covered transformers and leakage).
What a Pipeline is
A Pipeline chains several steps into one object. Every step except the last must be a transformer, meaning it has fit and transform. The last step can be any estimator, usually a classifier or regressor.
The pipeline itself behaves like an estimator. You call fit, predict and score on it, and it passes the data through each step for you.
What happens on fit and predict
When you call pipe.fit(X, y), the pipeline does this:
- Calls
fit_transformon the first step usingXandy. - Passes the output to the next step, and repeats for each transformer.
- Calls
fiton the final estimator with the transformed data.
When you call pipe.predict(X_new), each transformer only calls transform. Nothing is learned from the new data. This is the property that prevents leakage: the scaler's mean and standard deviation come from the training data only.
Building one with make_pipeline
make_pipeline is the short form. It names each step automatically, using the lowercase class name.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(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=1000))
# The scaler is refit on the training part of each fold, so no information leaks from the validation part.
scores = cross_val_score(pipe, X_train, y_train, cv=5)
print(scores.mean())
pipe.fit(X_train, y_train)
print(pipe.score(X_test, y_test))Here cross_val_score receives the whole pipeline. In each fold it refits the scaler on the training portion only, then scores on the held-out portion. If you had scaled X_train first and then cross-validated only the classifier, the validation fold would have influenced the scaler. That is the leak a pipeline removes.
The last line scores the test set. The pipeline scales X_test with the training mean and standard deviation, then predicts.
Pipeline versus make_pipeline
Use Pipeline when you want to choose step names yourself. Names matter later, because tuning and inspection refer to steps by name.
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
pipe = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
print(pipe.steps)
print(pipe.named_steps["scale"])| Feature | `Pipeline` | `make_pipeline` |
|---|---|---|
| Step names | You choose them | Generated from class names |
| Syntax | List of `(name, estimator)` tuples | Estimators as positional arguments |
| Best for | Code you will tune or share | Quick experiments |
With make_pipeline, two steps of the same class get suffixes (standardscaler-1, standardscaler-2). Explicit names are clearer in that case.
Common errors
- A non-transformer in the middle. Every step before the last needs
transform. A classifier in the middle raises aTypeErrorwhen you callfit. - Fitting a transformer first, then the pipeline. Calling
scaler.fit_transform(X)and then passing the result to a pipeline that also contains a scaler scales twice and leaks again. - Duplicate or invalid step names. Names must be unique. A name cannot contain a double underscore, because
__is reserved for addressing parameters. - Using
fit_transformon the pipeline when the last step is a classifier. A classifier has notransform, so the pipeline has notransformeither. Usefitandpredict.
Exercise
You scale all of X with StandardScaler, split into train and test, and then cross-validate a LogisticRegression on the training data. Why can the cross-validation score be overly optimistic, and how does wrapping both in a Pipeline fix it?
Show answer
The scaler learned its mean and standard deviation from every row, including rows that later land in validation folds, so validation data influenced preprocessing. With a Pipeline passed to crossvalscore, the scaler is refit on only the training portion of each fold, and the validation portion is only transformed with those statistics.
Exercise
You build make_pipeline(StandardScaler(), LogisticRegression()). What name does the classifier step get, and what call returns the fitted scaler object?
Show answer
The classifier step is named "logisticregression". The fitted scaler is available as pipe.named_steps["standardscaler"] (or pipe[0]).