Sub topic 18
Choosing between LightGBM and CatBoost
This chapter assumes you can train both libraries with early stopping and know the main parameters from the earlier chapters. It gives a way to choose between them, and a way to check that choice on your own data.
Start from the data, not the brand
Both libraries implement gradient boosted decision trees. On clean numeric tables with a sound validation setup, they usually land within a small margin of each other. Your own validation score will matter more than any general ranking. The choice usually comes down to four practical factors:
- how many rows and columns you have,
- how much of the data is categorical, especially high-cardinality categories,
- how much time you can spend tuning,
- where the model will run in production.
What differs in practice
| Factor | LightGBM | CatBoost |
|---|---|---|
| Training speed on large data | Usually fastest, because of histogram binning and leaf-wise growth | Slower on CPU for the same number of trees, often much faster on GPU |
| Categorical features | Supported, but split search over categories can overfit on rare levels | Core strength. Ordered target statistics encode categories without target leakage |
| Default settings | Reasonable, but `num_leaves` and `min_data_in_leaf` often need tuning | Strong defaults. Often competitive with little tuning |
| Tree shape | Leaf-wise, asymmetric trees. High capacity, can overfit small data | Symmetric trees. More regularized, faster prediction |
| Small datasets | Needs care with `num_leaves` and `min_data_in_leaf` | Ordered boosting reduces prediction shift, which helps most on small data |
| Missing values | Learns a default direction per split | Treats missing values as a separate bucket, configured by `nan_mode` |
A decision path
The diagram turns the table into a first guess. Treat the result as the model you try first. You still need to measure.
Rules of thumb and their limits
Choose CatBoost first when:
- Columns like
city,user_idorproduct_codecarry real signal. CatBoost encodes each category using only the rows that come before it in a random permutation. The row's own label is never part of its encoding, so the model does not leak the target. - The dataset is small or medium (thousands to a few hundred thousand rows), where prediction shift and overfitting hurt most.
- You want a good model quickly with default parameters.
- Low-latency prediction matters. Symmetric trees evaluate quickly.
Choose LightGBM first when:
- You have millions of rows and training time is the bottleneck.
- Your features are mostly numeric, or categories have few levels.
- You can afford a tuning search. Leaf-wise growth gives you a high-capacity model, and
num_leaveslets you control it. - You need the ecosystem around it, such as integrations your team already runs.
Where the rules break:
- LightGBM with well-prepared categories (frequency encoding, target encoding done inside cross-validation folds) can match CatBoost. Preparing them costs you engineering time.
- CatBoost with many high-cardinality columns and a large dataset can train slowly on CPU. Then the speed argument for LightGBM wins.
- Feature interactions of categories are built automatically in CatBoost. That helps accuracy but increases training time and memory.
Measure it: a fair comparison
A fair comparison needs the same rows, the same metric, the same early stopping patience, and a held-out test set that neither model used for stopping. The script below builds a table with a 200-level categorical column and compares both libraries. It uses a three-way split: train, a validation set for early stopping, and a test set for the final score.
import time
import numpy as np
import pandas as pd
import lightgbm as lgb
from catboost import CatBoostClassifier
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 20000
df = pd.DataFrame({
"age": rng.integers(18, 70, n),
"city": rng.choice([f"c{i}" for i in range(200)], n),
"plan": rng.choice(["free", "basic", "pro"], n),
})
signal = (df["plan"] == "pro") | (df["age"] > 55)
y = (signal ^ (rng.random(n) < 0.1)).astype(int).to_numpy()
idx = np.arange(n)
idx_train, idx_rest = train_test_split(idx, test_size=0.4, random_state=0)
idx_valid, idx_test = train_test_split(idx_rest, test_size=0.5, random_state=0)
cat_cols = ["city", "plan"]
df_lgb = df.astype({c: "category" for c in cat_cols})
# LightGBM: pandas category columns are used as categorical features.
t0 = time.perf_counter()
lgb_model = lgb.LGBMClassifier(
n_estimators=2000, learning_rate=0.05, num_leaves=31, verbose=-1
)
lgb_model.fit(
df_lgb.iloc[idx_train], y[idx_train],
eval_set=[(df_lgb.iloc[idx_valid], y[idx_valid])],
eval_metric="auc",
callbacks=[lgb.early_stopping(50, verbose=False)],
)
lgb_time = time.perf_counter() - t0
lgb_auc = roc_auc_score(
y[idx_test], lgb_model.predict_proba(df_lgb.iloc[idx_test])[:, 1]
)
# CatBoost: raw string columns are declared in cat_features.
t0 = time.perf_counter()
cb_model = CatBoostClassifier(
iterations=2000, learning_rate=0.1, eval_metric="AUC",
cat_features=cat_cols, verbose=0,
)
cb_model.fit(
df.iloc[idx_train], y[idx_train],
eval_set=(df.iloc[idx_valid], y[idx_valid]),
early_stopping_rounds=50,
)
cb_time = time.perf_counter() - t0
cb_auc = roc_auc_score(
y[idx_test], cb_model.predict_proba(df.iloc[idx_test])[:, 1]
)
print(f"LightGBM: test AUC {lgb_auc:.4f}, {lgb_time:.1f}s, "
f"{lgb_model.best_iteration_} trees")
print(f"CatBoost: test AUC {cb_auc:.4f}, {cb_time:.1f}s, "
f"{cb_model.get_best_iteration()} trees")Exact numbers depend on your machine and library versions. Compare the AUC gap against the noise between runs before you trust it.
Common errors when comparing
- Scoring on the early-stopping set. The validation set picks the number of trees, so its score is slightly optimistic. The script above reports on a separate test set.
- Comparing at different learning rates without noticing. The learning rate sets how many trees you need. Judge each model at its own tuned or default setting, and report the setting.
- Comparing a tuned model to a default one. Give both a similar tuning budget, or label the comparison as default versus default.
- Encoding categories by hand for CatBoost. Pre-encoded labels destroy the benefit of ordered target statistics. Pass raw categories and name them in
cat_features. - Judging from one random split. Repeat with several seeds or use cross-validation. For time-ordered data, use a time-based split for both models.
- Ignoring inference cost. Measure prediction latency and model size on your serving hardware. Training time alone can mislead.
A short checklist
- Count high-cardinality categorical columns and the number of rows.
- Train both libraries with defaults on the same split, with early stopping.
- Score both on a held-out test set. Repeat across seeds.
- Tune the leading model with a fixed budget, and give the other the same budget.
- Check training time, prediction latency and model size.
- Pick the model, or blend both if the gain justifies serving two models.
Exercise
A table has 3 million rows, 40 numeric columns and 2 categorical columns with 5 levels each. Training time is the main constraint, and you have a modest tuning budget. Which library do you try first, and what would make you switch?
Show answer
Try LightGBM first. The data is large and mostly numeric, and the categories are low-cardinality, so LightGBM's histogram binning and leaf-wise growth give fast training and the categories are not a problem. Tune num_leaves, min_data_in_leaf and learning_rate. Switch, or add CatBoost to a blend, if a held-out test set shows CatBoost scoring clearly higher beyond seed noise. The same applies if the categorical columns turn out to have many more levels than expected, or if prediction latency matters and CatBoost's symmetric trees serve faster.
Exercise
A colleague one-hot encodes a 500-level store_id column and then passes the result to CatBoost, saying CatBoost is "no better than LightGBM here". What went wrong with the comparison?
Show answer
One-hot encoding replaces the single categorical column with 500 sparse binary columns. CatBoost can no longer apply ordered target statistics to it, which is its main advantage on categorical data. The fix is to pass the raw store_id column and list it in cat_features, then compare again on the same split and with the same early stopping rules.