Sub topic 8
Pipelines: one path for training and prediction
This chapter assumes you can fit and predict with a scikit-learn estimator, you know what a pandas DataFrame is, and you have seen train/test splits and data leakage. By the end you will be able to build a pipeline that applies the same preprocessing at training time and at prediction time, and that is safe to use inside cross-validation.
The problem pipelines solve
A model rarely sees raw columns. Before the model, you impute missing values, scale numbers and encode categories. Each of those steps learns something from data. A scaler learns a mean and a standard deviation. An imputer learns a median. A one-hot encoder learns which categories exist.
Those learned values must come from the training rows only. They must then be reused unchanged on validation rows, test rows and new rows at prediction time. Doing this by hand is error-prone. You have to remember to call fit on training data, transform on everything else, and to repeat the exact same sequence in production.
A pipeline packages the steps and the model into one object. Calling fit on the pipeline fits each step in order on the training data. Calling predict runs the same transformations with the learned values and then asks the model for an answer.
Why not scale first and split later
The most common mistake is fitting a transformer on the full dataset before splitting. The test rows then influence the mean and standard deviation. The effect is often small, but it is still leakage, and with stronger transformations such as target encoding or feature selection it can be large.
The second code example in the plan contrasts the two approaches. The leaky version is:
from sklearn.preprocessing import StandardScaler
X_scaled_all = StandardScaler().fit_transform(X) # sees test rowsThe correct manual version fits on training rows only:
scaler = StandardScaler().fit(X_tr)
clf = LogisticRegression(max_iter=1000).fit(scaler.transform(X_tr), y_tr)This works, but you must carry scaler and clf around together and remember the order. A pipeline replaces the two objects with one.
A basic pipeline
A Pipeline takes a list of (name, estimator) pairs. Every step except the last must be a transformer, meaning it has fit and transform. The last step can be any estimator.
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
X, y = load_breast_cancer(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=42
)
model = Pipeline([
("scale", StandardScaler()),
("clf", LogisticRegression(max_iter=1000)),
])
scores = cross_val_score(model, X_train, y_train, cv=5, scoring="f1")
print("CV F1:", scores.mean())
model.fit(X_train, y_train)
print(classification_report(y_test, model.predict(X_test)))
new_row = X_test.iloc[[0]]
print(model.predict(new_row), model.predict_proba(new_row))Four things happen here that you did not have to code.
cross_val_scoreclones the pipeline for each fold and refits the scaler on that fold's training part. The held-out part of the fold never influences the scaler.model.fitfits the scaler onX_train, transformsX_train, and fits the classifier on the result.model.predicttransformsX_testusing the scaler's stored mean and standard deviation, then predicts.new_row = X_test.iloc[[0]]uses double brackets so the row stays a one-row DataFrame with its column names. A single bracket would return a Series, which is the wrong shape.
Different columns, different treatment
Real tables mix numeric and categorical columns, and each type needs its own steps. ColumnTransformer applies a different transformer to each group of columns and joins the outputs side by side.
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_)The structure is nested. The outer pipeline has a preprocessing step and a classifier. The preprocessing step is a ColumnTransformer with two branches, and each branch is itself a small pipeline.
Points worth noting:
handle_unknown="ignore"makes the encoder output all zeros for a category it never saw in training. Without it, a new city at prediction time raises an error.- Columns are selected by name, so the input DataFrame must contain those names at prediction time. Extra columns are dropped by default. Missing columns raise an error.
- Imputation comes before scaling, because the scaler should compute statistics on complete values.
Tuning through a pipeline
Parameters of nested steps are addressed as step__parameter. In the usage above, clf__C sets the C parameter of the step named clf. To reach deeper you chain names, for example prep__num__impute__strategy.
The important property is what GridSearchCV does with a pipeline. For every parameter combination and every fold, it clones the whole pipeline and refits all steps on that fold's training rows. The imputer medians, scaler statistics and encoder categories are all relearned each time. Nothing from the validation part of the fold leaks into preprocessing.
If you instead preprocessed the training set once and passed the result to GridSearchCV, every validation fold would have influenced the preprocessing. That is a quiet source of optimistic scores.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ValueError: Found unknown categories` | Encoder saw a new category at prediction time | Use `handle_unknown="ignore"` |
| `KeyError` for a column name | Prediction input is missing a column the pipeline expects | Validate columns before calling `predict` |
| `Invalid parameter` in a grid | Wrong step name or missing double underscore | Run `model.get_params().keys()` to list valid names |
| Scores much higher in your notebook than in production | Preprocessing done outside the pipeline | Move every learned step inside the pipeline |
| Shape error on a single row | Passed a Series or 1-D array | Pass a one-row DataFrame, such as `X.iloc[[0]]` |
Two further gotchas:
- Steps that change the number of rows, such as dropping outliers or resampling, do not fit in a standard
Pipeline. Do row filtering before the split, using only rules that do not depend on the target. Resampling needs theimblearnpipeline, which applies it to training folds only. - Stateless operations, such as taking a log of a column, can go in the pipeline with
FunctionTransformer. This keeps the logic bundled with the model, even though there is nothing to learn.
Saving and reusing the pipeline
Because the pipeline holds every learned value, saving the one object saves the whole path from raw columns to prediction. With joblib, joblib.dump(model, "model.joblib") writes it and joblib.load("model.joblib") restores it. Load it only in an environment with the same scikit-learn version, and only from files you trust, because loading uses pickle.
Inspecting a fitted pipeline
You can look inside a fitted pipeline with model.named_steps["scale"].mean_ to see the learned means. For a ColumnTransformer, get_feature_names_out() gives the output column names, which helps when you want to read the coefficients of a linear model.
Exercise
You fit a StandardScaler on the full dataset, split into train and test, then run GridSearchCV on a LogisticRegression using the scaled training rows. Name two separate places where information from held-out data reaches the preprocessing, and describe the fix.
Show answer
First, the scaler saw the test rows before the split, so test statistics shaped the scaling. Second, inside GridSearchCV, each validation fold was scaled with statistics that included that fold's own rows. The fix is to split first, put the scaler and the classifier in one Pipeline, and pass that pipeline to GridSearchCV so each fold refits the scaler on its training part only.
Exercise
Your pipeline works on training data, but at prediction time a new customer has a city value that never appeared in training and the call fails. What setting prevents this, and what does the encoder output for that row?
Show answer
Set handle_unknown="ignore" on OneHotEncoder. The encoder then outputs zeros in every column for that feature, so the row is still valid input and the model relies on the other features.