Sub topic 5
Preprocessing with Pipelines: Missing Values, Categories, Scaling
This chapter assumes you know basic pandas and scikit-learn (fit, transform, predict). It also assumes you know why a train/validation split exists. Earlier chapters covered validation and leakage. Here you apply that discipline to the steps that run before the model.
Why preprocessing belongs inside the model
Imputation, encoding, and scaling all learn something from data. An imputer learns a median. A scaler learns a mean and a standard deviation. An encoder learns the list of categories. If you learn those values on the full dataset and then cross-validate, each validation fold has already influenced the preprocessing. The leak is usually small, but it is real, and it grows with rare categories, small datasets, and target-aware encoders.
A scikit-learn Pipeline fixes this. When you pass a pipeline to cross_val_score, each fold calls fit on the training portion only. It then calls transform on the validation portion with the values it learned. The preprocessing is treated as part of the model.
This leaky pattern is the one to avoid:
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
X_num = rng.normal(size=(200, 3))
y = (X_num[:, 0] + rng.normal(size=200) > 0).astype(int)
# Wrong: the scaler sees every row, including future validation rows.
X_leaky = StandardScaler().fit_transform(X_num)
print(cross_val_score(LogisticRegression(), X_leaky, y, cv=5).mean())The scores look fine, which is why the mistake survives. Wrapping the scaler and model in make_pipeline removes the problem at no extra cost.
The building blocks
| Component | What it learns during `fit` | Typical use |
|---|---|---|
| `SimpleImputer` | Median, mean, or most frequent value per column | Fill missing values |
| `StandardScaler` | Mean and standard deviation per column | Put numeric columns on one scale |
| `OneHotEncoder` | The set of categories per column | Turn categories into 0/1 columns |
| `OrdinalEncoder` | A category-to-integer mapping | Tree models, or truly ordered categories |
| `ColumnTransformer` | Which transformer applies to which columns | Different handling for numeric and categorical columns |
| `Pipeline` | Nothing itself; it chains steps in order | Keep all steps and the model fitted together |
Missing values
Check first why values are missing. Three situations come up often:
- Random gaps, such as a sensor dropout. Median imputation is a reasonable default.
- Informative gaps, such as a blank income field because the applicant declined to answer. The fact that the value is missing is itself a signal.
- Structural gaps, such as "spouse's age" for a single person. The value does not exist, so any filled-in number is fiction.
For the second and third cases, keep a flag. SimpleImputer(add_indicator=True) appends a 0/1 column for each column that had missing values in the training data. A linear model can then learn a separate offset for "was missing".
Median is more robust than mean when a column has outliers, such as income. For categorical columns, either use strategy="most_frequent" or strategy="constant", fill_value="missing". The constant option keeps "missing" as its own category, which is often the better choice.
Some models need no imputation. HistGradientBoostingClassifier and HistGradientBoostingRegressor accept NaN directly and learn which branch missing values should take. A random forest also accepts NaN in recent scikit-learn versions. Linear models and neural networks do not accept NaN at all. If you compare model families, remember that imputation then becomes one more variable between them.
Categorical columns
A model cannot do arithmetic on the string "b", so categories must become numbers.
- One-hot encoding creates one 0/1 column per category. It is the safe default for linear models and neural networks, because it does not invent an order.
- Ordinal encoding maps categories to integers. It is appropriate when the order is real (
small < medium < large). Tree models also tolerate it for unordered categories, since they can split the integers into groups. A linear model would wrongly read the integers as a scale.
Set handle_unknown="ignore" on OneHotEncoder. Without it, a category that appears only in a validation fold (or in production) raises an error. With it, that row gets all zeros for that column's indicators.
High-cardinality columns, such as zip code or user ID, need care. One-hot encoding a column with 10,000 values produces 10,000 columns, mostly empty. Options include OneHotEncoder(min_frequency=20), which groups rare values into an "infrequent" bucket, and TargetEncoder (scikit-learn 1.3 and later). Target encoding uses the label, so it leaks easily when done outside a pipeline. Its fit_transform applies internal cross-fitting to reduce this, but only if it runs inside your fold loop.
Scaling
Scaling matters when the model uses distances or gradient-based optimization with a penalty:
| Model family | Needs scaling? | Reason |
|---|---|---|
| Logistic and linear regression with regularization | Yes | The penalty treats all coefficients equally, so feature units change the result |
| k-nearest neighbours, SVMs | Yes | Distances are dominated by large-valued columns |
| Neural networks | Yes | Unscaled inputs slow or destabilize training |
| Decision trees, random forests, gradient boosting | No | Splits depend only on the order of values |
Scaling a tree model does no harm, but it is wasted work and makes feature importances harder to read in original units. StandardScaler is sensitive to outliers. If a column has extreme values, RobustScaler (median and interquartile range) is an alternative. Skewed columns such as income sometimes need a log transform first.
Assembling the pipeline
The structure has two layers. A ColumnTransformer routes columns to the right treatment, and the pipeline attaches a model to the end. The following code builds both, then scores a baseline and a logistic regression on identical folds:
import numpy as np
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.dummy import DummyClassifier
from sklearn.impute import SimpleImputer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
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
y = ((X["age"] > 45) ^ (X["city"] == "a")).astype(int)
preprocess = ColumnTransformer([
("num", make_pipeline(SimpleImputer(strategy="median"), StandardScaler()), ["age", "income"]),
("cat", OneHotEncoder(handle_unknown="ignore", sparse_output=False), ["city"]),
])
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)
baseline = make_pipeline(preprocess, DummyClassifier(strategy="prior"))
logreg = make_pipeline(preprocess, LogisticRegression(max_iter=1000))
for name, model in [("baseline", baseline), ("logreg", logreg)]:
scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc")
print(name, scores.mean().round(3), scores.std().round(3))The sparse_output argument requires scikit-learn 1.2 or later. In older versions it was called sparse.
The target here is an XOR of age and city. A plain logistic regression has no interaction term, so it may score near the baseline. That is a useful reminder that good preprocessing does not make a model family appropriate. The next chapters compare model families on this same setup.
Selecting columns and inspecting results
Hard-coded column lists break when the schema changes. make_column_selector picks columns by dtype instead:
from sklearn.compose import ColumnTransformer, make_column_selector
from sklearn.impute import SimpleImputer
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler
preprocess = ColumnTransformer([
("num",
make_pipeline(SimpleImputer(strategy="median", add_indicator=True), StandardScaler()),
make_column_selector(dtype_include="number")),
("cat",
make_pipeline(
SimpleImputer(strategy="constant", fill_value="missing"),
OneHotEncoder(handle_unknown="ignore", sparse_output=False),
),
make_column_selector(dtype_exclude="number")),
])After fitting, preprocess.get_feature_names_out() returns the output column names, such as num__age and cat__city_a. Print them at least once. It is the quickest way to confirm that a column was not dropped, duplicated, or encoded as you did not intend. By default, columns not listed in a ColumnTransformer are dropped silently (remainder="drop"). Use remainder="passthrough" if you want them kept.
Common errors
- Fitting on everything first. Scaling or imputing the full dataset before
cross_val_scoreleaks fold information. Put every learned step inside the pipeline. - Forgetting
handle_unknown. The pipeline works in development, then fails on a new category in production. - Scaling one-hot columns without meaning to. Scaling 0/1 indicators is harmless for most models but makes them harder to interpret. Route them around the scaler, as the example above does.
- Treating integer codes as numbers. A column like
store_idholds numbers but is categorical. Cast it to a string or category type so the selector sends it to the encoder. - Dropping rows with missing values. This shrinks the data and biases it if the gaps are informative. If you drop rows for the training set, you still need a plan for production rows that have gaps.
- Mismatched preprocessing across model comparisons. If the linear model gets scaling and imputation but the tree model gets raw data, the score difference reflects more than the model. Use one shared
ColumnTransformerwhere it is valid, and document each deviation.
Exercise
A teammate scales the whole dataset with StandardScaler, then runs 5-fold cross-validation on a random forest and reports an AUC. Name two separate problems with this workflow.
Show answer
First, the scaler was fitted on all rows, so each validation fold influenced the mean and standard deviation used on it. That is leakage, and the fix is to put the scaler inside a pipeline so it is fitted per fold. Second, a random forest splits on the order of values, so scaling does nothing for it. The step adds a leak risk and no benefit, and it should be removed for tree models.
Exercise
A categorical column "plan" has values "free", "pro", and "team" in training. In production a row arrives with "enterprise". What happens with OneHotEncoder(handle_unknown="ignore"), and what happens without that argument?
Show answer
With "ignore", the row gets zeros in all three plan indicator columns, and prediction continues. Without it, the encoder raises a ValueError when transforming that row.