Sub topic 12
Putting it together with Pipeline and ColumnTransformer
This chapter assumes you know the scikit-learn fit, transform and predict workflow. It also assumes you have met imputation, scaling and one-hot encoding from earlier chapters. Here you will combine those pieces into one object. That object can be trained, cross-validated, saved and served without leaking information from validation data.
Why one object instead of loose steps
A common first attempt looks like this: impute the whole DataFrame, scale it, encode it, split it, and then fit a model. Each step works on its own. The order is the problem. The imputer's median and the scaler's mean were computed from rows that later land in the test set, so the test set has already influenced training. This is data leakage.
A Pipeline fixes this by chaining steps into one estimator. Calling fit on the pipeline fits each step, in order, on the data it is given. Calling predict or transform reuses the fitted values and never refits them. When you hand the pipeline to a cross-validation function, the whole chain is refitted on each training fold.
A second benefit is that you ship one artifact. The same object does the preprocessing in training and in serving, which leaves less room for the two to drift apart.
Pipeline mechanics
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.
pipe.fit(X, y)callsfit_transformon each transformer and passes the output to the next step. It then callsfiton the final estimator.pipe.predict(X)callstransformon each transformer andpredicton the final estimator.- Names must be unique and must not contain double underscores, because
__is used to address nested parameters. pipe.named_steps["clf"]orpipe["clf"]returns a step.pipe[:-1]returns a pipeline of everything except the final step.
make_pipeline builds the same object and generates names from the class names. It is shorter, but explicit names are easier to read in logs and in hyperparameter grids.
ColumnTransformer: different treatment per column
Real tables mix types. Numeric columns need imputation and scaling. Categorical columns need imputation and encoding. A ColumnTransformer applies a different transformer to each group of columns and concatenates the results horizontally.
Each entry is a tuple of (name, transformer, columns). The columns value can be a list of names, a list of integer positions, a boolean mask, or a selector such as make_column_selector(dtype_include="number").
The example below is the core pattern of this chapter. Each column group gets its own small pipeline, and the preprocessor is the first step of an outer pipeline that ends in a model.
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)),
])Two details matter here. First, handle_unknown="ignore" makes the encoder output all zeros for a category it did not see during training, instead of raising an error at prediction time. Second, the median and the most frequent value are learned only from the rows passed to fit.
The diagram shows the data flow through this model.
Evaluating the whole pipeline
Pass the pipeline, not preprocessed arrays, to the cross-validation function. Each fold then refits the imputers, scaler and encoder on its own training rows only.
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 ran preprocess.fit_transform(X) once and cross-validated only the classifier, the scaler would have seen every fold's validation rows. The score would be slightly optimistic. With target encoding or feature selection the inflation can be large.
Common errors and edge cases
Dropped columns
By default, remainder="drop". Any column not named in a transformer disappears silently. If you add a new column to the data and forget to list it, the model will never see it. Use remainder="passthrough" to keep unlisted columns unchanged, or set up the transformer so every column is accounted for. Checking preprocess.get_feature_names_out() after fitting is a quick way to confirm what reached the model.
Column order and names
When you fit on a DataFrame, ColumnTransformer selects columns by name, so column order in later inputs does not matter. When you fit on a NumPy array, selection is by position and a reordered array gives wrong results with no error. Prefer DataFrames at both fit and predict time. A missing column raises an error, which is what you want.
Sparse versus dense output
OneHotEncoder returns a sparse matrix by default. ColumnTransformer decides whether the combined output is sparse by comparing the density of its parts against sparse_threshold (default 0.3). Some estimators need dense input and will fail on sparse data. Either choose a model that accepts sparse input, set sparse_threshold=0 to force dense output, or set sparse_output=False on the encoder. With many categories, dense output can use a lot of memory.
Unseen categories and missing values in categories
handle_unknown="ignore" covers unseen categories. A missing value in a categorical column is a separate case. OneHotEncoder can treat NaN as its own category, but imputing first with most_frequent or a constant such as "missing" makes the behavior explicit.
Steps that need the target
Plain transformers ignore y. A supervised step such as SelectFromModel or a target encoder receives y through pipe.fit(X, y) and uses it only on the training rows. This is why these steps belong inside the pipeline.
Adding custom steps
Not every feature is a built-in transformer. FunctionTransformer wraps a stateless function so it can sit in a pipeline. The example below applies a log transform, then adds squared terms and pairwise products.
import numpy as np
from sklearn.preprocessing import FunctionTransformer, PolynomialFeatures
from sklearn.pipeline import make_pipeline
log_then_poly = make_pipeline(
FunctionTransformer(np.log1p, feature_names_out="one-to-one"),
PolynomialFeatures(degree=2, interaction_only=False, include_bias=False),
)
X_new = log_then_poly.fit_transform([[10.0, 200.0], [20.0, 5000.0]])feature_names_out="one-to-one" tells scikit-learn that the output columns match the input columns, so feature names still propagate. Without it, get_feature_names_out() fails on the pipeline. A function that learns something from the data, such as a column mean, should be a class with fit and transform (subclass BaseEstimator and TransformerMixin), not a plain function.
Putting selection inside the pipeline
Feature selection uses the target, so it can leak just as target encoding can. Placing it in the pipeline repeats the selection on every training fold.
from sklearn.feature_selection import SelectFromModel
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
selector_model = Pipeline([
("prep", preprocess),
("select", SelectFromModel(RandomForestClassifier(n_estimators=200, random_state=0))),
("clf", LogisticRegression(max_iter=1000)),
])Tuning and inspecting nested parameters
Because steps are named, you can reach any parameter with a double-underscore path. This lets a grid search tune preprocessing and the model together.
| Path | Meaning |
|---|---|
| `clf__C` | Regularization strength of the final model |
| `prep__num__impute__strategy` | Imputation strategy for numeric columns |
| `prep__cat__onehot__min_frequency` | Minimum count for a category to get its own column |
Searching over prep__num__impute__strategy with GridSearchCV refits the whole chain for every candidate and fold, so tuning choices are made without leakage. The cost is that every combination reruns preprocessing. The memory argument of Pipeline caches fitted transformers on disk and can save time when only late steps change.
Saving the fitted pipeline
To keep training and serving consistent, save the fitted pipeline as one file, for example with joblib.dump(model, "model.joblib"). Load it in the serving code and call predict on raw rows. Do not re-implement the preprocessing by hand there. Record the scikit-learn version too, since pickled objects are not guaranteed to load across versions. Only load files you created yourself, because unpickling untrusted data can run arbitrary code.
Exercise
You standardize the whole DataFrame with StandardScaler, split it into train and test sets, and report a test score. A colleague says the score is leaky. Which part of the workflow causes the leak, and how does a Pipeline fix it?
Show answer
The scaler computed its mean and standard deviation from all rows, including those that later became the test set, so the test data influenced the training transformation. Put the scaler and the model in one Pipeline, split first, and call fit on the training rows only. The scaler then learns its statistics from training data, and the test rows are only transformed with those values.
Exercise
After adding a new column "tenure" to your data, model accuracy does not change at all. Your ColumnTransformer lists only the original columns. What is the most likely cause, and what are two ways to address it?
Show answer
The default remainder="drop" silently discards columns that are not listed, so the model never receives "tenure". Add "tenure" to a transformer's column list, or set remainder="passthrough" to keep unlisted columns. Checking getfeaturenames_out() after fitting confirms which columns reached the model.