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 shows how a Pipeline chains those steps into one estimator and why that prevents data leakage.
The leakage problem
Data leakage happens when information from the evaluation data influences training. A common cause is fitting a scaler on the full dataset before splitting. The scaler's mean and standard deviation then include the test rows, so the test score looks better than it should.
The correct order is:
- Split the data.
- Fit the scaler on the training rows only.
- Apply that fitted scaler to both training and test rows.
Doing this by hand means tracking several objects. A mistake is easy to make, especially inside cross-validation.
Building a pipeline
A Pipeline is an estimator made of ordered steps. Every step except the last is a transformer, which has fit and transform. The last step is usually a regressor, which has fit and predict.
Calling pipe.fit(X_train, y_train) fits each transformer on the training data in turn, passes its output to the next step, and fits the final model. Calling pipe.predict(X_test) only transforms the new data with the already-fitted steps, then predicts.
Example
make_pipeline builds the pipeline and names the steps automatically from the class names.
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import 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(), LinearRegression())
pipe.fit(X_train, y_train)
print("test R2:", pipe.score(X_test, y_test))
print("scaler mean (first 3):", pipe[0].mean_[:3])
print("coef (first 3):", pipe[-1].coef_[:3])You can reach a step by index (pipe[0], pipe[-1]) or by name (pipe["linearregression"]). The score method of a pipeline uses the final estimator's score, which is R-squared for regressors.
Why it matters in cross-validation
Pass the whole pipeline to cross_val_score. For each fold, scikit-learn clones the pipeline and fits it on that fold's training part only. The scaler therefore never sees the validation fold. If you scale the full dataset first and then cross-validate the bare model, every fold leaks.
from sklearn.model_selection import cross_val_score
scores = cross_val_score(pipe, X, y, cv=5, scoring="r2")
print("mean R2:", scores.mean())Common errors
- Fitting a transformer on the test set. Never call
fitorfit_transformon test data. The pipeline avoids this for you. - Scaling before splitting. Put the scaler inside the pipeline instead.
- Expecting
coef_on the pipeline. The pipeline has nocoef_. Read it from the last step, such aspipe[-1].coef_. Those coefficients apply to scaled features, so they are in standardized units. - Using a non-transformer in a middle position. Only the last step may lack
transform.
Exercise
You run StandardScaler().fit_transform(X) on the full dataset, split the result into train and test sets, and then fit LinearRegression. Why is the test score unreliable, and how do you fix it?
Show answer
The scaler computed its mean and standard deviation using the test rows, so test information leaked into training. Split first, then put the scaler and the regressor in a make_pipeline and fit it on the training set only. The pipeline then learns scaling statistics from training data and only applies them to the test data.