Sub topic 11
Target encoding and why it needs care
This chapter assumes you know one-hot and ordinal encoding from the previous chapter, the leakage rule from earlier in the tutorial, and the scikit-learn fit/transform workflow. It covers target encoding for categorical columns with many distinct values, how it leaks the label, and how to use it safely.
The problem it solves
One-hot encoding creates one column per category. A zip_code column with 5,000 values becomes 5,000 sparse columns. Linear models become slow and unstable, and tree models split poorly on sparse indicators. Ordinal encoding avoids the width but invents an order that does not exist.
Target encoding replaces each category with a number computed from the target. For a binary target, that number is usually the mean of y for rows in that category. A city where 30% of past customers churned becomes 0.30. One column carries the signal, however many categories there are.
| Encoder | Output width | Uses the target | Leakage risk | Typical use |
|---|---|---|---|---|
| One-hot | One column per category | No | None | Low cardinality |
| Ordinal | One column | No | None | Ordered categories, tree models |
| Target | One column (per class) | Yes | High if done naively | High cardinality |
Why the naive version leaks
If you compute each category's mean over the whole training set and then train on the encoded column, each row's own label is part of its feature. A category with one row gets the encoding 0.0 or 1.0, which is exactly that row's label. The model learns to read the label from the feature. Training scores look excellent, and validation scores collapse.
Rare categories are also noisy even without leakage. A category seen twice, with one positive, has a mean of 0.5 from almost no evidence.
The code below shows the effect on pure noise. The target is random, so any honest score should be near an AUC of 0.5.
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import TargetEncoder
rng = np.random.default_rng(0)
n = 2000
X = pd.DataFrame({"zip": rng.integers(0, 500, size=n).astype(str)})
y = rng.integers(0, 2, size=n) # pure noise: no real signal
# Leaky: category means are computed on all rows, then cross-validated
means = pd.Series(y).groupby(X["zip"]).mean()
X_leaky = pd.DataFrame({"zip_te": X["zip"].map(means)})
leaky = cross_val_score(
LogisticRegression(), X_leaky, y, cv=5, scoring="roc_auc"
)
# Safe: the encoder lives inside the pipeline and is refit per training fold
safe_model = Pipeline([
("te", TargetEncoder(random_state=0)),
("clf", LogisticRegression()),
])
safe = cross_val_score(safe_model, X, y, cv=5, scoring="roc_auc")
print("leaky:", leaky.mean())
print("safe: ", safe.mean())The leaky score comes out clearly above 0.5 on data that contains no signal. The pipeline score stays near 0.5, which is the correct answer.
Smoothing
Smoothing pulls the estimate for a rare category toward the global mean. A common form blends the two:
encoded = (n × categorymean + m × globalmean) / (n + m)
Here n is the number of rows in the category and m is a smoothing strength you choose. A category with n = 2 and m = 20 is almost entirely the global mean. A category with n = 2000 is almost entirely its own mean. The encoder trusts a category in proportion to the evidence behind it.
You can write this by hand to see the mechanics. Use it only on training rows.
import pandas as pd
def smoothed_means(categories: pd.Series, y: pd.Series, m: float = 20.0):
global_mean = y.mean()
stats = y.groupby(categories).agg(["mean", "count"])
encoded = (stats["count"] * stats["mean"] + m * global_mean) / (
stats["count"] + m
)
return encoded, global_mean
train_cat = pd.Series(["a", "a", "b", "b", "b", "c"])
train_y = pd.Series([1, 0, 1, 1, 0, 1])
table, fallback = smoothed_means(train_cat, train_y, m=2.0)
# Unseen categories at prediction time fall back to the global mean
new_cat = pd.Series(["a", "z"])
print(new_cat.map(table).fillna(fallback))Scikit-learn's TargetEncoder has a smooth parameter. The default, "auto", picks the strength from the variance of the target within and between categories. You can pass a number to set it yourself.
Cross-fitting inside scikit-learn's TargetEncoder
Smoothing reduces the noise, but a row's own label still contributes to its own encoding. Scikit-learn's TargetEncoder (available from version 1.3) removes that with cross-fitting.
During fit_transform, the encoder splits the training data into cv folds (default 5). It computes each fold's encoding from the other folds, so no row sees its own label. The encoder also stores encodings fitted on the full training set. Later transform calls use those.
The diagram below shows the two paths.
This design has a consequence that surprises people:
Using it in a ColumnTransformer
Target encoding fits into the same structure you built earlier. Give it the high-cardinality columns and keep one-hot for the rest.
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.linear_model import LogisticRegression
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import OneHotEncoder, StandardScaler, TargetEncoder
preprocess = ColumnTransformer([
("num", StandardScaler(), ["age", "income"]),
("low", OneHotEncoder(handle_unknown="ignore"), ["plan"]),
("high", TargetEncoder(smooth="auto", cv=5, random_state=0), ["zip"]),
])
model = Pipeline([
("prep", preprocess),
("clf", LogisticRegression(max_iter=1000)),
])
# Tiny runnable example
df = pd.DataFrame({
"age": [25, 32, 47, 51, 38, 29, 44, 60, 35, 41, 27, 53],
"income": [40, 55, 80, 90, 62, 45, 77, 95, 58, 70, 42, 88],
"plan": ["a", "b", "a", "b", "a", "b", "a", "b", "a", "b", "a", "b"],
"zip": ["10", "10", "20", "20", "30", "30",
"10", "20", "30", "10", "20", "30"],
})
target = [0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1]
model.fit(df, target)
print(model.predict(df.head(3)))Pass random_state so the fold shuffling is reproducible. Without it, two runs of the same pipeline give slightly different training features.
Edge cases and failure modes
- Unseen categories. At prediction time, a category not seen in training gets the global target mean. This is a reasonable neutral guess, but check how often it happens in production.
- Missing values. Impute them or treat them as their own category on purpose. Check how your scikit-learn version handles
NaNin categorical columns before relying on a default. - Multiclass targets. The encoder produces one column per class, so the output is wider than one column.
- Continuous targets. The category mean of
yworks directly. The leakage risk is the same. - Distribution shift. Encodings reflect the past. If category behavior changes, such as a store whose conversion rate drops, the encoding goes stale. Monitor it and retrain.
- Nested selection. If you tune
smoothorcvwith a grid search, keep the encoder inside the pipeline passed to the search. Otherwise the search reuses leaked features. - Linear models and trees. Both can use target-encoded columns. Tree ensembles with native categorical support, such as histogram gradient boosting, may make the encoder unnecessary. Compare with cross-validation instead of assuming.
Decision guide
Start with one-hot encoding when a column has a few dozen categories or fewer. Try target encoding when cardinality is in the hundreds or more and one-hot hurts speed or accuracy. Judge the choice by cross-validated score on the whole pipeline, as in the evaluation chapter. A better training score proves nothing here, because the leaky version also produces one.
Exercise
A teammate computes train.groupby("city")["churned"].mean(), maps it onto both the training and validation sets, and reports a validation AUC of 0.91. After deployment the AUC is 0.68. Name two things wrong with the process and how you would fix each.
Show answer
First, the encoding was computed from labels and then applied to the training rows themselves, so each training row's own label leaks into its feature. If the validation labels were included in the groupby, the validation score is also inflated. Fix both by putting a cross-fitting TargetEncoder inside a Pipeline and evaluating with cross_val_score, so means are computed only from training folds. Second, rare cities get unreliable means from few rows. Fix this with smoothing, using the smooth parameter, so small categories move toward the global mean. A fallback to the global mean for unseen cities also keeps production predictions stable.
Exercise
Why does TargetEncoder().fit(X_train, y_train).transform(X_train) give a different result from TargetEncoder().fit_transform(X_train, y_train), and which should feed the model?
Show answer
fit_transform uses cross-fitting, so each training row is encoded from folds that exclude its own label. fit followed by transform encodes every row with full-data statistics that include its own label, which leaks. The model should be trained on the fit_transform output. A Pipeline does this automatically.