Sub topic 12
Putting it together with Pipeline and ColumnTransformer
This chapter assumes you know basic pandas, the scikit-learn fit and predict workflow, and why data leakage matters. Earlier chapters covered imputation, scaling and encoding one step at a time. Here you combine them into one object that you can fit, score and ship.
Why a single object
Running each step by hand invites mistakes. You might fit a scaler on the full dataset before splitting, or forget to apply the same encoder to new data. A Pipeline chains steps so that fit runs each one on the training data only. predict then reuses the fitted state of every step.
A ColumnTransformer solves a second problem. Numeric and categorical columns need different treatment, so it applies a separate transformer to each group of columns and joins the results side by side.
Building the pipeline
Each branch is itself a small Pipeline. The outer ColumnTransformer maps each branch to a list of column names.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
numeric_cols = ["age", "income"]
categorical_cols = ["city"]
preprocess = ColumnTransformer([
("num", Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
]), numeric_cols),
("cat", Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
]), categorical_cols),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])Calling model.fit(X_train, y_train) learns the medians, means, scales, categories and coefficients from the training rows. Calling model.predict(X_new) applies those learned values without refitting anything.
The setting handle_unknown="ignore" matters in production. A city that never appeared in training would otherwise raise an error. With this setting it becomes a row of zeros in the one-hot columns.
Scoring without leakage
Pass the whole pipeline to cross-validation, not pre-transformed data. Each fold then refits every imputer, scaler and encoder on its own training portion.
from sklearn.model_selection import cross_val_score
# X is a DataFrame with the columns above, y is the target
scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
print(scores.mean(), scores.std())If you instead scaled all of X first, each validation fold would have influenced the scaler's mean and variance. The score would look better than real performance.
Common errors
| Symptom | Likely cause |
|---|---|
| `ValueError: A given column is not a column of the DataFrame` | A name in `numeric_cols` or `categorical_cols` does not match the DataFrame. |
| Extra columns vanish from the output | `ColumnTransformer` drops unlisted columns by default (`remainder="drop"`). Use `remainder="passthrough"` to keep them. |
| Error on unseen category at predict time | `OneHotEncoder` was left at its default for `handle_unknown`. |
| Preprocessing fitted outside the pipeline | The transformer was fit on all data before the split. |
Exercise
You fit a StandardScaler on the full dataset, then call crossvalscore on a logistic regression using the scaled data. Why is the score unreliable, and how do you fix it?
Show answer
The scaler's mean and variance were computed using rows that later land in validation folds, so information leaks from validation into training and inflates the score. Put the scaler inside a Pipeline (or ColumnTransformer within a Pipeline) and pass that pipeline to crossvalscore, so the scaler is refit on each training fold only.