Sub topic 12
CatBoost: ordered target statistics for categorical features
This chapter assumes you know what a categorical feature is, how target encoding works in outline, and why a model that sees its own labels while training overfits. It also assumes you have read the CatBoost overview chapter.
The problem with categorical columns
Tree models need numbers. The usual ways of turning categories into numbers each have a cost:
| Method | Problem |
|---|---|
| One-hot encoding | A column with 10,000 values becomes 10,000 sparse columns. Trees split on them poorly. |
| Label encoding | The integer order is arbitrary, so splits like `city_id < 40` mean nothing. |
| Target (mean) encoding | Strong signal, but it leaks the label if computed naively. |
Target encoding replaces each category with the average target value for that category. The leak is easy to miss. If you compute the mean over all rows, each row's own label is part of its own feature. A category with two rows already carries half of each row's label. The model learns to trust the feature, and the trust does not hold on new data. This is a form of target leakage.
CatBoost keeps the strong signal of target encoding and removes this leak with ordered target statistics.
The ordered target statistic
CatBoost draws a random permutation of the training rows and treats it as a timeline. For each row, the encoding uses only rows that come earlier in the permutation and share the row's category:
TS(row) = (sum_of_earlier_targets + a * prior) / (count_of_earlier_rows + a)sum_of_earlier_targetsis the sum of labels of earlier rows with the same category value.count_of_earlier_rowsis how many such rows there are.prioris a starting guess for the target, for example the global mean or 0.5 for a binary target.ais the prior weight. It controls how many observations it takes to outweigh the prior.
A row's own label never enters its own feature. The feature is computed as if the model were seeing the data one row at a time.
A worked example
Take category A with four rows. In permutation order their labels are 1, 0, 1, 1. Use prior 0.5 and a = 1.
| Position | Label | Earlier sum | Earlier count | Statistic |
|---|---|---|---|---|
| 1 | 1 | 0 | 0 | (0 + 0.5) / (0 + 1) = 0.5 |
| 2 | 0 | 1 | 1 | (1 + 0.5) / (1 + 1) = 0.75 |
| 3 | 1 | 1 | 2 | (1 + 0.5) / (2 + 1) = 0.5 |
| 4 | 1 | 2 | 3 | (2 + 0.5) / (3 + 1) = 0.625 |
Early rows get values close to the prior, because little history exists. Later rows get values closer to the category's real rate.
At prediction time there is no ordering to respect. CatBoost uses statistics computed from the whole training set. For A that gives (3 + 0.5) / (4 + 1) = 0.7. A category never seen in training has count 0, so it falls back to the prior.
Seeing the leak with code
The script below implements the ordered statistic in pandas. It uses a feature that carries no information: a random ID with about two rows per value, and random labels. A good encoding should show no relationship between the feature and the label.
import numpy as np
import pandas as pd
def ordered_target_statistic(cat, y, prior=0.5, weight=1.0, seed=0):
"""Encode a categorical column using only earlier rows in a random permutation."""
rng = np.random.default_rng(seed)
order = rng.permutation(len(cat))
cat_p = pd.Series(np.asarray(cat)[order])
y_p = pd.Series(np.asarray(y)[order], dtype=float)
grouped = y_p.groupby(cat_p)
earlier_sum = grouped.cumsum() - y_p
earlier_count = grouped.cumcount()
ts = (earlier_sum + weight * prior) / (earlier_count + weight)
result = np.empty(len(cat))
result[order] = ts.to_numpy()
return result
rng = np.random.default_rng(1)
n = 2000
ids = rng.integers(0, 1000, n) # high-cardinality, pure noise
y = rng.integers(0, 2, n) # labels unrelated to ids
naive = pd.Series(y).groupby(ids).transform("mean").to_numpy()
ordered = ordered_target_statistic(ids, y)
print("naive corr with label: ", np.corrcoef(naive, y)[0, 1])
print("ordered corr with label:", np.corrcoef(ordered, y)[0, 1])The naive encoding correlates strongly with the label, even though the ID is noise. A tree model would split on it and overfit. The ordered encoding stays close to zero correlation, which is the honest answer.
Why several permutations
One permutation has a weakness. Rows near the start of it get statistics built from very little history, so their encoded values are noisy. CatBoost reduces this by using different random permutations at different boosting steps. No single row stays stuck at the front, and the noise averages out over many trees.
Combinations of categorical features
A single category is often weak, while a pair is strong. For example, city alone and plan alone may say little, but city combined with plan may predict churn well. CatBoost builds such combinations greedily while it grows a tree. When it considers a split, it can join the categorical features already used in that tree with a new one, then encode the combination with the same ordered statistic. The max_ctr_complexity parameter limits how many features may be combined.
What CatBoost does with categorical features
CatBoost does not apply one rule to every categorical column.
- Low-cardinality features. Columns with at most
one_hot_max_sizedistinct values are one-hot encoded. Larger columns use target statistics. - Several statistics per feature. The target statistic is one of several kinds. Others include counts of how often a category appears, which does not use the label at all.
- Different target types. For regression the statistic is built from target means. For multiclass problems it is built per class.
from catboost import CatBoostClassifier
model = CatBoostClassifier(
iterations=500,
one_hot_max_size=4, # one-hot for columns with up to 4 values
max_ctr_complexity=2, # combine at most 2 categorical features
verbose=0,
)Raising max_ctr_complexity gives richer features but slower training and more overfitting risk. Lowering it speeds training.
Common mistakes
- Passing floats or NaN as categories. Values in
cat_featurescolumns must be strings or integers. A float column, or missing values stored asNaN, raises an error. Convert withdf[col] = df[col].fillna("missing").astype(str). - Encoding before CatBoost. Do not target-encode a column yourself and then pass the result in. Pass the raw categories and let CatBoost encode them. Doing both adds leakage that CatBoost cannot see.
- Forgetting to declare the column. If a string column is not listed in
cat_features, CatBoost cannot treat it as categorical, and fitting fails on non-numeric data. If an integer ID column is not listed, it is treated as a number, and splits likeid < 40are meaningless. - Judging by one seed. The permutations depend on
random_seed. When two settings differ by a small amount, repeat the run with several seeds before choosing one.
Summary
Ordered target statistics give CatBoost a numeric encoding of each category without the model seeing a row's own label. The statistic is computed along a random permutation, uses only earlier rows, and blends the category's history with a prior. Multiple permutations reduce noise from short histories, and greedy combinations let the model find interactions between categories.
Exercise
Category "B" has three rows. In permutation order their labels are 0, 0, 1. Use prior 0.5 and a = 1. What ordered statistic does the third row receive during training, and what value would the category receive at prediction time?
Show answer
For the third row the earlier rows have labels 0 and 0, so the sum is 0 and the count is 2. The statistic is (0 + 0.5) / (2 + 1) = 0.1667. At prediction time CatBoost uses all training rows for the category: sum 1, count 3, giving (1 + 0.5) / (3 + 1) = 0.375. The training value excludes the row's own label of 1, which is why it is lower.
Exercise
A column user_id has 50,000 distinct values in 60,000 rows. A teammate target-encodes it with the full-data mean and passes the result to CatBoost as a numeric column. Validation AUC is excellent, but production AUC is poor. What is the likely cause, and what should change?
Show answer
Almost every user has one or two rows, so the full-data mean contains the row's own label. The model learns that the encoded value predicts the label, which does not hold on new users. Pass the raw user_id as a string in cat_features and let CatBoost compute ordered statistics. Also check that the validation split does not contain training rows' users, or the leak will stay hidden.