Sub topic 4
Building your first Pipeline
This chapter assumes you can fit a scikit-learn model with fit and predict, split data with train_test_split, and read basic NumPy arrays. You should also know what a transformer such as StandardScaler does. Earlier chapters covered the estimator API, common transformers, and why preprocessing on the full dataset leaks information. Here you put those pieces together into a Pipeline.
What a Pipeline is
A Pipeline is an object that chains a sequence of transformers and one final estimator. It behaves like a single estimator. You call fit once, and predict or score once, and the pipeline passes data through each step in order.
Without a pipeline, a typical workflow looks like this:
- Fit a scaler on the training data.
- Transform the training data.
- Fit a model on the transformed training data.
- Transform the test data with the same fitted scaler.
- Predict with the model.
Every one of those lines is a chance to apply the wrong object to the wrong data. A pipeline moves all of it behind a single interface.
Your first pipeline
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))make_pipeline takes the steps as positional arguments and names them for you. The scaler comes first because the logistic regression is sensitive to feature scale. cross_val_score receives the whole pipeline, not a pre-scaled array. That detail is what prevents leakage, and the next sections explain how.
Pipeline versus make_pipeline
There are two constructors. They build the same kind of object.
Pipeline takes a list of (name, estimator) tuples. You choose the names.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import 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 = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
pipe.fit(X_train, y_train)
print(pipe.named_steps["scale"].mean_[:3]) # fitted attribute of the scaler
print(pipe[0] is pipe.named_steps["scale"]) # indexing returns the same object
print(pipe.predict(X_test[:5]))make_pipeline generates names from the lowercased class names, such as standardscaler and logisticregression. If two steps share a class, scikit-learn appends a counter, as in standardscaler-1 and standardscaler-2.
| Constructor | Names | Best used when |
|---|---|---|
| `Pipeline([...])` | You choose them | You tune hyperparameters, inspect steps, or want stable, readable names |
| `make_pipeline(...)` | Generated from class names | You want a quick pipeline for cross-validation or a one-off model |
Explicit names matter once you tune parameters, because the name is part of the parameter path (clf__C). Generated names work, but they are longer and break if you swap a step for a different class.
What happens when you call each method
The pipeline's behavior depends on which method you call. The diagram shows fit and predict on a pipeline with one transformer and one classifier.
The rules are:
fit(X, y): for each intermediate step, callfit_transformon the data and pass the output to the next step. On the final step, callfit.predict(X): for each intermediate step, calltransformonly. On the final step, callpredict.score(X, y): transform with every intermediate step, then call the final estimator'sscore.transform(X): available only if the final step is also a transformer. The pipeline then acts as a larger transformer.
The pipeline exposes only the methods its last step supports. If the last step is a regressor, predict works but predict_proba raises an AttributeError. If the last step is a classifier with predict_proba, the pipeline gets predict_proba too.
The key point is that transform, not fit, runs at prediction time. The scaler stores the training mean and standard deviation in mean_ and scale_. It reuses those values on every later call and never re-estimates them from new data.
How a pipeline prevents leakage
Data leakage happens when information from data you are evaluating on influences the model you evaluate. Preprocessing is a quiet source of it, because a scaler or imputer learns statistics from the data you give it.
This is the leaky pattern:
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
X, y = load_breast_cancer(return_X_y=True)
# Wrong: the scaler sees every row, including rows that later act as validation folds.
X_scaled = StandardScaler().fit_transform(X)
leaky = cross_val_score(LogisticRegression(max_iter=1000), X_scaled, y, cv=5)
print(leaky.mean())Each validation fold was already used to compute the mean and variance that scaled it. The effect is small for a scaler, so the score may look almost the same. The problem gets serious with steps that use the labels or that fit many parameters, such as feature selection, target encoding, or dimensionality reduction. For those steps the inflated score can be large.
When you pass a pipeline to cross_val_score, scikit-learn clones the pipeline for each fold. It fits the clone on the training part only and applies it to the validation part with transform. Every fold gets its own fresh scaler. You write no extra code to get this behavior.
Splitting the test set off first is still necessary. In the first example, the pipeline sees only X_train during cross-validation and fit. The test set is touched once, at the end, by score.
Rules for the steps
A pipeline validates its steps when you construct it and again when you fit it. These are the rules and the errors they produce.
- Every step except the last must be a transformer. It must implement
fitandtransform, or be"passthrough"orNone. A classifier in the middle raises aTypeError. - The last step can be any estimator. It can be a classifier, a regressor, a clusterer, or another transformer.
- Step names must be unique. Duplicates raise a
ValueError. - Step names cannot contain double underscores. The double underscore separates a step from its parameter, so a name such as
my__stepis rejected. - Step names cannot match constructor arguments of the pipeline such as
memoryorsteps.
You can see rule 1 in action:
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
try:
Pipeline([
("clf", LogisticRegression()),
("scale", StandardScaler()),
]).fit([[0.0], [1.0]], [0, 1])
except TypeError as error:
print("TypeError:", error)Transformers in the middle of a pipeline also receive y during fit, so a supervised step such as SelectKBest works. They do not transform y. A standard pipeline changes only the features. If you need to resample rows or transform the target, you need other tools, such as TransformedTargetRegressor or the imbalanced-learn pipeline.
Accessing and changing steps
A pipeline is a regular estimator, so it supports the usual parameter tools. Four are worth knowing now.
named_stepsis a dictionary-like object.pipe.named_steps["clf"]returns the step by name.- Indexing and slicing work on position or name.
pipe[0]returns the first step.pipe[:-1]returns a new pipeline of all steps except the last.pipe["scale"]also works. get_params()andset_params()read and write parameters with thestep__parameterconvention.pipe.set_params(clf__C=0.5)changes the regularization strength of the step namedclf.- Replacing a step is done with
set_params(scale=MinMaxScaler()). Setting a step to"passthrough"skips it while keeping its name in the pipeline.
Slicing is useful for debugging. pipe[:-1].transform(X_test) shows you exactly what the final estimator receives.
Common errors and how to fix them
| Symptom | Likely cause | Fix |
|---|---|---|
| `TypeError: All intermediate steps should be transformers` | An estimator without `transform` sits before the last step | Move it to the end, or replace it with a transformer |
| `AttributeError` on `predict_proba` or `transform` | The final step does not provide that method | Check what the last step supports, or choose a different final estimator |
| `ValueError: Invalid parameter ... for estimator Pipeline` | Wrong step name in `set_params` or in a parameter grid | Print `pipe.get_params().keys()` and copy the exact name |
| `NotFittedError` when calling `predict` | `fit` was not called on this pipeline object | Call `fit`, or use the object that was fitted |
| Test score much lower than cross-validation score | Preprocessing fit outside the pipeline, or the test set used during tuning | Move all learning steps into the pipeline and touch the test set once |
| `ConvergenceWarning` from the logistic regression | Features unscaled, or too few iterations | Keep the scaler in the pipeline and raise `max_iter` |
When a name is wrong, pipe.get_params().keys() is the fastest check. It lists every parameter path the pipeline accepts.
Choosing a design
Use these criteria when you decide how to structure a first pipeline.
- Put in the pipeline anything that learns from data. A fixed operation, such as a log transform, does not leak, but putting it in the pipeline still guarantees the same operation runs at prediction time.
- Name steps explicitly if you plan to tune or inspect them. The names then form a stable interface to your code.
- Keep the pipeline flat while it is small. Nesting pipelines inside pipelines is allowed. The next chapter introduces
ColumnTransformer, which is the main reason to nest. - Keep the test set out of the loop. Cross-validate and tune on the training set, and call
scoreon the test set once.
Exercise
A colleague fits StandardScaler on the full dataset X, then calls train_test_split and cross_val_score on a plain LogisticRegression using the scaled data. Name the problem, and rewrite the workflow so that scaling happens correctly.
Show answer
The scaler learned its mean and standard deviation from rows that later become validation and test rows, so information from the evaluation data leaks into training. Split first, then build pipe = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)). Run cross_val_score(pipe, X_train, y_train, cv=5) on the training set. Then call pipe.fit(X_train, y_train) and pipe.score(X_test, y_test). The pipeline refits the scaler on each fold's training part and on the full training set, and never on the test data.
Exercise
Given pipe = Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression())]) that has already been fitted, which expression returns what the classifier receives for X_test? Which expression changes the regularization strength to 0.5?
Show answer
pipe[:-1].transform(X_test) applies every step except the last, so it returns the scaled features that clf would receive. pipe.set_params(clf__C=0.5) sets the parameter C on the step named clf. You must call fit again after changing it, because the fitted coefficients still reflect the old value.
Exercise
You build make_pipeline(LogisticRegression(), StandardScaler()) and call fit. What happens, and why?
Show answer
A TypeError is raised. Every step except the last must be a transformer with fit and transform, and LogisticRegression has no transform. Swap the order so the scaler comes first and the classifier is last.