Sub topic 7
Scaling safely with Pipeline and ColumnTransformer
This chapter assumes you can fit a scikit-learn estimator and call fit, transform and predict. It also assumes you know why a scaler must learn its statistics from training data only. The earlier chapters on leakage cover that rule. Here you will see how scikit-learn enforces it for you.
Why manual scaling breaks down
The correct manual workflow has three steps. Fit the scaler on the training split, transform both splits with it, then fit the model. That is easy to get right for one split. It gets fragile once you add cross-validation, hyperparameter search, or a mix of numeric and non-numeric columns.
Typical mistakes:
- Scaling the whole dataset first, then running
cross_val_score. Every validation fold has already influenced the mean and standard deviation (or min and max) used to scale the training folds. - Refitting the scaler on the test set "because the test data has a different range". The model then sees features on a different scale than the one it was trained on.
- Forgetting to apply the scaler at prediction time, or applying a different one.
- Scaling every column, including one-hot columns or IDs, because one call to
fit_transformwas easier.
A Pipeline removes the first three problems. A ColumnTransformer removes the fourth.
Pipeline: one object, one fit
A Pipeline chains transformers and ends with an estimator. Calling fit on the pipeline does this:
- Calls
fit_transformon each transformer in order, passing the output of each step to the next. - Calls
fiton the final estimator.
Calling predict or transform on a fitted pipeline calls only transform on each earlier step, so the stored training statistics are reused.
The validation fold never reaches fit on the scaler. That is the whole safety guarantee.
The simplest safe pipeline
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())cross_val_score clones the pipeline for each fold. Each clone fits its own scaler on that fold's training rows. You can confirm this by keeping the fitted estimators from each fold:
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_validate
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))
result = cross_validate(model, X, y, cv=5, return_estimator=True)
for fold, est in enumerate(result["estimator"]):
scaler = est.named_steps["standardscaler"]
print(fold, scaler.mean_[0])The printed means differ slightly from fold to fold. If you had scaled the full dataset beforehand, there would be only one mean, shared by all folds.
Pipeline versus `make_pipeline`
| Constructor | Step names | Use when |
|---|---|---|
| `make_pipeline(StandardScaler(), LogisticRegression())` | Generated from class names in lowercase: `standardscaler`, `logisticregression` | Quick work and short scripts |
| `Pipeline([("scale", StandardScaler()), ("clf", LogisticRegression())])` | Names you choose | Hyperparameter search, logging, and code others will read |
Step names matter because you address parameters as step__parameter.
Tuning through a pipeline
Hyperparameter search also refits the scaler on each training fold, as long as the scaler is inside the pipeline you pass to the search object.
from sklearn.datasets import load_breast_cancer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler, StandardScaler
X, y = load_breast_cancer(return_X_y=True)
pipe = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=2000)),
])
param_grid = {
"scale": [StandardScaler(), MinMaxScaler()],
"clf__C": [0.1, 1.0, 10.0],
}
search = GridSearchCV(pipe, param_grid, cv=5)
search.fit(X, y)
print(search.best_params_)
print(search.best_score_)Two things to notice. First, you can replace an entire step by listing step objects under its name, so the scaler choice becomes a tunable setting. Second, the double underscore in clf__C routes the value to the C parameter of the step named clf.
ColumnTransformer: scale only what should be scaled
Real tables mix numeric columns, binary flags and categories. Scaling a one-hot column or a binary flag usually adds nothing and makes the values harder to read. A ColumnTransformer applies a different transformer to each group of columns and joins the results side by side.
Each entry is a tuple of (name, transformer, columns). Columns can be positions, names (when the input is a DataFrame), boolean masks, or a selector function.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import MinMaxScaler, StandardScaler
df = pd.DataFrame({
"age": [25, 32, 47, 51, 62, 23, 36, 44, 58, 29, 41, 53],
"income": [32000, 48000, 85000, 91000, 120000, 28000,
52000, 77000, 99000, 39000, 66000, 88000],
"tenure_months": [3, 14, 60, 72, 120, 1, 20, 48, 96, 8, 36, 80],
"is_member": [0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1],
"churned": [1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0],
})
X = df.drop(columns="churned")
y = df["churned"]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, stratify=y, random_state=0
)
preprocess = ColumnTransformer(
[
("std", StandardScaler(), ["age", "income"]),
("mm", MinMaxScaler(), ["tenure_months"]),
],
remainder="passthrough", # is_member goes through unchanged
)
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression()),
])
model.fit(X_train, y_train)
print(model.score(X_test, y_test))
fitted_std = model.named_steps["prep"].named_transformers_["std"]
print(fitted_std.mean_)
print(model.named_steps["prep"].get_feature_names_out())The output columns come in the order of the entries, with remainder columns last. get_feature_names_out returns std__age, std__income, mm__tenure_months and remainder__is_member. The prefix is the entry name, so choose names you will recognize later.
The `remainder` setting
| Value | Effect on columns you did not list |
|---|---|
| `"drop"` (default) | Removed from the output |
| `"passthrough"` | Kept as they are, appended after the transformed columns |
| A transformer object | Transformed with that object |
The default is the usual source of surprises. If you list only two columns and leave remainder alone, the output contains only those two columns, and the model silently trains on fewer features.
Selecting columns by type
Hard-coded lists go stale when columns change. make_column_selector picks columns by dtype or name pattern when fit is called.
import pandas as pd
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.preprocessing import StandardScaler
df = pd.DataFrame({
"height_cm": [160.0, 172.0, 181.0, 168.0],
"weight_kg": [55.0, 70.0, 88.0, 64.0],
"city": ["Oslo", "Lima", "Oslo", "Pune"],
})
preprocess = ColumnTransformer(
[("num", StandardScaler(), make_column_selector(dtype_include="number"))],
remainder="passthrough",
)
out = preprocess.fit_transform(df)
print(preprocess.get_feature_names_out())
print(out)The city column is not numeric, so the scaler skips it and passthrough keeps it. The output array has object dtype because it mixes floats and strings. In a real model you would send city to an encoder instead.
Keeping DataFrames
By default a ColumnTransformer returns a NumPy array and drops the column names. Call set_output(transform="pandas") to get a DataFrame back, which makes inspection much easier.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, MinMaxScaler
df = pd.DataFrame({
"a": [1.0, 2.0, 3.0],
"b": [10.0, 20.0, 40.0],
"flag": [0, 1, 1],
})
preprocess = ColumnTransformer(
[("std", StandardScaler(), ["a"]), ("mm", MinMaxScaler(), ["b"])],
remainder="passthrough",
verbose_feature_names_out=False,
).set_output(transform="pandas")
print(preprocess.fit_transform(df))With verbose_feature_names_out=False the original column names are kept, as long as they are unique across the transformers.
Common errors and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| Validation score is higher than the held-out test score | Data scaled before cross-validation | Move the scaler into the pipeline |
| `ValueError: A given column is not a column of the dataframe` at predict time | Named columns used, but new data lacks them or was passed as an array | Pass a DataFrame with the same column names |
| Model has fewer inputs than expected | `remainder="drop"` discarded unlisted columns | Set `remainder="passthrough"` or list every column |
| Coefficients cannot be matched to features | Names lost after the transformer | Use `get_feature_names_out()` or `set_output(transform="pandas")` |
| `GridSearchCV` raises `Invalid parameter` | Wrong step name in the `step__param` key | Check `pipe.get_params().keys()` |
| Scaled binary columns look odd, such as `-1.2` and `0.8` | A flag was standardized | Route flags through `passthrough` |
What a pipeline does not cover
- The target. A pipeline scales features only. If you scale a regression target, wrap the model in
TransformedTargetRegressor, which appliesinverse_transformto predictions for you. - Leakage outside the pipeline. Anything you compute from the full dataset before splitting, such as imputation values or filtering rules, can leak in the same way. Put those steps in the pipeline too.
- Tree models. Scaling inside a pipeline with a random forest does no harm, but it costs time and changes nothing about the splits.
- Caching. Pass
memory="cache_dir"toPipelineto cache fitted transformers during grid search. This helps when scaling is slow, which is rare for scalers.
Exercises
Exercise
A colleague runs X_scaled = StandardScaler().fit_transform(X) and then cross_val_score(LogisticRegression(), X_scaled, y, cv=5). Explain what is wrong and rewrite the call so it is safe.
Show answer
The scaler saw all rows, including those that later land in validation folds. The mean and standard deviation used on each training fold therefore contain information from its validation fold, so the scores can be optimistic. Rewrite it with the scaler inside a pipeline: cross_val_score(make_pipeline(StandardScaler(), LogisticRegression()), X, y, cv=5). Each fold then fits its own scaler on the training rows only.
Exercise
A DataFrame has numeric columns x1 and x2, a binary column flag, and a numeric column target_count that you want left raw. You write ColumnTransformer([("std", StandardScaler(), ["x1", "x2"])]) and feed the result to a model. How many features does the model receive, and how do you keep flag and target_count unchanged?
Show answer
The model receives 2 features, because the default remainder="drop" discards flag and target_count. Add remainder="passthrough" so both are appended unchanged after the scaled columns. The model then receives 4 features, which you can confirm with get_feature_names_out().
Exercise
You want a grid search that compares StandardScaler and MinMaxScaler and tries C values 0.1 and 1.0 for a logistic regression. The pipeline steps are named scale and clf. Write the param_grid.
Show answer
{"scale": [StandardScaler(), MinMaxScaler()], "clf__C": [0.1, 1.0]}. The key scale replaces the whole step with each listed scaler, and clf__C sets the C parameter of the step named clf.