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 , 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 , each with leaves and leaf weights , by minimizing a penalized objective with . Round adds a tree to the current predictions . Write and for the first and second derivatives of at , and for the examples that land in leaf .
Expand the loss to second order, as in Newton boosting, and drop the constant :
A tree is constant on each leaf, for . Grouping by leaf, with and , the objective splits into independent one-dimensional quadratics:
Minimize each quadratic. The minimum value, the structure score, measures how good a tree shape is before its weights are even set:
Splitting one leaf into a left part and a right part changes the score by the gain, which scores any candidate split from four sums:
Reading the formulas: shrinks every leaf weight toward zero, most strongly where the curvature mass is small, that is, in leaves with few examples or with confident predictions. is a price per leaf: a split survives only if it improves the structure score by more than . For squared loss, and , so is the leaf's residual sum divided by its size plus , a shrunken mean. For log loss, , 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.
Squared loss: a leaf holds 4 examples whose residuals sum to 6. With , what weight does XGBoost give the leaf?
Show the answer
1
, so , and , so . Then , against the plain mean residual of : 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 , because the second-order objective is a weighted squared loss, plus a constant, in which 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 and searching them , 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.
GOSS runs with and . By what factor are the sampled small-gradient examples amplified?
Show the answer
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 , often the overall mean target, with strength :
Think first Every example has its own category, a customer ID, and the label is independent of it with . What does the greedy TS do to the training set, and to new data?
Each training example gets : positives and negatives take two different values, so one split at classifies the training set perfectly. A new example's ID was never seen, so its TS is the prior , 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: 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 when computing , looks like a fix, but it leaks too:
A categorical feature takes the same value for all training examples, 30 of them positive. A leave-one-out TS uses and prior . Positive examples get . What value does each negative example get?
Show the answer
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 makes the statistic depend on in the opposite direction.
Ordered target statistics borrow from online learning. Draw a random permutation of the training examples and compute each example's TS only from the examples before it, ; 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 's residual is computed from a model that was fitted using , 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 trained on the first examples of the permutation, and take example 's residual from . Done naively that means 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- tree is a lookup table with cells, indexed by yes/no answers. Such trees are balanced, less prone to overfitting, and very fast at prediction time.
Why does CatBoost compute a training example's target statistic only from the examples that precede it in a random permutation?
- To save memory, since only a prefix of the data is stored
- So that no example's own label enters its feature value, while every example still contributes to later statistics and to training
- Because the permutation sorts the examples by time, which target statistics require
- 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
| Aspect | XGBoost | LightGBM | CatBoost |
|---|---|---|---|
| Tree growth (default) | level by level; leaf-wise also available | leaf-wise (best-first) | oblivious, symmetric trees |
| Split finding | exact greedy, or candidates from quantiles or histograms | histograms of binned features | binned features |
| Signature ideas | regularized second-order objective, sparsity-aware splits, weighted quantile sketch | GOSS, exclusive feature bundling | ordered target statistics, ordered boosting |
| Categorical features | one-hot, or native support in recent versions | native: categories grouped by gradient statistics | ordered target statistics and feature combinations |
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 and , 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 : leaf weights , structure score , and a closed-form split gain.
- Weighted quantile sketches (weights ), 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.
A leaf has gradient sum and hessian sum , and . What weight does XGBoost assign it?
- 1.5
- 1.0
- −1.0
- 3.0
Show the answer
B. 1.0
. Without the penalty it would be ; shrinks it, and more so when is small.
What does XGBoost's parameter in do?
- It is the learning rate applied to each new tree
- It shrinks each leaf weight toward zero in proportion to its size
- It sets the maximum depth of the trees
- It charges a fixed cost per leaf, so a split is kept only if it improves the structure score by more than
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
Splitting one leaf into two adds one leaf, and the gain formula subtracts . Splits with gain below are not worth their complexity, which prunes the tree.
Why does GOSS multiply the sampled small-gradient examples by ?
- So that their gradient sums stay estimates of the sums over all small-gradient examples, keeping the gain estimates nearly unbiased
- To give badly fitted examples more weight
- To make the trees deeper
- 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.
What is the "prediction shift" that CatBoost's ordered boosting removes?
- A drift in the test distribution after deployment
- The bias from a learning rate that is too large
- 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 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 has seen , so is optimistic for training example in a way it is not for a fresh . 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).