Simple Algorithm
Machine Learning · Convergence · 26 min

XGBoost, LightGBM & CatBoost

Second-order splits, histograms and ordered boosting at scale.

The gradient boosting algorithm dates from 2001. What changed in the 2010s was engineering with real mathematics inside: a regularized second-order objective that scores every candidate split in closed form, histograms and gradient-based sampling that make split search cheap, and a fix for a subtle leak in how boosting reuses its own training data. This lesson derives the split gain, explains what XGBoost, LightGBM and CatBoost each changed, and separates speedups from changes to the statistics.

What you’ll learn

  • Derive XGBoost's optimal leaf weight wj∗=−Gj/(Hj+λ)w_j^*=-G_j/(H_j+\lambda), its structure score and its split gain, and explain sparsity-aware splits and the weighted quantile sketch.
  • Explain histogram-based split finding, LightGBM's gradient-based one-side sampling and exclusive feature bundling, and leaf-wise tree growth.
  • Explain target leakage in target statistics and the prediction shift of gradient boosting, and how CatBoost's ordered statistics and ordered boosting avoid them.
  • Choose and tune a modern boosting library sensibly, telling engineering approximations from changes to the estimator.

XGBoost: a regularized second-order objective

XGBoost (Chen & Guestrin, 2016) boosts regression trees fkf_k, each with TT leaves and leaf weights w∈RT\mathbf w\in\R^T, by minimizing a penalized objective ∑iℓ(yi,y^i)+∑kΩ(fk)\sum_i\ell(y_i,\hat y_i)+\sum_k\Omega(f_k) with Ω(f)=γT+12λ∥w∥2\Omega(f)=\gamma T+\tfrac12\lambda\norm{\mathbf w}^2. Round tt adds a tree ftf_t to the current predictions y^i(t−1)\hat y_i^{(t-1)}. Write gig_i and hih_i for the first and second derivatives of ℓ(yi,⋅)\ell(y_i,\cdot) at y^i(t−1)\hat y_i^{(t-1)}, and IjI_j for the examples that land in leaf jj.

DerivationOptimal leaf weights and the split gain
  1. L(t)≈∑i=1n[gift(xi)+12hift(xi)2]+γT+12λ∑j=1Twj2\mathcal L^{(t)}\approx\sum_{i=1}^n\Big[g_if_t(\mathbf x_i)+\tfrac12h_if_t(\mathbf x_i)^2\Big]+\gamma T+\tfrac12\lambda\sum_{j=1}^Tw_j^2

    Expand the loss to second order, as in Newton boosting, and drop the constant ∑iℓ(yi,y^i(t−1))\sum_i\ell(y_i,\hat y_i^{(t-1)}):

  2. L(t)≈∑j=1T[Gjwj+12(Hj+λ)wj2]+γT\mathcal L^{(t)}\approx\sum_{j=1}^T\Big[G_jw_j+\tfrac12(H_j+\lambda)w_j^2\Big]+\gamma T

    A tree is constant on each leaf, ft(xi)=wjf_t(\mathbf x_i)=w_j for i∈Iji\in I_j. Grouping by leaf, with Gj=∑i∈IjgiG_j=\sum_{i\in I_j}g_i and Hj=∑i∈IjhiH_j=\sum_{i\in I_j}h_i, the objective splits into independent one-dimensional quadratics:

  3. wj∗=−GjHj+λ,L(t)(q)=−12∑j=1TGj2Hj+λ+γTw_j^*=-\frac{G_j}{H_j+\lambda},\qquad\mathcal L^{(t)}(q)=-\frac12\sum_{j=1}^T\frac{G_j^2}{H_j+\lambda}+\gamma T

    Minimize each quadratic. The minimum value, the structure score, measures how good a tree shape is before its weights are even set:

  4. Gain=12[GL2HL+λ+GR2HR+λ−(GL+GR)2HL+HR+λ]−γ\text{Gain}=\frac12\Big[\frac{G_L^2}{H_L+\lambda}+\frac{G_R^2}{H_R+\lambda}-\frac{(G_L+G_R)^2}{H_L+H_R+\lambda}\Big]-\gamma

    Splitting one leaf into a left part LL and a right part RR changes the score by the gain, which scores any candidate split from four sums:

Reading the formulas: λ\lambda shrinks every leaf weight toward zero, most strongly where the curvature mass HjH_j is small, that is, in leaves with few examples or with confident predictions. γ\gamma is a price per leaf: a split survives only if it improves the structure score by more than γ\gamma. For squared loss, gi=y^i−yig_i=\hat y_i-y_i and hi=1h_i=1, so wj∗w_j^* is the leaf's residual sum divided by its size plus λ\lambda, a shrunken mean. For log loss, hi=pi(1−pi)h_i=p_i(1-p_i), and examples the model is already sure about barely count. XGBoost adds shrinkage (each new tree is scaled by a learning rate) and column subsampling on top.

