CatBoost › Formula

Michael BrenndoerferJuly 9, 202520 min read
Machine Learning from ScratchAll chapters
Part 5 of 9Tree-Based Models
Chapter 46CatBoost › Formula
Reading section 2 of 8 · Formula · 20 minSection 2 of 8 · 20 min

Book contents

Section 2 of 8 · 20 min read

CatBoost › FormulaOne section · Sections in this chapter2 / 8 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

CatBoost builds upon the fundamental gradient boosting framework we've already explored, but introduces several key modifications to the standard gradient boosting formula. Let's examine how CatBoost's approach differs from traditional gradient boosting implementations.

The core gradient boosting formula remains the same foundation:

Fm(x)=Fm−1(x)+γmhm(x)F_m(x) = F_{m-1}(x) + \gamma_m h_m(x)

where:

  • Fm(x)F_m(x): The ensemble model at iteration mm (cumulative prediction after adding mm trees)
  • Fm−1(x)F_{m-1}(x): The ensemble model from the previous iteration (cumulative prediction after m−1m-1 trees)
  • γm\gamma_m: The learning rate at iteration mm (controls the contribution of each new tree)
  • hm(x)h_m(x): The new tree added at iteration mm (trained on residuals or gradients)
  • xx: Input feature vector for a given observation

However, CatBoost modifies how we compute the gradients and how we build the trees.

Categorical Feature Processing:

CatBoost's most distinctive feature is its handling of categorical variables. Instead of preprocessing categorical features, CatBoost computes target statistics during training. For a categorical feature xkx^k with categories c1,c2,...,ckc_1, c_2, ..., c_k, CatBoost computes an encoded value for each observation as follows:

x^ik=∑j=1n[xjk=xik]⋅yj+α⋅p∑j=1n[xjk=xik]+α\hat{x}^k_i = \frac{\sum_{j=1}^{n} [x^k_j = x^k_i] \cdot y_j + \alpha \cdot p}{\sum_{j=1}^{n} [x^k_j = x^k_i] + \alpha}

where:

  • x^ik\hat{x}^k_i: The encoded numerical value for the ii-th observation's category in feature xkx^k
  • xikx^k_i: The categorical value of feature kk for observation ii
  • [xjk=xik][x^k_j = x^k_i]: Indicator function that equals 1 if observation jj has the same category as observation ii, and 0 otherwise
  • yjy_j: The target value for observation jj
  • nn: Total number of observations in the dataset
  • α\alpha: Smoothing parameter that controls regularization (typically set to 1)
  • pp: Prior probability of the target (usually the mean of the target variable across the entire dataset)

Numerator:
∑j=1n[xjk=xik]⋅yj\sum_{j=1}^{n} [x^k_j = x^k_i] \cdot y_j adds up the target values for all observations that share the same category as the ii-th observation. The term α⋅p\alpha \cdot p is added to introduce smoothing, pulling the encoding towards the global mean when there are few samples for a category.

Denominator:
∑j=1n[xjk=xik]\sum_{j=1}^{n} [x^k_j = x^k_i] counts how many times the category xikx^k_i appears in the dataset. Adding α\alpha to the denominator ensures the encoding is well-defined even for rare categories and further smooths the result.

This formula computes a smoothed mean target value for each category. For each observation, the encoded value is the average target for its category, but "shrunk" towards the overall mean pp according to the smoothing parameter α\alpha. This helps prevent overfitting, especially for categories that appear infrequently.

CatBoost uses this dynamic, smoothed target encoding for categorical features during training. By combining the mean target value for each category with the global mean, CatBoost creates numerical representations of categorical variables that capture their relationship with the target variable while reducing the risk of overfitting.

Out[3]:
Visualization
Flowchart showing CatBoost's categorical feature processing with target statistics and smoothing.
CatBoost's categorical feature processing flow. The process maps raw categorical data into numerical encodings using target statistics with smoothing. Each category is encoded based on the mean target value of observations with that category, plus a smoothing factor to prevent overfitting. This creates continuous, meaningful representations that preserve the relationship between categorical features and the target variable.

