← All posts

Machine learning algorithms › Tree models

What is gradient boosting? Trees that learn from mistakes

Gradient boosting adds small decision trees one at a time, each fixing the errors left so far. How it works, when it fits, and how XGBoost and LightGBM differ.

If you work with machine learning on spreadsheet-style data, you’ll run into the names XGBoost and LightGBM again and again. Both are libraries that implement gradient boosting. The XGBoost authors counted that 17 of the 29 winning solutions Kaggle published on its blog in 2015 used it (XGBoost paper). A study presented at NeurIPS in 2022 also reported that on medium-sized tabular data, tree-based models still beat deep learning (Grinsztajn et al.). That’s why you keep hearing the term, even with so much news about neural networks.

Put in one sentence, gradient boosting is an ensemble that adds shallow decision trees one at a time, training each new tree to predict how far off the predictions so far still are. An ensemble is a model that combines the predictions of many models. With squared error as the loss, “how far off” is the residual, the actual value minus the prediction. More generally, it’s the negative gradient of the loss, the direction in which moving the predictions lowers the loss fastest. Written out in words, the finished model is: prediction = starting value + learning rate × (tree 1’s answer + tree 2’s answer + …).

Where boosting came from

Boosting grew out of a question in learning theory: could many weak learners, each only slightly better than random guessing, be combined into one accurate learner? Yoav Freund and Robert Schapire answered with AdaBoost. A conference abstract came out in 1995 and the full journal paper in 1997, so you’ll see both years cited (Freund and Schapire). AdaBoost trains each new learner with more weight on the examples the earlier ones got wrong, then combines them by a weighted majority vote.

The person who broadened the idea was Jerome Friedman, in his 2001 paper “Greedy Function Approximation: A Gradient Boosting Machine” (Friedman). Just as gradient descent moves a model’s weights to lower the loss, he saw boosting as moving the predictions themselves, with one tree learning which way to move them. That’s why the same recipe works for any loss you can differentiate, and with squared error it becomes fitting the residuals again and again.

Building it by hand from residuals

Using 200 points along a sine curve with noise added, let’s stack regression trees of depth 2 one after another, and measure the test error on 1,000 new points from the same curve as we go. A depth-2 tree can only cut the line into four pieces, so it’s a weak learner. MSE (mean squared error) is the average of the squared gaps between the actual values and the predictions.

import numpy as np
from sklearn.tree import DecisionTreeRegressor

rng = np.random.default_rng(0)
X = rng.uniform(0, 6, 200).reshape(-1, 1)
y = 3 * np.sin(X[:, 0]) + rng.normal(0, 0.5, 200)  # a wavy curve plus noise
X_new = rng.uniform(0, 6, 1000).reshape(-1, 1)     # new points from the same curve
y_new = 3 * np.sin(X_new[:, 0]) + rng.normal(0, 0.5, 1000)

learning_rate = 0.1
pred = np.full(200, y.mean())  # start from the mean
pred_new = np.full(1000, y.mean())
for m in range(1, 1001):
    residual = y - pred  # what the model still gets wrong
    tree = DecisionTreeRegressor(max_depth=2).fit(X, residual)
    pred += learning_rate * tree.predict(X)  # a small step toward the residuals
    pred_new += learning_rate * tree.predict(X_new)  # new points move too
    if m in (1, 10, 30, 100, 300, 1000):
        print(f"round {m:4d}  train MSE {np.mean((y - pred) ** 2):.3f}  "
              f"test MSE {np.mean((y_new - pred_new) ** 2):.3f}")
round    1  train MSE 3.899  test MSE 4.253
round   10  train MSE 0.973  test MSE 1.116
round   30  train MSE 0.254  test MSE 0.336
round  100  train MSE 0.165  test MSE 0.292
round  300  train MSE 0.083  test MSE 0.334
round 1000  train MSE 0.008  test MSE 0.430

Each tree learns only from the residuals, and its answer is multiplied by the learning rate of 0.1 before it’s added. New points are predicted by adding up the same trees’ answers. scikit-learn’s GradientBoostingRegressor also starts from the mean when the loss is squared error, so with matching settings it should land in the same place.

from sklearn.ensemble import GradientBoostingRegressor

gbr = GradientBoostingRegressor(n_estimators=1000, learning_rate=0.1, max_depth=2).fit(X, y)
gap = max(np.abs(gbr.predict(X) - pred).max(), np.abs(gbr.predict(X_new) - pred_new).max())
print(f"largest gap from our loop {gap:.1e}")
largest gap from our loop 8.9e-16

The gap is at the level of rounding error, so the loop above is, in effect, the whole algorithm.

Learning rate, number of trees, and when to stop

Look back at the first output. The training MSE keeps falling to the end, but the test MSE drops to 0.292 around 100 trees and climbs back to 0.430 at 1,000. The noise has a standard deviation of 0.5, so even the true curve would score about 0.25 on new points, and a training MSE of 0.008 means the trees have memorized the noise. Getting better only on the data you learned from while getting worse on new data is called overfitting.

When I measured the test error after every tree with scikit-learn, it was lowest at 64 trees (0.289) with a learning rate of 0.1, and at 8 trees (0.326) with 1.0. Friedman introduced this scaling of each tree’s answer as shrinkage, and he reported that lowering the learning rate raises the best number of trees and generally improves the results. So the scikit-learn user guide also advises keeping the learning rate at 0.1 or less and allowing enough trees for early stopping to kick in. Early stopping halts training once the validation score hasn’t improved for a set number of rounds. The same guide says a tree of depth h can capture effects where h features interact, and that subsampling, training each tree on part of the rows (Friedman, 2002), raises accuracy further when combined with shrinkage.

