Sub topic 7
Scaling safely with Pipeline and ColumnTransformer
This chapter assumes you know how fit, transform and fit_transform work on StandardScaler and MinMaxScaler. It also assumes you know why fitting on test data causes leakage, and that you can read basic pandas code. Here you will see how scikit-learn's Pipeline and ColumnTransformer enforce the "fit on training data only" rule for you.
Why manual scaling breaks in cross-validation
Fitting a scaler on the training split works for one split. Cross-validation creates many splits. If you scale the whole dataset first and then call cross_val_score, every validation fold has already contributed to the mean and standard deviation. The scores come out slightly optimistic, and nothing warns you.
The fix is to make the scaler part of the model. A Pipeline chains steps, and its fit method fits each step on the data it receives. Cross-validation tools call fit on the training fold only, so the scaler is refit on each training fold.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
X, y = load_breast_cancer(return_X_y=True)
model = make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000))
scores = cross_val_score(model, X, y, cv=5)
print(scores.mean())make_pipeline names the steps automatically from the class names, here standardscaler and logisticregression.
How a pipeline calls its steps
The method you call decides what each step does.
| You call | Scaler step | Final model step |
|---|---|---|
| `pipeline.fit(X, y)` | `fit_transform` | `fit` |
| `pipeline.predict(X)` | `transform` | `predict` |
| `pipeline.score(X, y)` | `transform` | `score` |
After predict, the scaler's learned statistics do not change. New data is always scaled with the training statistics.
Different scalers for different columns
Real tables mix column types. You may want to standardize some columns, min-max scale others, and leave binary flags alone. ColumnTransformer takes a list of (name, transformer, columns) triples and applies each transformer to its columns. Columns you do not list are dropped unless you set remainder="passthrough".
The next example builds a small DataFrame, selects columns by name, and puts the ColumnTransformer inside a Pipeline.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler, StandardScaler
rng = np.random.default_rng(0)
df = pd.DataFrame({
"age": rng.integers(18, 80, 200),
"income": rng.normal(50000, 15000, 200),
"score": rng.uniform(0, 10, 200),
"is_member": rng.integers(0, 2, 200),
})
y = (df["income"] + 500 * df["age"] > 75000).astype(int)
preprocess = ColumnTransformer(
[
("standardize", StandardScaler(), ["age", "income"]),
("to_unit_range", MinMaxScaler(), ["score"]),
],
remainder="passthrough", # keeps is_member unchanged
)
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
print(cross_val_score(model, df, y, cv=5).mean())
model.fit(df, y)
print(model.named_steps["prep"].get_feature_names_out())The pipeline receives the raw DataFrame. Each fold fits the ColumnTransformer on its training rows only, and the scalers inside it learn their statistics from those rows.
get_feature_names_out() returns names such as standardize__age and remainder__is_member. The output columns are ordered by transformer, not by the original column order. Selecting columns by name keeps the code correct if the column order of your data changes.
Inspecting fitted steps
After fit, the fitted objects are available by name:
model.named_steps["prep"]returns the fittedColumnTransformer.model.named_steps["prep"].named_transformers_["standardize"].mean_returns the means learned forageandincome.model[-1]returns the last step, the classifier.
Use these to check that the learned statistics come from the training data.
Common errors
- Scaling before splitting. Calling
fit_transformon the full dataset and then splitting or cross-validating leaks information. Put the scaler in the pipeline instead. - Forgetting
remainder. Columns not listed in aColumnTransformerare silently dropped by default. Check the output shape. - Passing a NumPy array with name-based columns. Names work only with a DataFrame. For arrays, use integer positions.
- Scaling the target. A pipeline scales
Xonly. ScalingyneedsTransformedTargetRegressor, which is outside this chapter.
Exercise
A colleague runs X_scaled = StandardScaler().fit_transform(X) and then cross_val_score(LogisticRegression(), X_scaled, y, cv=5). What goes wrong, and how do you fix it?
Show answer
The scaler computes its mean and standard deviation from all rows, including the rows that later serve as validation folds, so the validation data leaks into preprocessing and the scores are optimistic. Fix it by passing the raw X to cross_val_score with make_pipeline(StandardScaler(), LogisticRegression()), so the scaler is refit on each training fold.
Exercise
In a ColumnTransformer with remainder="drop" (the default), what happens to a column that is not listed in any transformer, and which setting keeps it unchanged?
Show answer
The column is removed from the output. Setting remainder="passthrough" keeps it unchanged and appends it after the transformed columns.