Predict before you look

Squared loss: a leaf holds 4 examples whose residuals yi−y^iy_i-\hat y_i sum to 6. With λ=2\lambda=2, what weight does XGBoost give the leaf?

Show the answer

1

gi=y^i−yig_i=\hat y_i-y_i, so G=−6G=-6, and hi=1h_i=1, so H=4H=4. Then w∗=6/(4+2)=1.0w^*=6/(4+2)=1.0, against the plain mean residual of 1.51.5: the penalty acts like 2 extra examples with residual zero.

The system around these formulas mattered as much:

  • Split finding. The exact greedy method sorts each feature and scans all thresholds. The approximate method proposes candidate thresholds at quantiles of each feature, weighted by hih_i, because the second-order objective is a weighted squared loss, ∑i12hi(f(xi)+gi/hi)2\sum_i\tfrac12h_i\big(f(\mathbf x_i)+g_i/h_i\big)^2 plus a constant, in which hih_i plays the role of a weight. Chen & Guestrin designed a weighted quantile sketch with provable accuracy for this.
  • Sparsity-aware splits. For missing or zero entries, each split learns a default direction, trying both and keeping the better, so its cost grows only with the number of non-missing entries.
  • Systems design. Pre-sorted column blocks reused across rounds, cache-aware access, and out-of-core computation let one machine train on very large datasets.

LightGBM: histograms, one-side sampling and bundling

