◆ AI All-in-One

Level 3 In-Depth AI · Classical Machine Learning

Gradient Boosting: XGBoost and LightGBM

Build a model as a sum of many small decision trees, each trained to fix the mistakes of the ones before it. It is gradient descent where each step is a tree, and it is still the method to beat on tabular data.

Level
●●●●● Intermediate
Reading
13 min
To learn it well
1 hour to read, an afternoon to practise
↗ Plan a path here

Read first

Decision TreesGradient Descent

This leads to

—
The full path from zero — 12 concepts before this one
  1. What Is AI?
  2. Probability Basics
  3. Derivatives and Slopes
  4. Vectors
  5. How Machines Learn
  6. Probability Distributions
  7. Partial Derivatives and Gradients
  8. Supervised, Unsupervised and Reinforcement Learning
  9. Entropy, Cross-Entropy and KL Divergence
  10. Gradient Descent
  11. Supervised Learning
  12. Decision Trees
  13. Gradient Boosting: XGBoost and LightGBM

Read them roughly in this order. See it on the concept map →

Why it matters

If your data lives in a table (customers and their purchases, loans and their outcomes, sensors and their readings), the model most likely to give the best accuracy is a gradient-boosted tree ensemble. As of late 2026 this is still the standard default despite a decade of deep learning, although pretrained tabular foundation models such as TabPFN now match or beat tuned boosted trees on many benchmark datasets, especially small and medium-sized ones. A widely cited 2022 study by Grinsztajn, Oyallon and Varoquaux, Why do tree-based models still outperform deep learning on tabular data?, found tree ensembles ahead of neural networks on typical medium-sized tabular benchmarks. Gradient boosting libraries have won a large share of Kaggle competitions on tabular data since about 2014, and they run fraud detection, credit scoring, search ranking and demand forecasting at many large companies.

The three libraries you will meet are XGBoost, LightGBM and CatBoost. scikit-learn has its own fast version, HistGradientBoostingClassifier, modelled on LightGBM.

Gradient boosting is also a lovely idea. It takes Gradient Descent, which nudges numbers downhill, and applies it to functions, adding a small tree at each step.

The intuition

Imagine a team of mediocre golfers playing one ball. The first player hits it roughly towards the hole. The second doesn't start from the tee. They walk to where the ball landed and hit from there, aiming to fix what the first player left. The third fixes what's left after that. No single player is good, but each only has to correct the remaining error, and that error shrinks with every shot.

Gradient boosting works the same way:

  1. Start with a very simple guess, such as the average of the targets.
  2. Look at the errors (the residuals: true value minus prediction).
  3. Train a small tree to predict those residuals.
  4. Add a fraction of that tree's output to the model. The errors shrink.
  5. Repeat hundreds or thousands of times.
after 1 tree training MSE 5.12 after 10 trees training MSE 1.57 after 100 trees training MSE 0.14 model prediction (sum of trees so far) training data each tree: depth 2, η = 0.1
Fig. 1 Gradient boosting fitting a wavy curve with depth-2 trees and learning rate 0.1. After one tree the model is almost flat. After ten it has the rough shape. After a hundred it follows the data closely. Each tree only had to fix what the trees before it got wrong.

This is very different from a random forest. A forest grows deep trees independently and averages them to cancel their variance. Boosting grows shallow trees in sequence, each one depending on all the previous ones, to cut bias.

Bagging / random forest trees built independently, in parallel data tree 1 tree 2 tree 3 average or vote each tree: deep, on a bootstrap sample · goal: cancel out variance Boosting trees built one after another, each fixing the errors left so far start: average y tree 1 fits the errors errors tree 2 fits the errors errors tree 3 fits the errors … sum: F₀ + η·(t₁+t₂+…) each tree: shallow (weak), trained on what the model so far gets wrong · goal: cut bias η (learning rate) shrinks every tree's contribution so no single tree overcorrects
Fig. 2 Bagging versus boosting. In a random forest, deep trees are trained in parallel on resampled data and averaged. In boosting, shallow trees are trained one after another, each on the errors the model still makes, and their outputs are added up, each shrunk by the learning rate.

