CatBoost › Example
Machine Learning from ScratchAll chapters CatBoost › ExampleOne section · Sections in this chapter4 / 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
Let's work through a concrete example to understand how CatBoost processes categorical features and builds symmetric trees. We'll use a simplified dataset to make the calculations clear and traceable.
Dataset Setup: Consider a small dataset with 6 observations, 2 numerical features, and 1 categorical feature:
| ID | Age | Income | City | Target |
|---|---|---|---|---|
| 1 | 25 | 50000 | NYC | 1 |
| 2 | 30 | 60000 | SF | 1 |
| 3 | 35 | 70000 | NYC | 0 |
| 4 | 28 | 55000 | LA | 1 |
| 5 | 40 | 80000 | SF | 0 |
| 6 | 32 | 65000 | LA | 1 |
Step 1: Categorical Feature Processing
CatBoost processes the categorical feature "City" by computing target statistics. For each category, we calculate:
With and (prior probability):
- NYC:
- SF:
- LA:
Step 2: Building a Symmetric Tree
CatBoost builds symmetric trees where all nodes at the same level use the same feature. For a tree of depth 2, we need to select 2 features for the 2 levels.
Let's say we select "Age" for level 1 and "City_encoded" for level 2. The tree structure would be:
Level 1: Age < 32.5?
├── Yes (Age < 32.5)
│ └── Level 2: City_encoded < 0.722?
│ ├── Yes → Leaf 1 (NYC: 0.556)
│ └── No → Leaf 2 (LA: 0.889)
└── No (Age ≥ 32.5)
└── Level 2: City_encoded < 0.722?
├── Yes → Leaf 3 (NYC: 0.556)
└── No → Leaf 4 (SF: 0.556)
Step 3: Leaf Value Calculation
For each leaf, we calculate the optimal leaf value using the gradients. The leaf values are computed to minimize the loss function, typically using the average of the gradients in each leaf.
This symmetric structure ensures that the tree is balanced and uses the same features at each level, which helps prevent overfitting and creates more interpretable models.