Gradient-boosted trees (GBDT)

In one sentence

Build hundreds of small decision trees in sequence, each one fitting the errors the ensemble still makes; on tabular data XGBoost and LightGBM remain the default to beat.

Analogy: Golf: the first shot lands near the hole, each next shot is a short correction from where the ball stopped, and you swing softly (learning rate) so you don't overshoot.

Each round fits a small tree to what the ensemble still gets wrong; early stopping on validation data decides when to stop.

How it works

  • Each new tree fits the negative gradient of the loss; for squared error that is the residual y − ŷ.
  • Shrink each tree by the learning rate (0.01–0.1) and let early stopping pick how many trees.
  • They win on tabular data: no scaling, native missing values, sharp irregular boundaries, minutes on a CPU.
  • XGBoost adds second-order gradients; LightGBM uses histograms and leaf-wise growth; CatBoost handles categories natively.
  • Explain predictions with SHAP, not split counts.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your LightGBM demand model was trained on prices from $5 to $100. Pricing asks what happens at $300; the model predicts the same demand as at $100. What's going on?

Go deeper

Full explanation

A decision tree splits rows on feature thresholds (amount > 500?, country = BR?) until each leaf holds similar targets. One tree is weak and unstable; gradient boosting adds many small ones, sequentially:

  1. Start from a constant: the mean, or the base-rate log-odds.
  2. For each row, compute the negative gradient of the loss. For squared error it is just the residual y − ŷ; for log loss, y − p.
  3. Fit a shallow tree to those gradients and add it, shrunk by the learning rate: F ← F + η · tree.
  4. Repeat hundreds to thousands of times; early stopping on a validation set picks how many.

Each tree fixes what the ensemble still gets wrong. XGBoost adds second-order gradients and leaf-weight regularization; LightGBM uses histogram bins and leaf-wise growth for speed; CatBoost handles categories with ordered target statistics.

Why they still win on tabular data: no scaling, native missing values, robust to useless columns, and they fit the sharp, irregular boundaries that neural nets tend to smooth over, in minutes on a CPU.

Knobs: learning rate (0.01–0.1) × number of trees (via early stopping), depth or num_leaves, min samples per leaf, row and column subsampling. Explain predictions with SHAP, not split counts.

Code LightGBM with early stopping, then SHAP
pythonLightGBM with early stopping, then SHAP
import lightgbm as lgb
import shap

X_tr, y_tr, X_va, y_va = time_split(load_transactions())  # validate on the latest weeks

model = lgb.LGBMClassifier(
    n_estimators=5000,          # a cap: early stopping picks the real number
    learning_rate=0.05,         # smaller steps -> more trees, better generalization
    num_leaves=63,              # main complexity knob (leaf-wise growth)
    min_child_samples=100,      # no leaf fitted on a handful of rows
    subsample=0.8, subsample_freq=1,  # row bagging every iteration
    colsample_bytree=0.8,       # feature bagging per tree
    reg_lambda=1.0,             # L2 penalty on leaf weights
)
model.fit(
    X_tr, y_tr,
    eval_set=[(X_va, y_va)], eval_metric="average_precision",
    callbacks=[lgb.early_stopping(100), lgb.log_evaluation(200)],
)
print("trees kept:", model.best_iteration_)

# Exact per-prediction attributions for trees (TreeSHAP), not split counts
explanation = shap.TreeExplainer(model)(X_va.iloc[:2000])
shap.plots.beeswarm(explanation)       # global: which features matter, which direction
shap.plots.waterfall(explanation[0])   # local: why this one transaction scored high
Real example

A payments team predicts fraud on 40M card transactions with ~300 engineered features: amount, merchant category, card velocity over 1h and 24h, device age. A tuned MLP reaches PR-AUC 0.58 after a week of work; LightGBM with near-default settings reaches 0.66 in 25 minutes on one CPU machine, early-stopping at tree 1,840. TreeSHAP then gives analysts the top reasons behind every blocked payment, e.g. "6 transactions in the last hour, device seen for the first time".

