TExcelTAD

LightGBM and CatBoost

XGBoost has two strong rivals built on the same Newton-boosting core. LightGBM (Microsoft, 2017) is about speed: it bins features into histograms and grows trees leaf by leaf, so it trains on millions of rows in minutes. CatBoost (Yandex, 2018) is about categorical features: it encodes them with target statistics computed in a way that does not leak the label. LightGBM runs in your browser; CatBoost does not, so its example is recorded from a real run.

LightGBM's two ideas

Histogram splits. Exact split search sorts every feature and tries every cut: n−1n - 1 candidates per feature per node. LightGBM first cuts each feature into at most 255 bins (by quantiles), then per node adds up the gradients and hessians in each bin and tries only the bin edges. The cost of a split search drops from O(n)O(n) to O(bins)O(\text{bins}) after one pass to fill the histogram, and a child's histogram can be computed as the parent's minus its sibling's. The loss in precision is tiny:

python · try it yourself
import numpy as np
import pandas, sklearn                                 # load these before LightGBM (see the XGBoost lesson)
import lightgbm as lgb

rng = np.random.default_rng(0)
n = 100_000
x = rng.normal(size=n)
y = np.where(x > 0.3, 1.0, 0.0) + rng.normal(scale=0.5, size=n)
g = 0 - y                                              # gradients at prediction 0 (squared error)

def split_gain(GL, NL, G, N):
    GR, NR = G - GL, N - NL
    return GL ** 2 / NL + GR ** 2 / NR - G ** 2 / N

# exact: sort all n values and try every cut
order = np.argsort(x)
GL = np.cumsum(g[order])[:-1]; NL = np.arange(1, n)
i = np.argmax(split_gain(GL, NL, g.sum(), n))
print(f"exact split:     x <= {(x[order][i] + x[order][i + 1]) / 2:.4f}  ({n - 1} candidate cuts)")

# histogram: 255 quantile bins, sum the gradients per bin, try only the 254 bin edges
edges = np.quantile(x, np.linspace(0, 1, 256)[1:-1])
bins = np.searchsorted(edges, x, side="left")
G_bin = np.bincount(bins, weights=g, minlength=255)
N_bin = np.bincount(bins, minlength=255)
GLh, NLh = np.cumsum(G_bin)[:-1], np.cumsum(N_bin)[:-1]
k = np.argmax(split_gain(GLh, NLh, g.sum(), n))
print(f"histogram split: x <= {edges[k]:.4f}  (254 candidate cuts)")

model = lgb.LGBMRegressor(n_estimators=1, num_leaves=2, learning_rate=1.0, min_child_samples=1,
                          verbose=-1, n_jobs=1).fit(x[:, None], y)
print(f"LightGBM split:  x <= {model.booster_.dump_model()['tree_info'][0]['tree_structure']['threshold']:.4f}")
exact split:     x <= 0.3001  (99999 candidate cuts)
histogram split: x <= 0.2969  (254 candidate cuts)
LightGBM split:  x <= 0.2969

With 254 candidates instead of 99 999 the split lands at 0.2969 instead of 0.3001, both next to the true step at 0.3, and LightGBM's own binning picks the same bin edge as the hand-made histogram. The split score here is the gain formula of the XGBoost lesson with h=1h = 1 and λ=0\lambda = 0.

Leaf-wise growth. XGBoost and scikit-learn grow a tree level by level (depth-wise). LightGBM always splits the leaf with the largest gain anywhere in the tree (best-first), so the tree size is controlled by num_leaves rather than depth. For the same number of leaves, leaf-wise trees reach a lower loss, but they can grow deep and narrow on small data, so min_child_samples (minimum rows per leaf) and max_depth act as brakes. A depth-wise tree of depth DD has up to 2D2^D leaves; the LightGBM documentation suggests keeping num_leaves below 2max_depth2^{\text{max\_depth}}.

LightGBM also has gradient-based one-side sampling (keep rows with large gradients, sample the rest) and exclusive feature bundling (merge sparse features that are never non-zero together), both for speed on large data.

Categorical features

A city column with 40 values can be one-hot encoded (40 sparse columns), integer-coded (an arbitrary order), or handled natively. LightGBM's native mode sorts the categories at each node by their mean gradient statistic and then finds the best split of that ordering, so one split can group any subset of cities. The example generates a churn table in which each of 40 cities has its own churn level, and compares native categories with integer codes under 5-fold cross-validation:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.model_selection import cross_val_score, StratifiedKFold
from sklearn.metrics import roc_auc_score
import lightgbm as lgb