Histograms. Bucket each feature into a small number of bins once, before training. At a node, one pass over its examples accumulates the gradient and hessian sums per bin, and the best split is found by scanning the bins. Building the histograms costs O(#data×#features)\order{\#\text{data}\times\#\text{features}} and searching them O(#bins×#features)\order{\#\text{bins}\times\#\text{features}}, so the data pass dominates (Ke et al., 2017). Since a child's histogram is its parent's minus its sibling's, only the smaller child needs a pass. LightGBM attacks the two remaining factors, the number of examples and the number of features.

Predict before you look

GOSS runs with a=0.2a=0.2 and b=0.1b=0.1. By what factor are the sampled small-gradient examples amplified?

Show the answer

8 ×

(1−a)/b=0.8/0.1=8(1-a)/b=0.8/0.1=8: the 10% sample stands in for the 80% of examples outside the top 20%, so each sampled example counts eight times. Each tree is then built from 30% of the data.

Exclusive feature bundling (EFB). In sparse data many features are rarely nonzero at the same time: think of one-hot columns. Such features can share one histogram by offsetting their bins. Finding the fewest bundles is NP-hard, by reduction from graph coloring, so LightGBM bundles greedily, tolerating a small rate of conflicts.

Leaf-wise growth. Instead of growing a tree level by level, LightGBM repeatedly splits whichever leaf has the largest gain anywhere in the tree, up to a cap on the number of leaves. For a given number of leaves this tends to reduce the loss faster, but it can grow deep, lopsided trees that overfit small datasets, so a depth limit and a minimum number of examples per leaf matter. Ke et al. report speedups of up to more than 20 times over conventional gradient boosting at almost the same accuracy.

CatBoost: target leakage and ordered boosting

Trees need numbers to split on. One-hot encoding a categorical feature with thousands of levels creates thousands of sparse columns. A target statistic (TS) replaces each category by an estimate of the mean target within it, smoothed toward a prior value pp, often the overall mean target, with strength a>0a>0:

x^k=∑j1[xj=xk] yj+a p∑j1[xj=xk]+a\hat x_k=\frac{\sum_j\mathbf 1[x_j=x_k]\,y_j+a\,p}{\sum_j\mathbf 1[x_j=x_k]+a}
Ordering categories by their mean target, this statistic with a=0a=0, is also how CART finds the best binary split of a categorical feature (CART in Depth). Computed over the whole training set, this "greedy" TS is target encoding with a leak: example kk's own label sits inside its feature value.
Think first Every example has its own category, a customer ID, and the label is independent of it with P(y=1)=12P(y=1)=\tfrac12. What does the greedy TS do to the training set, and to new data?

Each training example gets x^k=(yk+ap)/(1+a)\hat x_k=(y_k+ap)/(1+a): positives and negatives take two different values, so one split at t=(0.5+ap)/(1+a)t=(0.5+ap)/(1+a) classifies the training set perfectly. A new example's ID was never seen, so its TS is the prior pp, and the model predicts the same class for everyone: 50% accuracy. Prokhorenkova et al. (2018) use this example to state the property a TS needs, P1: E(x^∣y=v)\E(\hat x\mid y=v) must be the same for training and test examples.

A holdout TS, computed on a separate part of the data, satisfies P1 but wastes data, violating P2: use all the training data both for the statistics and for the model. A leave-one-out TS, which drops example kk when computing x^k\hat x_k, looks like a fix, but it leaks too:

Predict before you look

A categorical feature takes the same value for all n=100n=100 training examples, 30 of them positive. A leave-one-out TS uses a=1a=1 and prior p=0.3p=0.3. Positive examples get (29+0.3)/(99+1)=0.293(29+0.3)/(99+1)=0.293. What value does each negative example get?

Show the answer

0.303

(30+0.3)/(99+1)=0.303(30+0.3)/(99+1)=0.303. Every negative example gets 0.303 and every positive one 0.293, so a split at 0.298 separates the training set perfectly, although the feature is constant and carries no information at all. Leaving out yky_k makes the statistic depend on yky_k in the opposite direction.

Ordered target statistics borrow from online learning. Draw a random permutation σ\sigma of the training examples and compute each example's TS only from the examples before it, {j:σ(j)<σ(k)}\{j:\sigma(j)<\sigma(k)\}; test examples use the whole training set. No label ever enters its own feature (P1), and every example contributes to the statistics of later ones and to training (P2). Early examples get noisy statistics, so CatBoost draws different permutations for different boosting rounds.

The cause is the same leak one level up: example kk's residual is computed from a model that was fitted using yky_k, so residuals on training points are distributed differently from residuals on new points. Ordered boosting computes each residual with a model that never saw that label: keep supporting models MiM_i trained on the first ii examples of the permutation, and take example kk's residual from Mσ(k)−1M_{\sigma(k)-1}. Done naively that means nn models; CatBoost shares tree structures across them and uses a few permutations, and offers this "Ordered" mode beside a "Plain" mode, which is standard gradient boosting with ordered target statistics.

CatBoost's base learners are oblivious trees: every node at a given depth uses the same split, so a depth-dd tree is a lookup table with 2d2^d cells, indexed by dd yes/no answers. Such trees are balanced, less prone to overfitting, and very fast at prediction time.

Check your understanding

Why does CatBoost compute a training example's target statistic only from the examples that precede it in a random permutation?

  1. To save memory, since only a prefix of the data is stored
  2. So that no example's own label enters its feature value, while every example still contributes to later statistics and to training
  3. Because the permutation sorts the examples by time, which target statistics require
  4. To make each training example's statistic equal to the one used at test time
Show the answer

B. So that no example's own label enters its feature value, while every example still contributes to later statistics and to training

Excluding the example itself is necessary (the greedy TS leaks), but leaving out only that one example is not enough (the leave-one-out TS leaks in reverse). Using only the "past" of a random order makes the statistic independent of the example's own label, as it will be for a test example, without holding out any data.

Choosing a library, and what really matters

AspectXGBoostLightGBMCatBoost
Tree growth (default)level by level; leaf-wise also availableleaf-wise (best-first)oblivious, symmetric trees
Split findingexact greedy, or candidates from quantiles or histogramshistograms of binned featuresbinned features
Signature ideasregularized second-order objective, sparsity-aware splits, weighted quantile sketchGOSS, exclusive feature bundlingordered target statistics, ordered boosting
Categorical featuresone-hot, or native support in recent versionsnative: categories grouped by gradient statisticsordered target statistics and feature combinations
As of the mid-2020s. All three keep evolving, and each now offers options the others pioneered.
python
import xgboost as xgb
import lightgbm as lgb

xgb_model = xgb.XGBClassifier(
    n_estimators=5000, learning_rate=0.05, max_depth=6,
    subsample=0.8, colsample_bytree=0.8,
    reg_lambda=1.0, gamma=0.0,             # the lambda and gamma of the split gain
    tree_method="hist", early_stopping_rounds=100, eval_metric="logloss",
)
xgb_model.fit(X_train, y_train, eval_set=[(X_val, y_val)], verbose=False)

lgb_model = lgb.LGBMClassifier(
    n_estimators=5000, learning_rate=0.05, num_leaves=31,   # leaf-wise growth
    min_child_samples=20, subsample=0.8, subsample_freq=1, colsample_bytree=0.8,
)
lgb_model.fit(X_train, y_train, eval_set=[(X_val, y_val)],
              callbacks=[lgb.early_stopping(stopping_rounds=100)])

A large cap on the number of trees and early stopping on a validation set, the recipe of Gradient Boosting. LightGBM's row subsampling needs subsample_freq > 0 to take effect.

Which ideas change the estimator, and which only make it faster? The second-order objective with λ\lambda and γ\gamma, minimum leaf sizes, row and column subsampling, oblivious trees and ordered statistics change what is learned. Histograms, quantile sketches, GOSS and feature bundling are approximations designed to learn nearly the same model much faster. No library wins on every dataset, so when accuracy matters, tune more than one, each with early stopping on the same validation folds.

Key takeaways

  • XGBoost minimizes a second-order expansion of the loss plus γT+12λ∥w∥2\gamma T+\tfrac12\lambda\norm{\mathbf w}^2: leaf weights −G/(H+λ)-G/(H+\lambda), structure score −12∑jGj2/(Hj+λ)+γT-\tfrac12\sum_jG_j^2/(H_j+\lambda)+\gamma T, and a closed-form split gain.
  • Weighted quantile sketches (weights hih_i), default directions for missing values, and cache-aware blocks let second-order tree boosting scale to very large datasets.
  • LightGBM speeds up split search with histograms, keeps all large-gradient examples and a reweighted sample of the rest (GOSS), bundles mutually exclusive sparse features, and grows trees leaf-wise.
  • Target statistics computed with an example's own label leak it; CatBoost uses ordered target statistics, ordered boosting against prediction shift, and oblivious trees.
  • Second-order steps, regularization, subsampling and leak-free encodings change the estimator; histograms, sketches, GOSS and bundling are approximations for speed whose effect on accuracy is usually small.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A leaf has gradient sum G=−12G=-12 and hessian sum H=8H=8, and λ=4\lambda=4. What weight does XGBoost assign it?

  1. 1.5
  2. 1.0
  3. −1.0
  4. 3.0
Show the answer

B. 1.0

w∗=−G/(H+λ)=12/12=1.0w^*=-G/(H+\lambda)=12/12=1.0. Without the penalty it would be 12/8=1.512/8=1.5; λ\lambda shrinks it, and more so when HH is small.

Question 2

What does XGBoost's parameter γ\gamma in Ω(f)=γT+12λ∥w∥2\Omega(f)=\gamma T+\tfrac12\lambda\norm{\mathbf w}^2 do?

  1. It is the learning rate applied to each new tree
  2. It shrinks each leaf weight toward zero in proportion to its size
  3. It sets the maximum depth of the trees
  4. It charges a fixed cost per leaf, so a split is kept only if it improves the structure score by more than γ\gamma
Show the answer

D. It charges a fixed cost per leaf, so a split is kept only if it improves the structure score by more than γ\gamma

Splitting one leaf into two adds one leaf, and the gain formula subtracts γ\gamma. Splits with gain below γ\gamma are not worth their complexity, which prunes the tree.

Question 3

Why does GOSS multiply the sampled small-gradient examples by (1−a)/b(1-a)/b?

  1. So that their gradient sums stay estimates of the sums over all small-gradient examples, keeping the gain estimates nearly unbiased
  2. To give badly fitted examples more weight
  3. To make the trees deeper
  4. Because examples with small gradients are more likely to be mislabeled
Show the answer

A. So that their gradient sums stay estimates of the sums over all small-gradient examples, keeping the gain estimates nearly unbiased

GOSS keeps every large-gradient example, the informative ones, and only a random fraction of the rest. Upweighting that fraction corrects for the subsampling, so the split gains are computed on approximately the original distribution of gradients.

Question 4

What is the "prediction shift" that CatBoost's ordered boosting removes?

  1. A drift in the test distribution after deployment
  2. The bias from a learning rate that is too large
  3. Residuals on training examples are computed with a model that was fitted on those same examples, so they are distributed differently from residuals on new examples, which biases the next trees
  4. The rounding error of histogram-based split finding
Show the answer

C. Residuals on training examples are computed with a model that was fitted on those same examples, so they are distributed differently from residuals on new examples, which biases the next trees

The model Ft−1F_{t-1} has seen yky_k, so Ft−1(xk)F_{t-1}(\mathbf x_k) is optimistic for training example kk in a way it is not for a fresh x\mathbf x. Ordered boosting computes each example's residual with a model trained only on examples that precede it in a random permutation.

Further reading

  • T. Chen & C. Guestrin, "XGBoost: a scalable tree boosting system," Proceedings of KDD, 785–794 (2016).
  • G. Ke, Q. Meng, T. Finley, T. Wang, W. Chen, W. Ma, Q. Ye & T.-Y. Liu, "LightGBM: a highly efficient gradient boosting decision tree," Advances in Neural Information Processing Systems 30, 3146–3154 (2017).
  • L. Prokhorenkova, G. Gusev, A. Vorobev, A. V. Dorogush & A. Gulin, "CatBoost: unbiased boosting with categorical features," Advances in Neural Information Processing Systems 31 (2018).
  • J. H. Friedman, "Greedy function approximation: a gradient boosting machine," Annals of Statistics 29(5), 1189–1232 (2001).