Sub topic 5
Preprocessing with pipelines: missing values, categories, scaling
This chapter assumes you know pandas, the scikit-learn fit/transform/predict interface, and the idea of cross-validation from the previous chapter. Here you will build one preprocessing object that handles numeric and categorical columns and is safe to use inside validation.
Why preprocessing belongs in a pipeline
Imputing, encoding and scaling all learn something from data: a median, a category list, a mean and standard deviation. If you compute these on the full table before splitting, information from the validation rows leaks into training. Scores then look better than they will in production.
A Pipeline fixes this. Cross-validation refits the whole pipeline on each training fold and only applies it to the matching validation fold.
The three steps
Missing values. SimpleImputer(strategy="median") replaces gaps with the training median. The median is less sensitive to outliers than the mean. For categorical columns, strategy="most_frequent" or a constant such as "missing" works. If the fact that a value is missing carries signal, pass add_indicator=True to get an extra 0/1 column per affected feature.
Categories. OneHotEncoder turns each category into its own 0/1 column. Set handle_unknown="ignore" so a category first seen at prediction time becomes all zeros instead of raising an error. One-hot encoding works poorly for columns with thousands of distinct values, because it creates thousands of columns. Treat those separately.
Scaling. StandardScaler rescales a column to mean 0 and standard deviation 1. Linear models, neural networks and distance-based models need it, because features on different scales distort regularization and gradient steps. Tree-based models split on thresholds, so scaling does not change their results and you can skip it.
A working example
ColumnTransformer applies a different sub-pipeline to each group of columns. The code below fits on a training split only, then transforms a row with an unseen city and a missing income.
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
rng = np.random.default_rng(0)
n = 500
X = pd.DataFrame({
"age": rng.integers(18, 80, n).astype(float),
"income": rng.normal(50000, 15000, n),
"city": rng.choice(["a", "b", "c"], n),
})
X.loc[rng.choice(n, 25, replace=False), "income"] = np.nan
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
X_train, X_test = train_test_split(X, test_size=0.2, random_state=0)
preprocess.fit(X_train)
print(preprocess.transform(X_test).shape)
print(preprocess.get_feature_names_out())
new_row = pd.DataFrame({"age": [30.0], "income": [np.nan], "city": ["d"]})
print(preprocess.transform(new_row))The test set has five columns: two scaled numbers and three city indicators. The new row gets the training median for income and zeros for all city columns.
Common errors
- Fitting on everything. Calling
fit_transformon the full table beforecross_val_scoreleaks statistics. Put the preprocessor inside the pipeline instead. - Inconsistent columns.
ColumnTransformerselects columns by name. A renamed or missing column fails at transform time. By default, columns you did not list are dropped silently. - Version differences.
sparse_outputreplacedsparsein scikit-learn 1.2. On older versions, usesparse=False. - Scaling for trees. It is harmless but adds nothing. Reusing one preprocessor for every candidate is still fine, and it keeps comparisons consistent.
Exercise
You standardize all numeric columns on the full dataset, then run 5-fold cross-validation on a logistic regression. Why is the score unreliable, and how do you fix it?
Show answer
The scaler's mean and standard deviation were computed using rows that later serve as validation data, so validation information leaks into training. Put the scaler in a pipeline with the model, for example with makepipeline or a ColumnTransformer, and pass that pipeline to crossval_score. The scaler is then refitted on each training fold only.