Overview
Gradient boosting builds a model as a sum of many small trees, each one correcting the errors left by the trees before it. Trees need numbers, so a category such as a city has to be encoded. A natural encoding is the average target for that city, but if a row's own label is part of that average, the feature leaks the answer and the model overfits. CatBoost avoids this by putting the rows in a random order and encoding each row using only the rows before it. It applies the same idea to the boosting itself, so the errors that shape each tree come from predictions that never saw the row in question.
A short history
CatBoost was developed at Yandex and released as open source in 2017. The accompanying paper by Liudmila Prokhorenkova and colleagues, presented at NeurIPS in 2018, identified a subtle leak in earlier boosting methods: target statistics and gradients computed on the same rows the model is fitted to. Ordered target statistics and ordered boosting remove that leak. The library became popular for tables with many categorical columns because it handles them without manual encoding.
How it works
- Draw one random permutation of the training rows.
- Replace each categorical value by its ordered target statistic: the mean target of the same category over the earlier rows of the permutation, blended with the global mean as a prior.
- Start every prediction at the global mean (or its log-odds for
logloss). - For each tree, compute the gradients of the loss. With
ordered=Truethe gradients that choose the tree's structure come from predictions built only from earlier rows. - Grow an oblivious tree: at each level pick the single (feature, border) test that maximises the score over all leaves, and apply it to every node of that level.
- Set each leaf value to and add the tree to the model.
- At prediction time, encode a category by its statistic over the whole training set and sum the leaf values of all trees.
Watch out for
- Rows early in the permutation are encoded from very few earlier rows, so their statistics are noisy and close to the prior. The full library averages several permutations to reduce this, while this template uses one.
- A category never seen in training has no statistic and falls back to the prior, so the model treats all new categories alike.
- An oblivious tree applies one test to a whole level, which makes it weaker per tree than a free-form tree. Too few
iterationsor too small adepthunderfits. - This template is a simplified NumPy version of the paper for small tables: one permutation, no feature combinations, no missing-value handling, and only squared error and binary log-loss.
Use cases
When to use it
Tabular data with categorical columns, above all high-cardinality ones such as user ids, cities or product codes, where one-hot encoding is wasteful and a plain target mean leaks the label.
In industry
- Web search
- Ranking search results, the kind of task the library was built for at Yandex.
- Insurance
- Pricing and claim prediction from tables full of categories such as vehicle model, region and occupation.
- Retail
- Demand forecasting with store, product and promotion identifiers used directly as categorical features.
Choosing it: what must hold
- Tabular data in which categorical columns carry much of the signal.
- A supervised target: a class, a number or a ranking.
- Tolerance for somewhat longer training than histogram methods on very large tables.
When to choose something else
| If | Use instead |
|---|---|
| Almost all features are numeric and the table is very large | LightGBM or XGBoost |
| The categorical features have millions of distinct ids, as in click logs | An embedding-based model such as DeepFM or DLRM |
| You need a simple model that people can read | A decision tree or logistic regression |
Math foundations
Ordered target statistic
The number that replaces the category of row : the mean target over earlier rows of the same category, pulled towards the prior . Row 's own label is never used, so nothing leaks.
Boosting as an additive model
Each round adds one tree , shrunk by the learning rate , to the model so far.
Gradient statistics
The negative gradient says which way each prediction should move, the second derivative how sharply the loss bends. For squared error and . For log-loss and .
Split score of a level
How much the loss can drop if the leaves are cut this way. The tree tries every candidate test for the level and keeps the one with the highest score.
Leaf value
One Newton step for the rows of the leaf, shrunk by . The penalty pulls values of leaves with few rows towards zero.
Leaf index of an oblivious tree
Each level contributes one bit, so a row's leaf is a binary number of digits. Evaluating a tree is comparisons with no branching.
Symbols
- the random permutation; a smaller value means the row comes earlier
- the category of row i
- the target of row i
- the prior, the global mean of the target
- prior_weight
- the model after m trees
- learning_rate
- negative gradient and second derivative of the loss for row i
- sums of g and h over the rows in leaf l
- l2_leaf_reg
- depth of the tree
- feature and border tested at level d
- 1 if the statement inside is true, otherwise 0
Worked by hand
A city column with prior and . In permutation order the rows are: paris with , rome with , paris with , then another paris row.
The same category gets a different number in each row, because each row only sees the labels before it. The value starts at the prior and moves towards the category's own mean as more rows arrive.
Visual example
Loading the example.
Try this
- Each level of a tree uses one cut for every branch.
- Compare the grid-like regions with XGBoost at the same depth.
Code sample
import numpy as np
from impl import CatBoost
from config import CatBoostConfig
rng = np.random.default_rng(0)
effect = {"paris": 3.0, "rome": -2.0, "oslo": 0.5}
city = rng.choice(list(effect), size=500)
x = rng.normal(size=500)
y = np.array([effect[c] for c in city]) + 2.0 * x
X = np.empty((500, 2), dtype=object)
X[:, 0], X[:, 1] = city, x # column 0 is categorical
model = CatBoost(CatBoostConfig(cat_features=(0,), iterations=150)).fit(X, y)
print(round(model.loss_history[0], 2), "->", round(model.loss_history[-1], 2)) # training RMSE
print(model.predict(X[:3]).round(2), y[:3].round(2))Read the implementation (216 lines)
"""CatBoost-style gradient boosting: ordered target statistics, oblivious trees, ordered boosting.
NumPy only. Three ideas from CatBoost are implemented:
1. Ordered target statistics. A categorical value is replaced by the mean target of its category, but for a
training row only rows that come BEFORE it in a random permutation are used, so a row never sees its own
label (no target leakage).
2. Oblivious (symmetric) trees. Every node of a level uses the same (feature, border) test, so a tree of
depth d is a table of 2^d leaf values indexed by d bits.
3. Ordered boosting. The gradients that choose a tree's structure come from a running prediction that, for
each row, was built only from rows before it in the permutation. The leaf values of the final model are
then estimated from all rows.
"""
from __future__ import annotations
import numpy as np
try:
from .config import CatBoostConfig
except ImportError: # run from the template's own folder
from config import CatBoostConfig
def _sigmoid(z: np.ndarray) -> np.ndarray:
return 1.0 / (1.0 + np.exp(-np.clip(z, -60.0, 60.0)))
def ordered_target_statistics(categories, y: np.ndarray, order: np.ndarray, prior: float, prior_weight: float) -> np.ndarray:
"""Encode one categorical column without target leakage.
categories: (n,) hashable values. y: (n,) targets. order: (n,) a permutation, order[0] is the first row.
For each row: (sum of y over earlier rows of the same category + prior_weight * prior)
/ (number of such rows + prior_weight).
Returns (n,) floats in the original row order.
"""
out = np.empty(len(y))
sums: dict = {}
counts: dict = {}
for row in order:
key = categories[row]
out[row] = (sums.get(key, 0.0) + prior_weight * prior) / (counts.get(key, 0) + prior_weight)
sums[key] = sums.get(key, 0.0) + float(y[row])
counts[key] = counts.get(key, 0) + 1
return out
class CatBoost:
"""Gradient boosting on oblivious trees with categorical features handled by ordered target statistics.
loss "rmse": regression. loss "logloss": binary classification with 0/1 labels.
"""
def __init__(self, config: CatBoostConfig | None = None) -> None:
self.config = config or CatBoostConfig()
self.trees_: list[dict] = [] # each: {"features": [..], "borders": [..], "values": (2^depth,)}
self.base_ = 0.0
self.cat_stats_: dict[int, dict] = {} # column -> {category: (sum of y, count)} over all training rows
self.prior_ = 0.0
self.loss_history: list[float] = [] # training loss of the model after each tree
# ---- features --------------------------------------------------------------------------------------
def _numeric(self, X, train_ts: dict | None = None) -> np.ndarray:
"""Turn the raw table into floats: categorical columns become target statistics. Returns (n, d)."""
cfg = self.config
n, d = len(X), len(X[0])
out = np.empty((n, d))
for j in range(d):
column = [row[j] for row in X]
if j not in cfg.cat_features:
out[:, j] = np.asarray(column, dtype=float)
elif train_ts is not None:
out[:, j] = train_ts[j]
else: # prediction: statistics of the whole training set; unseen categories get the prior
stats = self.cat_stats_[j]
out[:, j] = [(stats.get(c, (0.0, 0))[0] + cfg.prior_weight * self.prior_)
/ (stats.get(c, (0.0, 0))[1] + cfg.prior_weight) for c in column]
return out
def _borders(self, F: np.ndarray) -> list[np.ndarray]:
"""Candidate split points of each feature: up to `border_count` midpoints between distinct values."""
borders = []
for j in range(F.shape[1]):
values = np.unique(F[:, j])
mids = (values[1:] + values[:-1]) / 2.0
if len(mids) > self.config.border_count:
mids = np.unique(np.quantile(mids, np.linspace(0, 1, self.config.border_count)))
borders.append(mids)
return borders
# ---- loss ------------------------------------------------------------------------------------------
def _grad_hess(self, y: np.ndarray, pred: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Negative gradient and hessian of the loss with respect to the raw prediction."""
if self.config.loss == "rmse":
return y - pred, np.ones_like(y)
p = _sigmoid(pred)
return y - p, p * (1.0 - p)
def _loss(self, y: np.ndarray, pred: np.ndarray) -> float:
if self.config.loss == "rmse":
return float(np.sqrt(np.mean((y - pred) ** 2)))
return float(np.mean(np.logaddexp(0.0, pred) - y * pred))
# ---- one oblivious tree ----------------------------------------------------------------------------
def _grow_tree(self, F: np.ndarray, borders: list, g: np.ndarray, h: np.ndarray) -> tuple[dict, np.ndarray]:
"""Choose one (feature, border) per level by the gain sum_leaves G^2 / (H + l2).
F: (n, d) features. g, h: (n,) gradients and hessians that drive the structure.
Returns (tree without leaf values, leaf index of every row (n,)).
"""
cfg = self.config
leaf = np.zeros(len(F), dtype=int)
features, cuts = [], []
current = np.sum(g) ** 2 / (np.sum(h) + cfg.l2_leaf_reg)
for level in range(cfg.depth):
n_leaves = 2 ** (level + 1)
best = (current + 1e-12, None, None)
for j, cand in enumerate(borders):
if len(cand) == 0:
continue
bits = F[:, j][:, None] > cand[None, :] # (n, m)
idx = (leaf[:, None] * 2 + bits) + np.arange(len(cand))[None, :] * n_leaves
G = np.bincount(idx.ravel(), weights=np.repeat(g, len(cand)), minlength=len(cand) * n_leaves)
H = np.bincount(idx.ravel(), weights=np.repeat(h, len(cand)), minlength=len(cand) * n_leaves)
score = (G**2 / (H + cfg.l2_leaf_reg)).reshape(len(cand), n_leaves).sum(axis=1)
b = int(score.argmax())
if score[b] > best[0]:
best = (float(score[b]), j, float(cand[b]))
if best[1] is None:
break # no split improves the fit
current = best[0]
features.append(best[1])
cuts.append(best[2])
leaf = leaf * 2 + (F[:, best[1]] > best[2])
return {"features": features, "borders": cuts}, leaf
@staticmethod
def _leaf_index(tree: dict, F: np.ndarray) -> np.ndarray:
leaf = np.zeros(len(F), dtype=int)
for j, cut in zip(tree["features"], tree["borders"]):
leaf = leaf * 2 + (F[:, j] > cut)
return leaf
def _ordered_leaf_values(self, leaf: np.ndarray, g: np.ndarray, h: np.ndarray, order: np.ndarray) -> np.ndarray:
"""For each row, the leaf value estimated only from rows before it in the permutation. Returns (n,)."""
by_leaf = order[np.argsort(leaf[order], kind="stable")] # grouped by leaf, permutation order inside
g_sorted, h_sorted, leaf_sorted = g[by_leaf], h[by_leaf], leaf[by_leaf]
cg = np.cumsum(g_sorted) - g_sorted # sums over earlier rows, any leaf
ch = np.cumsum(h_sorted) - h_sorted
starts = np.flatnonzero(np.r_[True, leaf_sorted[1:] != leaf_sorted[:-1]])
group = np.cumsum(np.r_[True, leaf_sorted[1:] != leaf_sorted[:-1]]) - 1
values = np.empty(len(g))
values[by_leaf] = (cg - cg[starts][group]) / (ch - ch[starts][group] + self.config.l2_leaf_reg)
return values
# ---- public API ------------------------------------------------------------------------------------
def fit(self, X, y: np.ndarray) -> "CatBoost":
"""Train. X: (n, d) table (2-d array or list of rows); the columns listed in `cat_features` may hold any
hashable values, the others must be numeric. y: (n,) values (rmse) or 0/1 labels (logloss)."""
cfg = self.config
y = np.asarray(y, dtype=float)
n = len(y)
rng = np.random.default_rng(cfg.seed)
order = rng.permutation(n)
self.prior_ = float(y.mean())
train_ts, self.cat_stats_ = {}, {}
for j in cfg.cat_features:
column = [row[j] for row in X]
train_ts[j] = ordered_target_statistics(column, y, order, self.prior_, cfg.prior_weight)
stats: dict = {}
for c, target in zip(column, y):
s, k = stats.get(c, (0.0, 0))
stats[c] = (s + float(target), k + 1)
self.cat_stats_[j] = stats
F = self._numeric(X, train_ts)
borders = self._borders(F)
if cfg.loss == "rmse":
self.base_ = self.prior_
else:
p = np.clip(self.prior_, 1e-6, 1 - 1e-6)
self.base_ = float(np.log(p / (1 - p)))
pred = np.full(n, self.base_) # the model's prediction on the training rows
ordered_pred = np.full(n, self.base_) # per row: built only from rows before it in the permutation
self.trees_, self.loss_history = [], []
for _ in range(cfg.iterations):
g, h = self._grad_hess(y, pred)
g_struct, h_struct = self._grad_hess(y, ordered_pred) if cfg.ordered else (g, h)
tree, leaf = self._grow_tree(F, borders, g_struct, h_struct)
n_leaves = 2 ** len(tree["features"])
G = np.bincount(leaf, weights=g, minlength=n_leaves)
H = np.bincount(leaf, weights=h, minlength=n_leaves)
tree["values"] = cfg.learning_rate * G / (H + cfg.l2_leaf_reg)
pred += tree["values"][leaf]
if cfg.ordered:
ordered_pred += cfg.learning_rate * self._ordered_leaf_values(leaf, g_struct, h_struct, order)
self.trees_.append(tree)
self.loss_history.append(self._loss(y, pred))
return self
def decision_function(self, X) -> np.ndarray:
"""Raw model output: the value for rmse, the log-odds for logloss. Returns (n,)."""
F = self._numeric(X)
out = np.full(len(F), self.base_)
for tree in self.trees_:
out += tree["values"][self._leaf_index(tree, F)]
return out
def predict_proba(self, X) -> np.ndarray:
"""Probability of class 1, (n,). Only for loss='logloss'."""
if self.config.loss != "logloss":
raise ValueError("predict_proba is only defined for loss='logloss'")
return _sigmoid(self.decision_function(X))
def predict(self, X) -> np.ndarray:
"""Predicted values (rmse) or 0/1 labels (logloss), (n,)."""
raw = self.decision_function(X)
return raw if self.config.loss == "rmse" else (raw >= 0).astype(int)- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Call ordered_target_statistics on the four-row city example above with order=np.arange(4), prior=2.0 and prior_weight=1.0, and check the numbers. Then fit CatBoost on the city data from the README with ordered=True and with ordered=False, and compare the training loss_history with the error on fresh rows.
Check on learning
- Why does encoding a category by the plain mean target over all rows, including the row itself, cause overfitting, especially for rare categories?
A way to think about it
Take a category that appears exactly once. Work out what its encoded value equals, and what a tree can then learn from that feature.
- In the ordered statistic, the first rows of the permutation get values near the prior. Is that a flaw or a feature? What would the model learn from these rows?
A way to think about it
Compare the situation with prediction time for a new or rare category. Think about whether training on noisy encodings prepares the model for that.
- An oblivious tree of depth 4 has at most 16 leaves but only 4 tests. A free-form tree of depth 4 can have 15 different tests. What does the oblivious tree lose, and what does it gain?
A way to think about it
Consider how flexibly each can carve up the feature space, then how much each can adapt to noise in a small leaf, and how fast each is to evaluate.
- What happens to a leaf value as grows, and which leaves are affected the most?
A way to think about it
Compare for a leaf with and one with when .