XGBoost, LightGBM, and CatBoost

The widely used implementations keep this skeleton and change how the trees are built and refined.

Implementation Introduced in Known for
XGBoost Chen and Guestrin, KDD 2016 A tree complexity penalty, a default direction for missing values
LightGBM Ke et al., NIPS 2017 Histogram-based splits, GOSS and EFB, leaf-wise growth
CatBoost Prokhorenkova et al., NeurIPS 2018 Categorical features, ordered boosting
HistGradientBoosting scikit-learn 0.21 Inspired by LightGBM

In LightGBM, GOSS uses only a sample of the rows with small gradients, and EFB bundles features that are rarely nonzero at the same time. With these two, the authors report training up to over 20 times faster than conventional gradient boosting with almost the same accuracy. LightGBM also uses leaf-wise growth, splitting whichever leaf lowers the loss most, so tree size is set with num_leaves (31 by default). CatBoost’s ordered boosting is a way to prevent the prediction shift that comes from the training data’s answers leaking into the model.

Three libraries on the same data

Now let’s give HistGradientBoosting, XGBoost, and LightGBM a learning rate of 0.05 and up to 2,000 trees, and have each stop after 50 rounds without improvement on the same validation set. I fixed the seeds and ran XGBoost and LightGBM on one thread, and scikit-learn’s model gave the same result with different thread counts.

import lightgbm as lgb
import xgboost as xgb
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
from sklearn.model_selection import train_test_split

def compare(X, y):
    # 64% train, 16% validation (for early stopping), 20% test
    X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.2, random_state=0)
    X_tr, X_va, y_tr, y_va = train_test_split(X_tr, y_tr, test_size=0.2, random_state=0)
    hgb = HistGradientBoostingRegressor(learning_rate=0.05, max_iter=2000, early_stopping=True,
                                        n_iter_no_change=50, random_state=0)
    hgb.fit(X_tr, y_tr, X_val=X_va, y_val=y_va)
    xgbr = xgb.XGBRegressor(learning_rate=0.05, n_estimators=2000, early_stopping_rounds=50,
                            n_jobs=1, random_state=0)
    xgbr.fit(X_tr, y_tr, eval_set=[(X_va, y_va)], verbose=False)
    lgbr = lgb.LGBMRegressor(learning_rate=0.05, n_estimators=2000, n_jobs=1, random_state=0,
                             verbose=-1)
    lgbr.fit(X_tr, y_tr, eval_X=X_va, eval_y=y_va,
             callbacks=[lgb.early_stopping(50, verbose=False)])
    lin = LinearRegression().fit(X_tr, y_tr)
    for name, model, trees in [("LinearRegression", lin, "-"),
                               ("HistGradientBoosting", hgb, hgb.n_iter_),
                               ("XGBoost", xgbr, xgbr.best_iteration + 1),
                               ("LightGBM", lgbr, lgbr.best_iteration_)]:
        print(f"{name:<20} test R2 {r2_score(y_te, model.predict(X_te)):.3f}  trees {trees}")

The data comes from make_friedman1, where only 5 of the 10 features go into the target.

from sklearn.datasets import make_friedman1

X, y = make_friedman1(n_samples=2000, noise=1.0, random_state=0)
compare(X, y)
LinearRegression     test R2 0.692  trees -
HistGradientBoosting test R2 0.915  trees 360
XGBoost              test R2 0.912  trees 743
LightGBM             test R2 0.921  trees 276

R² is 1 for perfect predictions and 0 for always predicting the mean. Linear regression stopped at 0.692, while the three libraries reached 0.912 to 0.921. The trees column is the number of trees used for prediction, and HistGradientBoosting also keeps the trees from the last 50 rounds before it stopped. The gap in tree counts comes mainly from the default tree shape. When I switched XGBoost, which grows to depth 6, to grow up to 31 leaves, it used 270 trees and scored 0.921. So I wouldn’t read a difference this small as a ranking.

How it differs from a random forest

A random forest also combines many trees, but it grows them separately and averages them. In the words of the scikit-learn user guide, random forests rely on deep trees that each overfit, while boosting stacks shallow trees that each underfit, one after another, to correct the errors before them.

When it fits and when it doesn’t

Gradient boosting fits best with tabular data, where each column means something different, such as age, price, or a count. Grinsztajn and colleagues reported that across 45 such datasets with about 10,000 training rows, tree-based models beat deep learning however much was spent on hyperparameter search. Among the reasons, they point out that neural networks lean toward overly smooth functions and that MLP-style networks are hurt more by uninformative features.

Of course, it has weak spots too. There are many hyperparameters and they interact, so you need a validation set or cross-validation to choose them, and with small, noisy data the advantage can disappear. When I passed the diabetes dataset, with 442 patients and 10 features, to the compare function above, the three libraries scored an R² of 0.316 to 0.352, about the same as linear regression’s 0.346. And for data without fixed columns, such as images, audio, or text, deep learning models that learn their own features are often the better fit.

Where to start

If you’re new to this, try changing max_depth and learning_rate one at a time in the loop above. For real tables, scikit-learn’s HistGradientBoosting models are enough to start with, and they turn on early stopping by default once you have more than 10,000 samples. XGBoost installs with pip install xgboost (installation guide) and LightGBM with pip install lightgbm (Python package guide). On macOS, that LightGBM guide says you also need OpenMP, which you can install with brew install libomp. I ran these examples on November 2, 2026, with Python 3.13.12, scikit-learn 1.9.1, XGBoost 3.4.1, and LightGBM 4.7.0.

AI tools helped with the research for this post.