Key idea Gradient boosting builds a model as a sum of small trees. Each new tree is trained to predict the current errors of the sum so far, and is added with a small weight (the learning rate). It is gradient descent, with trees as the steps.

How it works

A worked example by hand

Five houses, with size (in hundreds of square metres) and price (in hundreds of thousands):

Size xx 1 2 3 4 5
Price yy 3 4 8 9 11

We'll use stumps (trees with a single split) and learning rate η=0.5\eta = 0.5.

Round 0. Start with the average price: F0=(3+4+8+9+11)/5=7F_0 = (3 + 4 + 8 + 9 + 11)/5 = 7 for every house. The residuals y−F0y - F_0 are −4,−3,1,2,4-4, -3, 1, 2, 4. The mean squared error (MSE) is (16+9+1+4+16)/5=9.2(16 + 9 + 1 + 4 + 16)/5 = 9.2.

Round 1. Fit a stump to the residuals. Try each split, and for each compute the squared error of predicting each side's mean residual:

  • Split at x≤2.5x \le 2.5: left residuals {−4,−3}\{-4, -3\}, mean −3.5-3.5, squared error 0.5. Right {1,2,4}\{1, 2, 4\}, mean 2.33, squared error 4.67. Total 5.17.
  • Split at x≤3.5x \le 3.5: left {−4,−3,1}\{-4, -3, 1\}, mean −2-2, squared error 14. Right {2,4}\{2, 4\}, mean 3, squared error 2. Total 16.

(The other two splits are worse still.) So stump 1 says: −3.5-3.5 if x≤2.5x \le 2.5, else +2.33+2.33. Add half of it:

F1(x)=F0+0.5×stump1(x)F_1(x) = F_0 + 0.5 \times \text{stump}_1(x)

That gives 7−1.75=5.257 - 1.75 = 5.25 for the two small houses and 7+1.17=8.177 + 1.17 = 8.17 for the three large ones. New residuals: −2.25,−1.25,−0.17,0.83,2.83-2.25, -1.25, -0.17, 0.83, 2.83. MSE drops from 9.2 to 3.08.

Round 2. Fit a stump to the new residuals. Now the best split is x≤3.5x \le 3.5, with leaf values −1.22-1.22 and +1.83+1.83. Adding half of it gives predictions 4.64,4.64,7.56,9.08,9.084.64, 4.64, 7.56, 9.08, 9.08, and MSE 1.39.

Each round fixes part of what is left. After round 2 the model is a sum of three pieces: a constant and two stumps, each shrunk by 0.5. Keep going and the predictions approach the targets.

Why it is called gradient boosting

Why fit the residuals? Because for squared error they are exactly the direction downhill.

Write the loss for one example as L=12(y−F)2L = \frac{1}{2}(y - F)^2, where FF is the current prediction. Its derivative with respect to the prediction is:

∂L∂F=−(y−F)\frac{\partial L}{\partial F} = -(y - F)

So the negative gradient is y−Fy - F, the residual. Fitting a tree to the residuals means fitting a tree to the direction that lowers the loss fastest, and adding η\eta times that tree is a step of Gradient Descent. The difference from ordinary gradient descent is what moves. Ordinary gradient descent updates a fixed set of parameters. Gradient boosting updates the predictions themselves, using a tree to turn "how each training prediction should move" into a rule that also applies to new data.

This view is powerful because it works for any differentiable loss. In general, at round mm:

  1. Compute the pseudo-residuals ri=−∂L(yi,Fm−1(xi))∂Fr_i = -\frac{\partial L(y_i, F_{m-1}(\mathbf{x}_i))}{\partial F} for each example ii.
  2. Fit a small regression tree hmh_m to the pairs (xi,ri)(\mathbf{x}_i, r_i).
  3. Set each leaf's value to the best constant for the real loss in that leaf.
  4. Update: Fm(x)=Fm−1(x)+η hm(x)F_m(\mathbf{x}) = F_{m-1}(\mathbf{x}) + \eta \, h_m(\mathbf{x}).

