Sub topic 12
CatBoost: ordered target statistics for categorical features
This chapter assumes you know what target encoding is, what overfitting means, and how to build a pandas DataFrame. It also assumes you have read the CatBoost overview chapter.
The leakage problem
A categorical column such as city cannot be fed to a tree as text. A common fix is target encoding, which replaces each category with the mean of the label for that category. The naive version computes the mean over all rows, including the row being encoded. The row's own label then leaks into its feature. The model learns to trust the encoded column too much, and validation scores drop.
The ordered fix
CatBoost draws a random permutation of the training rows. It encodes each row using only the rows that come before it in that permutation. The formula is:
encoded = (sum of labels of earlier rows with this category + a * prior) / (count of earlier rows with this category + a)Here prior is a constant starting guess and a is its weight. The prior keeps early rows, which have few or no predecessors, from getting extreme values. No row ever sees its own label.
A hand-built version
This sketch treats the DataFrame order as the permutation. It shows the idea but is not CatBoost's code.
import pandas as pd
df = pd.DataFrame({
"city": ["A", "B", "A", "A", "B", "A"],
"y": [1, 0, 1, 0, 1, 1],
})
prior, a = 0.5, 1.0
prev_sum = df.groupby("city")["y"].cumsum() - df["y"]
prev_cnt = df.groupby("city").cumcount()
df["encoded"] = (prev_sum + a * prior) / (prev_cnt + a)
print(df)The first row of each city gets 0.5, which is the prior. The second A row gets (1 + 0.5) / 2 = 0.75.
What CatBoost adds
- It uses several permutations, not one, so the encoding of an early row is not stuck with little history.
- At prediction time it encodes categories with statistics from the whole training set.
- It builds combinations of categorical features, such as
cityplusplan, and encodes them the same way. - It one-hot encodes features with few categories. The
one_hot_max_sizeparameter sets the cutoff.
You enable all of this by listing the columns in cat_features when you build a Pool. Pass the raw strings. Do not label-encode them first, because CatBoost would treat the integers as numbers.
Trade-offs
Ordered statistics cost extra training time compared with plain one-hot or integer codes. High-cardinality columns, such as user IDs, also use more memory. In return, you get an encoding that rarely overfits and needs no manual cross-validated target encoding step.
Exercise
In the hand-built example, why does the first row of every category receive the prior instead of its own label's mean?
Show answer
Each row is encoded only from rows before it in the permutation. The first row of a category has no earlier rows, so the sums are zero and the formula reduces to the prior. This guarantees a row's own label never appears in its encoding, which prevents target leakage.