Sub topic 10
Pipelines: one object, no leakage
This chapter assumes you can fit a LinearRegression, split data with train_test_split, and scale features with StandardScaler. It covers why preprocessing must be fitted on training data only, and how a Pipeline enforces that for you.
The leakage problem
Data leakage happens when information from outside the training data influences the fitted model. The held-out score then looks better than the model will perform on new data.
Scaling is a common source. StandardScaler learns a mean and a standard deviation from the data it sees. If you fit it on the full dataset before splitting, the test rows have helped set those statistics. The effect is small for plain scaling, but it grows with steps that learn more from the data, such as feature selection, imputation, or target encoding.
Here is the leaky pattern:
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
# Wrong: the scaler sees every row, including future test rows.
X_scaled = StandardScaler().fit_transform(X)
X_train, X_test, y_train, y_test = train_test_split(
X_scaled, y, test_size=0.2, random_state=0
)
model = Ridge(alpha=1.0).fit(X_train, y_train)
print("leaky test R2:", model.score(X_test, y_test))The correct pattern fits the scaler on the training rows and only applies it to the test rows:
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
scaler = StandardScaler().fit(X_train) # learn mean/std from train only
model = Ridge(alpha=1.0).fit(scaler.transform(X_train), y_train)
print("test R2:", model.score(scaler.transform(X_test), y_test))This is correct, but you must remember to call scaler.transform at every prediction. Forgetting it, or using a scaler fitted on different data, gives silently wrong results.
What a Pipeline does
A Pipeline chains transformers and a final estimator into one object. A transformer is an estimator with fit and transform. StandardScaler, OneHotEncoder, and PolynomialFeatures are transformers. The last step is usually a model such as Ridge.
When you call pipe.fit(X, y), each transformer runs fit_transform on the data in order. The final estimator then runs fit. When you call pipe.predict(X_new), each transformer runs only transform, using the statistics it stored during fit. The final estimator then predicts.
The dotted lines show the key point. Statistics learned during fit are stored and reused. They are never recomputed from new data.
Building one
make_pipeline names each step automatically from its lowercase class name. Pipeline lets you name steps yourself.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline, make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
named = Pipeline([("scale", StandardScaler()), ("model", Ridge(alpha=1.0))])
pipe.fit(X_train, y_train)
print("test R2:", pipe.score(X_test, y_test))
print("step names:", list(pipe.named_steps))
print("custom names:", list(named.named_steps))pipe.score runs the scaler's transform and then the model's score. The pipeline exposes fit, predict, and score like any estimator, so everything that accepts an estimator accepts a pipeline.
Inspecting fitted steps
You can index a pipeline by position or by name to reach a fitted step. This is how you read coefficients after scaling.
import numpy as np
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0)).fit(X, y)
scaler = pipe[0] # same as pipe.named_steps["standardscaler"]
model = pipe[-1] # the final estimator
print("feature means:", np.round(scaler.mean_, 3))
print("coef (per std. dev.):", np.round(model.coef_, 1))
print("intercept:", round(float(model.intercept_), 1))Because the inputs were standardized, each coefficient is the change in y for a one standard deviation increase in that feature. The intercept is the prediction when every feature sits at its training mean. Slicing with pipe[:-1] returns a pipeline of just the transformers, which is useful for looking at the transformed matrix.
Pipelines and cross-validation
The main payoff comes with cross-validation. cross_val_score splits the data into folds. For each fold it clones the estimator, fits it on the training part, and scores it on the validation part. If you pass a pipeline, the scaler is refitted on each training part, so no validation fold influences its own scaling.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
pipe = make_pipeline(StandardScaler(), Ridge(alpha=1.0))
scores = cross_val_score(pipe, X, y, cv=5, scoring="r2")
print("R2 per fold:", scores)
print("mean:", scores.mean(), "std:", scores.std())If you instead scaled all of X first and passed the scaled array to cross_val_score, every fold would use statistics computed from its own validation rows. The pipeline removes that mistake.
Tuning pipeline parameters
Parameters of inner steps are addressed as stepname__parameter, with a double underscore. This lets a search tool tune a pipeline as one unit.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_diabetes(return_X_y=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=0
)
pipe = make_pipeline(StandardScaler(), Ridge())
print(sorted(k for k in pipe.get_params() if k.startswith("ridge")))
grid = GridSearchCV(pipe, {"ridge__alpha": [0.01, 0.1, 1, 10, 100]}, cv=5)
grid.fit(X_train, y_train)
print("best:", grid.best_params_)
print("test R2:", grid.score(X_test, y_test))get_params() lists every valid name, which helps when a parameter name is rejected. Later chapters use this form with RidgeCV and GridSearchCV.
Common errors
- Fitting preprocessing before the split. Any
fitorfit_transformon the full dataset leaks. Put the step in the pipeline instead. - Calling
fit_transformon test data. This refits the scaler on the test rows. Usetransform, or let the pipeline do it. - Wrong parameter name in a grid.
alphafails for a pipeline. Useridge__alpha, or the custom step name you chose. - Transformer as the last step. A pipeline ending in a transformer has
transformbut nopredict. The final step must be an estimator withpredictfor regression. - Target scaling. A pipeline transforms
Xonly. To scaley, wrap the pipeline inTransformedTargetRegressor. - Column order. A fitted pipeline expects the same columns in the same order at prediction time. With DataFrames, the next chapters use column names via
ColumnTransformer.
Cost and caching
Every cross-validation fold refits every step. For cheap steps like scaling this costs little. For slow transformers you can pass memory="cache_dir" to Pipeline or make_pipeline, which caches fitted transformers keyed by their parameters and input data.
Summary table
| Call | What each transformer does | What the final estimator does |
|---|---|---|
| `pipe.fit(X, y)` | `fit_transform` | `fit` |
| `pipe.predict(X)` | `transform` | `predict` |
| `pipe.score(X, y)` | `transform` | `score` |
Exercise
You run X_scaled = StandardScaler().fit_transform(X) and then call cross_val_score(Ridge(), X_scaled, y, cv=5). Why is the score potentially optimistic, and how do you fix it?
Show answer
The scaler computed its mean and standard deviation from all rows, so each validation fold influenced the scaling used on its own training data. Fix it by passing the raw X to cross_val_score with make_pipeline(StandardScaler(), Ridge()). The scaler is then refitted on only the training part of each fold.
Exercise
A pipeline is built with make_pipeline(StandardScaler(), Ridge()). What key do you use in a GridSearchCV parameter grid to tune Ridge's regularization strength?
Show answer
ridge__alpha. The step name is the lowercase class name, followed by a double underscore and the parameter name.