Trade-offs +3 · −3

+ You gain

  • Best out-of-the-box accuracy on tabular data, with little preprocessing: no scaling, native missing values.
  • Trains in minutes on CPUs; scoring a row is a few thousand comparisons, cheap to serve.
  • Explainable enough for risk teams: TreeSHAP gives exact per-prediction attributions.

− You pay

  • Can't learn representations from raw text, images or sequences; it needs engineered features or embeddings as input.
  • No extrapolation: predictions are piecewise constant and flat beyond the training range.
  • Billion-row sparse ID data favors learned embeddings; trees are also hard to update online.

Use it when

Structured problems such as fraud, credit risk, churn, pricing, CTR baselines and feature-based ranking, from thousands to hundreds of millions of rows. Start here before any neural net.

Avoid it when

Raw text, images or audio; long sequences where order matters; or billion-scale sparse IDs where embeddings and end-to-end training win.

Numbers to know 5
  • XGBoost paper (2016): 17 of the 29 Kaggle challenge-winning solutions published in 2015 used XGBoost.
  • Grinsztajn et al. (NeurIPS 2022): on 45 datasets, trees still beat deep nets on medium-sized tabular data (~10K rows).
  • Defaults: XGBoost learning rate 0.3, max_depth 6; LightGBM learning rate 0.1, num_leaves 31. Rule of thumb: 0.01–0.1 plus early stopping.
  • LightGBM (NeurIPS 2017) reported up to 20×+ faster training than conventional GBDT at almost the same accuracy.
  • Facebook ads (He et al., 2014): boosted trees as feature transforms plus logistic regression beat either alone by over 3%.
Common pitfalls 4
  • Setting n_estimators by hand instead of a high cap plus early stopping on a time-based validation set, never the test set.
  • Trusting gain or split-count importance: it is biased toward high-cardinality features. Use SHAP or permutation importance.
  • Expecting extrapolation: a demand model trained on prices up to $100 predicts flat at $300.
  • One-hot encoding thousands of categories; use native categorical support (LightGBM, CatBoost) or out-of-fold target encoding.
Interview questions 3

Answer out loud first, then reveal.

Why do GBDTs still beat deep learning on tabular data, and when would you switch?Show answer

Tabular features are heterogeneous (amounts, counts, categories) and the target is often a sharp, irregular function of a few of them. Trees split on thresholds, so they ignore scale and useless columns and capture those cliffs, while MLPs tend to learn overly smooth functions; Grinsztajn et al. showed this across 45 datasets. I'd switch to, or add, a neural net for raw text, images or sequences, for high-cardinality IDs that need learned embeddings at billions of rows, as in large ads and feed systems, or for one multi-task model. Even then the GBDT is my baseline: Airbnb documented a long series of attempts before deep learning beat its tuned GBDT search ranker.

Random forest or gradient boosting?Show answer

Both are tree ensembles, but they attack different errors. A random forest trains deep trees independently on bootstrap samples and averages them, which cuts variance: more trees never hurts, it parallelizes trivially and needs almost no tuning. Boosting trains shallow trees sequentially on the ensemble's gradients, which cuts bias, so it is usually more accurate but can overfit with too many trees or too high a learning rate, and needs early stopping. I use a random forest as a two-minute baseline and a tuned LightGBM or XGBoost for production.

Feature importance says `user_id` is your top feature. What do you do?Show answer

I distrust it twice. Gain and split-count importances favor high-cardinality features because they offer more split points, so an ID can look important just by memorizing training users. And if it truly drives predictions, the model is memorizing, not generalizing, and it will fail on new users. I'd check SHAP and permutation importance on a time-based validation set, replace the raw ID with point-in-time aggregates such as the user's historical rates, and confirm the score improves on users the model never saw.