For classification with log loss, the model's output FF is a log-odds score, the probability is p=σ(F)p = \sigma(F), and the pseudo-residual works out to y−py - p: the label (0 or 1) minus the predicted probability. Absolute error, Huber loss, ranking losses and Poisson losses for counts all slot into the same recipe (see Loss Functions).

XGBoost goes one step further and uses the second derivative as well (a Newton step), which gives better leaf values and a principled split score.

The knobs that matter

  • Learning rate η\eta (also called shrinkage): how much of each tree to add. Typical values are 0.01 to 0.3. Smaller is more accurate but needs more trees. Halving it roughly doubles the trees needed.
  • Number of trees: unlike a random forest, boosting can overfit if you add too many, because later trees start fitting noise. Choose it with early stopping: hold out a validation set, watch its error after each tree, and stop when it hasn't improved for, say, 20–50 rounds.
  • Tree size: max_depth (typically 3–8) or num_leaves / max_leaf_nodes (typically 15–255). Each tree is a weak learner, only slightly better than guessing, on purpose. Depth controls how many features can interact within one tree.
  • Row and column subsampling: train each tree on a random 50–90% of the rows and features. This is borrowed from random forests, adds variety, and usually helps (called stochastic gradient boosting).
  • Regularisation: minimum examples per leaf, and in XGBoost/LightGBM L1/L2 penalties on leaf values (see Regularization: L1 and L2).

A good default recipe: learning rate 0.05–0.1, moderate trees, early stopping on a validation set, then tune tree size and subsampling with random or Bayesian search.

What makes the modern libraries fast

The slow step in tree building is trying every threshold of every feature. Modern libraries use histogram binning: before training, each feature is bucketed into at most about 255 bins, and splits are only considered between bins. Counting into bins is fast and cache-friendly, and the loss in accuracy is negligible. On top of that:

  • XGBoost (2014) added second-order updates, built-in regularisation, sparse and missing-value handling, and careful engineering.
  • LightGBM (Microsoft, 2017) grows trees leaf-wise (always splitting the leaf with the largest gain, rather than level by level) and adds sampling tricks for very large data. It is usually the fastest.
  • CatBoost (Yandex, 2017) handles categorical features with a careful form of target encoding and uses symmetric trees. It often does well with little tuning.

All three, and scikit-learn's histogram version, handle missing values natively by learning which way missing values should go at each split.

In code

Gradient boosting for regression from scratch: a loop that fits a small tree to the residuals and adds a tenth of it.

import numpy as np
from sklearn.tree import DecisionTreeRegressor

rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(200, 1))
y = np.sin(X[:, 0]) * 3 + X[:, 0] * 0.5 + rng.normal(0, 0.5, 200)

lr, n_trees = 0.1, 100
pred = np.full_like(y, y.mean())          # F0: start from the average
trees = []
for m in range(1, n_trees + 1):
    residual = y - pred                   # negative gradient of squared error
    tree = DecisionTreeRegressor(max_depth=2).fit(X, residual)
    pred += lr * tree.predict(X)          # take a small step towards fixing the errors
    trees.append(tree)
    if m in (1, 5, 20, 100):
        print(f"trees {m:3d}   training MSE {np.mean((y - pred) ** 2):.3f}")

def predict(X_new):
    return y.mean() + lr * sum(t.predict(X_new) for t in trees)
print(predict(np.array([[2.0], [7.5]])).round(2))

# trees   1   training MSE 5.116
# trees   5   training MSE 2.829
# trees  20   training MSE 0.711
# trees 100   training MSE 0.141
# [3.5  6.61]

