Sub topic 8
Pipelines: one path for training and prediction
This chapter assumes you can write basic Python, use pandas DataFrames, and have seen a scikit-learn estimator with fit and predict. It also assumes you know why data leakage inflates scores, which the previous chapter covered.
Why a pipeline
A pipeline chains preprocessing steps and a model into one object. You call fit once and predict once. Every step learns its parameters (a mean, a category list, a median) from the training rows only. At prediction time the same fitted steps are reused unchanged.
Hand-written preprocessing breaks in two common ways. You may fit a scaler on all the data before splitting, which leaks test information. Or you may transform new rows differently from training rows, for example with a different category order. A pipeline prevents both.
Different columns, different steps
Real tables mix numeric and categorical columns. A ColumnTransformer applies a separate transformer to each group of columns and joins the results. Nesting it inside a Pipeline gives one object for the whole workflow.
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
def build_model(numeric_cols, categorical_cols):
numeric = Pipeline([
("impute", SimpleImputer(strategy="median")),
("scale", StandardScaler()),
])
categorical = Pipeline([
("impute", SimpleImputer(strategy="most_frequent")),
("onehot", OneHotEncoder(handle_unknown="ignore")),
])
prep = ColumnTransformer([
("num", numeric, numeric_cols),
("cat", categorical, categorical_cols),
])
return Pipeline([
("prep", prep),
("clf", LogisticRegression(max_iter=1000)),
])
# Usage, given a DataFrame split into X_train and y_train:
# model = build_model(["age", "income"], ["city", "plan"])
# search = GridSearchCV(model, {"clf__C": [0.1, 1, 10]}, cv=5, scoring="f1")
# search.fit(X_train, y_train)
# print(search.best_params_, search.best_score_)Note the details:
- Numeric columns get a median fill, then scaling. Categorical columns get a most-frequent fill, then one-hot encoding.
handle_unknown="ignore"means a category never seen in training becomes all zeros instead of raising an error at prediction time.- Step names become parameter prefixes.
clf__Cmeans theCparameter of the step namedclf.
Pipelines and cross-validation
Pass the whole pipeline to cross_val_score or GridSearchCV. On each fold, scikit-learn refits every step on that fold's training part and scores on the held-out part. The held-out fold never influences the imputer, scaler or encoder. If you preprocess first and cross-validate only the model, the held-out folds have already shaped the preprocessing, and the scores are optimistic.
Common errors
- Fitting a step outside the pipeline. Calling
fit_transformon the full dataset before splitting reintroduces leakage. - Wrong column names.
ColumnTransformerselects by name. A misspelled or missing column fails at fit time. At prediction time, new data must have the same columns. - Dropping unlisted columns. By default, columns not named in any transformer are dropped. Set
remainder="passthrough"only if you want them kept as-is. - Saving only the model. Persist the entire fitted pipeline, not just the final estimator. Otherwise the serving code must rebuild the preprocessing by hand.
Exercise
A teammate scales the full dataset with StandardScaler, then runs crossvalscore on a LogisticRegression with cv=5. What is wrong, and how do you fix it?
Show answer
The scaler's mean and variance were computed using rows that later serve as validation folds, so each fold's score is slightly optimistic. Put the scaler and the classifier in one Pipeline and pass that pipeline to crossvalscore. The scaler is then refit on the training part of each fold.
Exercise
A pipeline trained with OneHotEncoder() raises an error when a new row has a city not seen in training. Which setting avoids the error, and what does the encoder output for that row?
Show answer
Set handle_unknown="ignore". The encoded city columns for that row are all zeros.