Sub topic 11
Target encoding and why it needs care
This chapter assumes you know one-hot encoding, scikit-learn pipelines, and cross-validation. It also assumes you understand data leakage from the earlier chapter.
The problem it solves
One-hot encoding makes one column per category. A zip_code column with 5,000 values gives 5,000 columns, most of them nearly empty. Target encoding replaces each category with a single number: a statistic of the target for rows in that category. For a binary target, that statistic is the mean, which is the observed rate of positives.
If customers from zip code 94110 churned 30% of the time in the training data, every row with that zip code gets the value 0.30. The result is one dense numeric column, however many categories there are.
Why naive target encoding leaks
The encoded value is computed from y. If you compute it on the full training set and then train on those rows, each row's own label contributes to its feature. For a rare category the effect is severe. A category with one row gets an encoding equal to that row's label, so the model sees the answer in the feature.
The training score then looks excellent, and the model fails on new data. This is leakage through the encoder itself.
Two safeguards
Smoothing pulls the estimate for rare categories toward the global mean. With n rows in a category, a category mean m, a global mean g, and a smoothing strength s, the encoding is (n * m + s * g) / (n + s). A category with 2 rows barely moves from g. A category with 2,000 rows stays close to m.
Cross-fitting computes the encoding for each training row from folds that exclude that row. This is the out-of-fold path in the diagram.
Using scikit-learn's TargetEncoder
Since scikit-learn 1.3, TargetEncoder does both. Its fit_transform uses internal cross-fitting with cv=5 by default, and smooth="auto" sets the smoothing from the data.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import TargetEncoder
X = pd.DataFrame({
"zip": ["a", "a", "b", "b", "b", "c", "c", "d"] * 25,
"age": list(range(200)),
})
y = pd.Series([0, 1, 0, 0, 1, 1, 1, 0] * 25)
prep = ColumnTransformer(
[("zip", TargetEncoder(smooth="auto", cv=5, random_state=0), ["zip"])],
remainder="passthrough",
)
model = Pipeline([("prep", prep), ("clf", LogisticRegression(max_iter=1000))])
scores = cross_val_score(model, X, y, cv=5, scoring="roc_auc")
print(scores.mean())Because the encoder sits inside the pipeline, cross_val_score refits it on each training fold. The validation fold's labels never reach it.
Common errors
- Encoding before splitting the data into train and test sets.
- Using
fit().transform()on training data instead offit_transform(). - Skipping smoothing on categories with few rows.
- Applying it to low-cardinality columns where one-hot encoding is simpler and safe.
Unseen categories at prediction time receive the global target mean, so a new zip code does not cause an error.
Exercise
A category appears once in the training data, with label 1. Without smoothing or cross-fitting, what encoding does that row get, and why is that a problem? How does smoothing change it?
Show answer
It gets 1.0, which is exactly its own label, so the feature reveals the target and the model can memorize it. With smoothing, the value becomes (1 1 + s g) / (1 + s), which moves toward the global mean g. Cross-fitting also removes the row's own label from its encoding.