Symmetric Trees (Oblivious Trees):

CatBoost uses symmetric trees, also known as oblivious trees, where all nodes at the same depth (level) split on the same feature and threshold. This is in contrast to traditional decision trees, where each node can split on any feature independently. In a symmetric tree of depth dd, there are dd binary splits, and thus 2d2^d leaf nodes. The structure of the tree is fully determined by the sequence of dd features (and their thresholds) chosen for each level.

Let's formalize the prediction function for a symmetric tree.

Suppose the mm-th tree in the ensemble has depth dd, and at each level kk (k=1,2,...,dk = 1, 2, ..., d), the tree splits on feature fkf_k at threshold tkt_k. For an input xx, we can define a binary decision at each level:

bk(x)={0if xfk≤tk1if xfk>tkb_k(x) = \begin{cases} 0 & \text{if } x_{f_k} \leq t_k \\ 1 & \text{if } x_{f_k} > t_k \end{cases}

where:

  • bk(x)b_k(x): Binary decision at level kk for input xx (0 for left branch, 1 for right branch)
  • xfkx_{f_k}: Value of feature fkf_k in input vector xx
  • fkf_k: Feature index used for splitting at level kk
  • tkt_k: Threshold value for the split at level kk

The path from the root to a leaf is determined by the vector of decisions (b1(x),b2(x),...,bd(x))(b_1(x), b_2(x), ..., b_d(x)). This vector can be interpreted as a binary number, which uniquely identifies one of the 2d2^d leaves. The index of the leaf node jj for input xx can be computed as:

j(x)=1+∑k=1dbk(x)⋅2d−kj(x) = 1 + \sum_{k=1}^d b_k(x) \cdot 2^{d - k}

where:

  • j(x)j(x): Index of the leaf node that input xx reaches (ranges from 1 to 2d2^d, or 0 to 2d−12^d-1 if zero-indexed)
  • dd: Depth of the symmetric tree (number of levels)
  • 2d−k2^{d-k}: Binary weight for the decision at level kk

The prediction of the mm-th symmetric tree for input xx is then:

hm(x)=cm,j(x)h_m(x) = c_{m, j(x)}

where:

  • hm(x)h_m(x): Prediction of the mm-th tree for input xx
  • cm,jc_{m, j}: The value (prediction) assigned to leaf jj in tree mm
  • j(x)j(x): The leaf index reached by input xx (computed using the formula above)

Alternatively, this can be written in indicator function notation as:

hm(x)=∑j=12dcm,j⋅1Rm,j(x)h_m(x) = \sum_{j=1}^{2^d} c_{m, j} \cdot \mathbf{1}_{R_{m, j}}(x)

where:

  • Rm,jR_{m, j}: The region (set of all inputs xx) corresponding to leaf jj in tree mm

  • 1Rm,j(x)\mathbf{1}_{R_{m, j}}(x): Indicator function that equals 1 if xx falls into region Rm,jR_{m, j}, and 0 otherwise

  • 2d2^d: Total number of leaves in the symmetric tree of depth dd

  • Each input xx is routed through dd binary splits (same feature per level for all nodes at that level).

  • The sequence of split decisions forms a binary code that selects one of 2d2^d leaves.

  • The output is the value assigned to that leaf.

This structure ensures that the tree is perfectly balanced and that the same features are considered at each level, which helps regularize the model and reduce overfitting.

Out[4]:
Visualization
Traditional tree diagram with Age, Income, and City splits arranged irregularly above five labeled leaves.
Traditional decision tree with an irregular structure. Different features and thresholds appear across nodes, producing five illustrated leaves and a structure that can overfit.
CatBoost symmetric tree diagram with repeated Age splits at one level and repeated Income splits at the next, above five labeled leaves.
CatBoost symmetric tree with a balanced structure. Nodes at the same level use the same feature family, producing five illustrated leaves and a regularized, predictable decision structure.

Gradient Computation with Ordered Boosting:

CatBoost implements a technique called "ordered boosting" to reduce overfitting. Instead of using all available data to compute gradients, CatBoost uses only the data that came before the current observation in the training set. This approach simulates the real-world scenario where we don't have access to future data when making predictions.

Let's expand the math behind this process.

Suppose we have a training dataset of nn observations, ordered as (x1,y1),(x2,y2),…,(xn,yn)(x_1, y_1), (x_2, y_2), \ldots, (x_n, y_n). At boosting iteration mm, the model so far is Fm−1(x)F_{m-1}(x). For each observation ii, the gradient is:

gm,i=∂L(yi,Fm−1(xi))∂Fm−1(xi)g_{m,i} = \frac{\partial L(y_i, F_{m-1}(x_i))}{\partial F_{m-1}(x_i)}

where:

  • gm,ig_{m,i}: Gradient of the loss function for observation ii at iteration mm
  • LL: Loss function (e.g., squared error for regression, log-loss for classification)
  • yiy_i: Actual target value for observation ii
  • Fm−1(xi)F_{m-1}(x_i): Current model prediction for observation ii at iteration m−1m-1
  • xix_i: Feature vector for observation ii

Traditional boosting computes the split criteria for the next tree using all gradients {gm,1,gm,2,…,gm,n}\{g_{m,1}, g_{m,2}, \ldots, g_{m,n}\}, i.e., all data points contribute to the statistics used for finding the best splits.

Ordered boosting in CatBoost, however, restricts the information available for each observation. When computing the split statistics for observation ii, only the gradients from observations with indices j<ij < i are used. That is, for each ii, the statistics for building the tree at iteration mm are computed using:

{gm,j:j<i}\{g_{m,j} : j < i\}

This can be formalized as follows. For each observation ii, the split statistics Sm,iS_{m,i} used to determine the best split are computed as:

Sm,i=Aggregate({gm,j:j<i})S_{m,i} = \text{Aggregate}\left(\{g_{m,j} : j < i\}\right)

where "Aggregate" denotes the sum or other relevant statistic (such as sum of gradients and Hessians) required for the split-finding algorithm.

This process ensures that, for each observation, the model and the splits are built using only information that would have been available up to that point in the data sequence, thus preventing "target leakage" from future data and reducing overfitting.

In summary:

  • The gradient for observation ii at iteration mm is: gm,i=∂L(yi,Fm−1(xi))∂Fm−1(xi)g_{m,i} = \frac{\partial L(y_i, F_{m-1}(x_i))}{\partial F_{m-1}(x_i)}
  • When building the tree at iteration mm, CatBoost uses only the gradients from observations j<ij < i to compute the split criteria for observation ii: Sm,i=Aggregate({gm,j:j<i})S_{m,i} = \text{Aggregate}\left(\{g_{m,j} : j < i\}\right)

This ordered approach reduces leakage during training by simulating the real-world scenario where future data is not available.

Out[5]:
Visualization
Training-sequence diagram where all observations except current observation 4 feed into its gradient computation, with a warning about future information.
Traditional gradient boosting computes the gradient for observation 4 using observations 1, 2, 3, 5, 6, and 7. The inclusion of later observations illustrates the future-information leakage that ordered boosting avoids.
Training-sequence diagram where only observations 1 through 3 feed into observation 4's gradient computation, with future observations marked unavailable and a three-item legend.
CatBoost ordered boosting computes the gradient for observation 4 using only previous observations 1, 2, and 3. Observations 5, 6, and 7 remain explicitly marked as unavailable future data.

Mathematical Properties

CatBoost's symmetric tree structure provides several important mathematical properties. The constraint that all nodes at the same level use the same feature creates a more balanced tree structure, which helps prevent overfitting and improves generalization. This structure also makes the model more interpretable, as the decision path is more predictable and easier to understand.

The ordered boosting technique provides a form of regularization by preventing the model from using information that wouldn't be available in real-world scenarios. This approach helps models perform better on unseen data, particularly in time-series or sequential data scenarios.

CatBoost's categorical feature processing creates smooth, continuous representations of categorical variables that are learned during training. This approach often results in better performance than traditional encoding methods because the encoding is optimized specifically for the task at hand, rather than using generic preprocessing techniques.