Skip to content

Lesson 5 of 9 · 28m

Preprocessing Pipelines That Do Not Leak

Compose imputers, encoders, scalers, and models into one fitted object so validation and deployment apply exactly the same transformations.

The most expensive preprocessing bug is subtle: the validation score is excellent, the model ships, and production performance collapses. Nothing mystical happened. The experiment let preprocessing learn from evaluation data, or deployment applied slightly different transformations. A pipeline is not convenience plumbing. It is the boundary that keeps learning inside training.

Build transformations as a graph

Numeric and categorical features usually need different treatment:

from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.linear_model import LogisticRegression

numeric = ['account_age_days', 'first_week_events']
categorical = ['plan_code', 'referral_source', 'country']

preprocess = ColumnTransformer([
    ('num', Pipeline([
        ('impute', SimpleImputer(strategy='median')),
        ('scale', StandardScaler()),
    ]), numeric),
    ('cat', Pipeline([
        ('impute', SimpleImputer(strategy='most_frequent')),
        ('onehot', OneHotEncoder(handle_unknown='ignore')),
    ]), categorical),
])

Now bind it to the model:

clf = Pipeline([
    ('prep', preprocess),
    ('model', LogisticRegression(max_iter=1000)),
])
clf.fit(X_train, y_train)

The object you ship is clf, not a model plus tribal memory.

Why pipelines prevent leakage

Cross-validation calls fit on training folds only. If preprocessing is inside the pipeline, imputation medians, scaling means, category vocabularies, and feature selection are refit inside each fold. If preprocessing happens before cross-validation, every fold has already seen the full dataset. The validation score is contaminated no matter how honest the split looked.

Unknown categories are normal production traffic

Training never includes every future category. handle_unknown='ignore' maps unseen categories to all-zero one-hot features rather than crashing:

encoder = OneHotEncoder(handle_unknown='ignore', sparse_output=True)

That is usually correct for high-cardinality categorical input, but it can hide schema drift. Log unknown-category rates in production instead of treating silent robustness as correctness.

Feature selection belongs inside the pipeline too

If you select features using target correlation or univariate tests, that selector must live in the pipeline:

from sklearn.feature_selection import SelectKBest, mutual_info_classif

clf = Pipeline([
    ('prep', preprocess),
    ('select', SelectKBest(mutual_info_classif, k=100)),
    ('model', LogisticRegression(max_iter=1000)),
])

Otherwise validation rows influenced which features exist. The leakage is still real even though no row passed directly into training.

Field notes

  • sparse_output=True replaced the old sparse argument in modern scikit-learn; pin versions before copying examples.
  • Scaling is unnecessary for tree ensembles but often critical for linear and distance-based models.
  • Imputing before splitting is leakage even when the statistic looks harmless.
  • ColumnTransformer output order is transformer order, not original dataframe order.
  • Test the pipeline on raw dataframe-shaped input because that is what production should send.

Was this lesson helpful?

Sign in to rate