Sub topic 10
CatBoost: What It Does Differently
This chapter assumes you know how gradient boosted trees work, including residuals, learning rate and additive trees. It also assumes you can read basic pandas and scikit-learn code. CatBoost is a gradient boosting library that makes the same basic bet as LightGBM: add many small trees, each fixing the errors of the ensemble so far. It differs in three design choices. Each one targets a specific failure mode of ordinary boosting. This chapter gives the overview. Later chapters cover each choice in detail.
The problems CatBoost was built to address
Standard gradient boosting has two quiet sources of bias.
- Target leakage from categorical encoding. Trees need numbers. A common fix is target encoding: replace each category with the mean label of the rows that share it. If a row's own label is part of its own encoding, the model sees information it will not have at prediction time. Training scores then look better than real performance.
- Prediction shift. Each boosting step computes gradients using a model that was trained on the same rows. Those gradients are biased compared with gradients on unseen data. The bias builds up across iterations and can hurt generalization, especially on small datasets.
CatBoost addresses both with the idea of ordering. It treats rows as if they arrived in a random time sequence, and it only lets a row's statistics depend on rows that came before it.
The three main design choices
| Design choice | What it does | Problem it targets |
|---|---|---|
| Ordered target statistics | Encodes a categorical value using only the labels of earlier rows in a random permutation | Target leakage |
| Ordered boosting | Computes each row's gradient from a model that has not been trained on that row | Prediction shift |
| Symmetric (oblivious) trees | Uses the same split condition on every node at a given depth | Overfitting, and slow prediction |
Ordered target statistics
You pass raw categorical columns, such as strings, and declare them with cat_features. CatBoost shuffles the rows. For each row, it computes a statistic like the smoothed mean label of the same category, using only rows earlier in the shuffle. The first rows of each category get a statistic based mostly on a prior, because little history exists. It also builds combinations of categorical features, such as city plus plan, which lets the trees capture interactions. The detailed mechanics are in the chapter on ordered target statistics.
Ordered boosting
Instead of using one model's residuals on the same data it was fit to, CatBoost keeps supporting models trained on prefixes of the permutation. A row's gradient comes from a model that never saw that row. This removes the bias, at a computational cost. In practice, CatBoost uses ordered boosting by default on small datasets and a plain mode on larger ones. You can set it with boosting_type.
Symmetric trees
In a symmetric tree, every node at the same depth uses the same feature and threshold. A tree of depth 6 is then a table of 6 conditions and 64 leaves. Three consequences follow.
- The structure is a strong regularizer, because the tree cannot isolate a small region with a special split.
- Prediction is fast. Evaluating a tree means checking 6 conditions and reading a bit pattern as an index into the leaf values.
- Each tree is weaker than a freely grown tree, so CatBoost may need more iterations to match the fit.
Compare this with LightGBM's leaf-wise growth, where each leaf can choose its own split. LightGBM fits the training data more flexibly. CatBoost is more constrained, and often more stable with default settings.
Defaults you can rely on
CatBoost has a reputation for working well without tuning. Several defaults are chosen to make that true.
- If you do not set a learning rate, CatBoost picks one automatically from the dataset size and the number of iterations.
- Default depth is 6.
- Random strength and L2 leaf regularization are on by default.
- Numeric features are quantized into borders, much like LightGBM's histograms. The default is 254 borders per feature on CPU.
Automatic learning rate selection depends on the iteration count and the data. If you pass a fixed learning_rate, as the example below does, you take control of that behavior.
A first CatBoost model
The model below uses raw string columns. Note that no encoding step appears in the code.
import numpy as np
import pandas as pd
from catboost import CatBoostClassifier, Pool
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 5000
df = pd.DataFrame({
"age": rng.integers(18, 70, n),
"city": rng.choice(["A", "B", "C", "D"], n),
"plan": rng.choice(["free", "basic", "pro"], n),
})
signal = (df["plan"] == "pro") | (df["age"] > 55)
flip = rng.random(n) < 0.1
y = (signal ^ flip).astype(int)
X_train, X_valid, y_train, y_valid = train_test_split(
df, y, test_size=0.2, random_state=0
)
cat_features = ["city", "plan"]
train_pool = Pool(X_train, y_train, cat_features=cat_features)
valid_pool = Pool(X_valid, y_valid, cat_features=cat_features)
model = CatBoostClassifier(
iterations=1000,
learning_rate=0.1,
depth=6,
eval_metric="AUC",
verbose=100,
)
model.fit(train_pool, eval_set=valid_pool, early_stopping_rounds=50)
print(model.get_best_iteration())A Pool is CatBoost's data container. It holds features, labels and the list of categorical columns together, so the library knows which columns to encode. The eval_set supplies the validation data for early stopping. By default, CatBoost shrinks the final model to the best iteration found on that set (use_best_model).
Common errors
- Forgetting
cat_features. If a string column is not declared, CatBoost raises an error. If a categorical column is stored as integers, it is silently treated as numeric, and you lose the categorical encoding. - Missing categories as NaN. In categorical columns, CatBoost does not accept NaN values. Replace them with a placeholder string such as
"missing"before building the Pool. - Encoding categories yourself first. Label or target encoding before CatBoost removes its leakage protection. Pass the raw categories.
- Comparing speed unfairly. Ordered boosting, categorical combinations and many iterations make CatBoost slower to train than LightGBM on some data. Compare on the same data, with early stopping, and measure both training and prediction time.
- Reusing the validation set for early stopping and for a final score. The early-stopped model is tuned to that set. Keep a separate test set for the final estimate.
When these choices pay off
The three choices matter most in particular situations.
- Many high-cardinality categorical columns. Ordered target statistics give you a leakage-safe encoding without writing a pipeline.
- Small or noisy datasets. Ordered boosting and symmetric trees reduce overfitting.
- Latency-sensitive serving. Symmetric trees evaluate quickly, which helps in online inference.
They matter less with a large, mostly numeric dataset, where LightGBM's speed is often the deciding factor. The final chapter returns to this comparison.
Exercise
A teammate target-encodes the city column with pandas, using the mean label per city across the whole training set, and then passes the encoded column to CatBoost as a numeric feature. Training AUC is very high and validation AUC is much lower. Name the problem and give the fix in terms of CatBoost's design.
Show answer
The encoding uses each row's own label, so it leaks the target into the feature, and the model overfits to it. Pass city as the raw string column and list it in cat_features. CatBoost then computes ordered target statistics, where each row's encoding uses only the labels of rows earlier in a random permutation.
Exercise
Why can a symmetric tree of depth 6 be evaluated faster than a leaf-wise tree with 64 leaves, and what is the trade-off?
Show answer
Every node at one depth shares the same split condition, so the tree is 6 conditions. Their outcomes form a 6-bit index into an array of 64 leaf values, with no branching through nodes. The trade-off is that each tree is less flexible, so the model may need more iterations to reach the same training fit, though the constraint also acts as regularization.