def make_churn(n=3000, seed=0):
    """A generated customer table: 40 cities with their own churn level, a plan, tenure and charges."""
    rng = np.random.default_rng(seed)
    city_effect = rng.normal(scale=1.0, size=40)
    city = rng.integers(0, 40, n)
    plan = rng.choice(["basic", "plus", "pro"], n, p=[0.5, 0.3, 0.2])
    tenure = rng.integers(1, 72, n)
    charge = rng.normal(60, 20, n).clip(10, None)
    z = -1 + city_effect[city] - 0.04 * tenure + 0.02 * (charge - 60) + np.where(plan == "basic", 0.5, 0)
    p_true = 1 / (1 + np.exp(-z))
    churn = (rng.random(n) < p_true).astype(int)
    df = pd.DataFrame({"city": pd.Categorical([f"c{c:02d}" for c in city]), "plan": pd.Categorical(plan),
                       "tenure": tenure, "charge": charge.round(2)})
    return df, churn, p_true

X, y, p_true = make_churn()
print(X.head(3).to_string())
print("churn rate:", round(y.mean(), 3), " AUC of the true probabilities (the ceiling):", round(roc_auc_score(y, p_true), 3))
cv = StratifiedKFold(5, shuffle=True, random_state=0)
params = dict(n_estimators=200, learning_rate=0.05, num_leaves=15, min_child_samples=20, verbose=-1, n_jobs=1, random_state=0)
codes = X.assign(city=X.city.cat.codes, plan=X.plan.cat.codes)   # the same cities as plain integers 0-39
for name, data in [("categorical (native)", X), ("integer codes", codes)]:
    s = cross_val_score(lgb.LGBMClassifier(**params), data, y, cv=cv, scoring="roc_auc")
    print(f"{name:21s} CV ROC AUC {s.mean():.3f}")
  city   plan  tenure  charge
0  c26  basic      14   50.38
1  c22  basic      14   57.59
2  c10    pro      69   56.13
churn rate: 0.144  AUC of the true probabilities (the ceiling): 0.776
categorical (native)  CV ROC AUC 0.733
integer codes         CV ROC AUC 0.726

Because the data is generated, the true churn probability of every customer is known, and ranking customers by it gives an AUC of 0.776: no model can expect to do better (churn is random even when the probability is known). Native categories reach 0.733, integer codes 0.726. The gap is small here because trees can still carve integer codes into groups with several splits; it grows with the number of categories. A column given as pandas category dtype is used natively; integer columns are treated as numbers unless listed in categorical_feature.

CatBoost: ordered target statistics

The obvious encoding of a category for a model is its target mean: replace "city c26" by the churn rate of c26 customers. Computed on the full training set, it leaks: each row's own label is in its own encoding, so rare categories look perfectly predictive. CatBoost computes the encoding for each row from the rows before it in a random permutation only (an ordered target statistic), smoothed towards the overall rate with a prior aa and weight PP:

x^i=∑j<i, cj=ciyj+aP#{j<i:cj=ci}+a\hat{x}_{i} = \frac{\sum_{j < i,\ c_j = c_i} y_j + a P}{\#\{j < i : c_j = c_i\} + a}

The same "past only" idea, called ordered boosting, is used for the residuals. CatBoost also grows oblivious trees: every node at the same depth uses the same split, so a depth-4 tree is a lookup table of 16 cells, fast to evaluate and naturally regularised. It also builds combinations of categorical features automatically.

This example is recorded (CatBoost does not run in the browser). It trains CatBoost on the raw city and plan strings and LightGBM with native categories on the same split:

python · try it yourself
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import roc_auc_score
import lightgbm as lgb
from catboost import CatBoostClassifier

def make_churn(n=3000, seed=0):
    """The same generated customer table as in the LightGBM example."""
    rng = np.random.default_rng(seed)
    city_effect = rng.normal(scale=1.0, size=40)
    city = rng.integers(0, 40, n)
    plan = rng.choice(["basic", "plus", "pro"], n, p=[0.5, 0.3, 0.2])
    tenure = rng.integers(1, 72, n)
    charge = rng.normal(60, 20, n).clip(10, None)
    z = -1 + city_effect[city] - 0.04 * tenure + 0.02 * (charge - 60) + np.where(plan == "basic", 0.5, 0)
    churn = (rng.random(n) < 1 / (1 + np.exp(-z))).astype(int)
    df = pd.DataFrame({"city": [f"c{c:02d}" for c in city], "plan": plan,
                       "tenure": tenure, "charge": charge.round(2)})
    return df, churn