The true curve gives 3.73 at x=2x = 2 and 6.56 at x=7.5x = 7.5. Notice the training MSE after 100 trees (0.141) is already below the noise variance we added (0.25). The model has started to fit noise, which is why real code uses early stopping.

In practice, use scikit-learn's histogram-based implementation. Here it is on 20,000 rows of a synthetic nonlinear problem in which half the features are pure noise, with early stopping and a random forest for comparison:

from sklearn.datasets import make_friedman1
from sklearn.ensemble import HistGradientBoostingRegressor, RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split

# 20,000 rows, 10 features (5 useful, 5 pure noise), a nonlinear target with interactions
X, y = make_friedman1(n_samples=20_000, n_features=10, noise=1.0, random_state=0)
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)

gbm = HistGradientBoostingRegressor(
    learning_rate=0.1,        # shrink each tree's contribution
    max_iter=2000,            # upper limit on the number of trees
    max_leaf_nodes=15,        # size of each tree
    early_stopping=True,      # stop when the validation score stops improving...
    validation_fraction=0.1,  # ...measured on 10% of the training data held aside
    n_iter_no_change=30, random_state=0)
gbm.fit(X_tr, y_tr)

rf = RandomForestRegressor(n_estimators=300, n_jobs=-1, random_state=0).fit(X_tr, y_tr)

print("boosting rounds used :", gbm.n_iter_)
print(f"gradient boosting MAE: {mean_absolute_error(y_te, gbm.predict(X_te)):.3f}")
print(f"random forest MAE    : {mean_absolute_error(y_te, rf.predict(X_te)):.3f}")

# boosting rounds used : 271
# gradient boosting MAE: 0.870
# random forest MAE    : 1.092

Early stopping chose 271 trees out of a possible 2,000. The noise we added (standard deviation 1.0) puts a floor of about 0.80 on the achievable mean absolute error, so boosting at 0.870 is close to the best possible. For classification, use HistGradientBoostingClassifier the same way.

The dedicated libraries follow the same scikit-learn style (fit, predict). These snippets are not run here, since the libraries are separate installs (pip install xgboost lightgbm catboost), but they show the current APIs, assuming you have split off a validation set X_val, y_val:

import xgboost as xgb
model = xgb.XGBRegressor(n_estimators=2000, learning_rate=0.05, max_depth=6,
                         subsample=0.8, colsample_bytree=0.8, early_stopping_rounds=50)
model.fit(X_tr, y_tr, eval_set=[(X_val, y_val)], verbose=False)

import lightgbm as lgb
model = lgb.LGBMRegressor(n_estimators=2000, learning_rate=0.05, num_leaves=31,
                          subsample=0.8, subsample_freq=1, colsample_bytree=0.8)
model.fit(X_tr, y_tr, eval_X=X_val, eval_y=y_val,    # LightGBM 4.7+; older: eval_set=[(X_val, y_val)]
          callbacks=[lgb.early_stopping(50)])

from catboost import CatBoostRegressor
model = CatBoostRegressor(iterations=2000, learning_rate=0.05, depth=6,
                          early_stopping_rounds=50, verbose=0)
model.fit(X_tr, y_tr, eval_set=(X_val, y_val))   # add cat_features=[...] for categorical columns

Common pitfalls

  • Too many trees without early stopping. Boosting keeps driving training error down and eventually memorises noise. Always use a validation set and early stopping, or tune the number of trees with Cross-Validation.
  • Learning rate too high. With η=1\eta = 1 each tree overcorrects and the model overfits fast. Lower it and add trees.
  • Early-stopping on the test set. If you pick the stopping point using the test set, your test score is no longer honest. Use a separate validation split.
  • Leaky features. Boosting is superb at finding any feature that secretly encodes the answer (an ID that correlates with the label, a timestamp after the event). A suspiciously high score is usually a leak. See Training, Validation and Test Sets.
  • Extrapolation. Like all tree models, boosted trees predict flat beyond the range of the training data. For trending Time Series Forecasting, model the trend separately or predict differences.
  • Over-tuning. With dozens of hyperparameters it is easy to overfit the validation set by trying hundreds of combinations. Keep a final untouched test set.