X, y = make_churn()
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=0, stratify=y)

cat = CatBoostClassifier(iterations=300, learning_rate=0.05, depth=4, cat_features=["city", "plan"],
                         random_seed=0, verbose=0, thread_count=1, allow_writing_files=False)
cat.fit(X_tr, y_tr)                                    # raw strings: CatBoost encodes them itself
print("CatBoost  test ROC AUC:", round(roc_auc_score(y_te, cat.predict_proba(X_te)[:, 1]), 3))

to_cat = lambda d: d.astype({"city": "category", "plan": "category"})
lgbm = lgb.LGBMClassifier(n_estimators=200, learning_rate=0.05, num_leaves=15, verbose=-1, n_jobs=1, random_state=0)
lgbm.fit(to_cat(X_tr), y_tr)
print("LightGBM  test ROC AUC:", round(roc_auc_score(y_te, lgbm.predict_proba(to_cat(X_te))[:, 1]), 3))
print(cat.get_feature_importance(prettified=True).round(1).to_string(index=False))
CatBoost  test ROC AUC: 0.713
LightGBM  test ROC AUC: 0.701
Feature Id  Importances
    tenure         36.2
      city         30.4
    charge         21.2
      plan         12.2

On this split of 750 test customers CatBoost is slightly ahead (0.713 against 0.701 ROC AUC), with default settings and no encoding work. One split is a noisy comparison; the comparison bench shows how to compare models properly. CatBoost's importances (the share of the loss reduction due to each feature) put tenure and city first, matching how the data was generated.

XGBoost, LightGBM or CatBoost?

XGBoost LightGBM CatBoost
tree growth depth-wise (or lossguide) leaf-wise oblivious (symmetric)
speed on large data fast (hist) fastest slower to train, very fast to predict
categorical features supported, newer native, mature best: ordered target statistics
defaults need some tuning need num_leaves/min_child_samples care on small data strong out of the box
main knobs max_depth, min_child_weight, eta num_leaves, min_child_samples, learning_rate depth, learning_rate, l2_leaf_reg

All three are within noise of each other on most tabular problems once tuned. Choose by your data (many categorical columns: CatBoost; very large data: LightGBM), your deployment needs and what your team knows. scikit-learn's HistGradientBoostingClassifier follows LightGBM's design and is a good dependency-free choice.

Pitfalls

  • Leaf-wise trees on small data. A large num_leaves with the default min_child_samples=20 can still overfit a few thousand rows; lower num_leaves or raise min_child_samples.
  • Target encoding by hand on the full data. It leaks the label into the features. Use CatBoost, or target encoding fitted inside cross-validation folds (Data Preparation).
  • Unseen categories at prediction time. LightGBM sends them with the "other" side of the split; check how your library treats them before you deploy.

Practice

  1. A tree has max_depth=5. What is the largest num_leaves that makes sense, and why does LightGBM suggest staying below it?
Answer

25=322^5 = 32 leaves. A leaf-wise tree with 32 leaves and no depth limit could put most of them on one deep path; staying below 2max_depth2^{\text{max\_depth}} keeps the tree from being more complex than the depth-wise tree it is compared with.

  1. A city appears in 2 training rows, both churned. What does a plain target-mean encoding give it, and why is that a problem?
Answer

1.0, a perfect churn signal based on two rows whose own labels produced it. The model learns "this city always churns" from the encoding itself: leakage. Smoothing towards the overall rate and the ordered (past-only) computation both prevent it.

Test yourself

What makes LightGBM's split search fast?

  1. It uses oblivious trees
  2. It bins features into histograms and only tries bin edges
  3. It skips categorical features
  4. It uses linear models in the leaves

What does leaf-wise (best-first) growth do?

  1. Splits every node at the same depth
  2. Always splits the leaf with the largest gain, wherever it is
  3. Uses the same split for every node at a level
  4. Grows one tree per class

Why does CatBoost compute target statistics only from earlier rows in a permutation?

  1. To save memory
  2. So a row's own label never contributes to its encoding, which avoids leakage
  3. Because categories are sorted
  4. To make trees symmetric