Watch out Gradient boosting overfits when you add trees past the point the validation error stops improving. The training error will keep falling and look great. Watch a validation curve and use early stopping, every time.

Where it leads

  • Choosing between forests and boosting. Random forests are harder to get badly wrong and need almost no tuning. Gradient boosting usually wins by a few percent with sensible settings. Many practitioners try both.
  • AdaBoost, the original boosting algorithm, re-weights misclassified examples instead of fitting residuals. It turned out to be a special case of gradient boosting with an exponential loss.
  • Learning to rank. Gradient-boosted trees with ranking losses (LambdaMART) powered web search ranking for years.
  • Explaining predictions. SHAP values compute exact per-feature contributions quickly for tree ensembles. See Interpretability and Explainability.
  • Time series. Boosted trees on lag features are a strong forecasting baseline. See Time Series Forecasting.
  • Neural networks for tables have improved fast: on living benchmarks such as TabArena, tuned deep models and tabular foundation models (TabPFN and its successors) now often match or beat boosted trees, especially on smaller datasets. As of late 2026 gradient boosting is still the fast, reliable default that any alternative must beat. See Neural Networks.

A bit of history

Boosting began as a theoretical question. In 1988–89 Michael Kearns and Leslie Valiant asked whether a "weak" learner, barely better than chance, could always be boosted into a strong one. Robert Schapire proved in 1990 that it could. Yoav Freund and Schapire then turned the idea into the practical AdaBoost algorithm (1995, journal version 1997), which won them the Gödel Prize in 2003.

In 1999–2001 Jerome Friedman reframed boosting as gradient descent in function space in Greedy Function Approximation: A Gradient Boosting Machine, which gave us gradient boosting with arbitrary losses, shrinkage and stochastic subsampling. Tianqi Chen released XGBoost in 2014. It became famous during the Higgs Boson Machine Learning Challenge on Kaggle that year, and the paper with Carlos Guestrin followed in 2016. LightGBM (Microsoft) and CatBoost (Yandex) followed in 2017. scikit-learn added its histogram-based estimators, inspired by LightGBM, in version 0.21 (2019).

Try it

  1. Continue the hand example for a third round. Fit a stump to the residuals after round 2. Which split wins, and what is the new MSE?
  2. In the from-scratch code, try lr = 1.0 with 100 trees and lr = 0.01 with 100 trees. Compare the training MSE and plot the predictions. Which looks overfitted, and which underfitted?
  3. Harder: add a held-out validation set to the from-scratch code and record the validation MSE after every tree. At which round does it stop improving?

Hint for 1: the residuals after round 2 are y−F2y - F_2 = −1.64,−0.64,0.44,−0.08,1.92-1.64, -0.64, 0.44, -0.08, 1.92.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. In gradient boosting with squared error, what is each new tree trained to predict?

  2. You keep adding trees to a gradient-boosting model. Training error keeps falling, but validation error started rising after tree 270. What should you do?

  3. You halve the learning rate (shrinkage) from 0.1 to 0.05. What should you expect?

  4. How does boosting differ from a random forest?

  5. What does histogram binning do in libraries like LightGBM and XGBoost?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Video

StatQuest

Josh Starmer · Beginner · Free

Short, cheerful, very clear videos on statistics and nearly every ML algorithm.

Course

Decision Forests course

Google · Beginner · Free

A short, clear course on decision trees, random forests and gradient-boosted trees, with diagrams.

Docs

XGBoost documentation

XGBoost developers · Intermediate · Free

Docs for XGBoost, including a readable introduction to boosted trees and its parameter guide.

Docs

LightGBM documentation

Microsoft · Intermediate · Free

Docs for LightGBM, the fast histogram-based gradient boosting library, with a useful parameter-tuning page.

Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/ml/gradient-boosting.md