Sign in

XGBoost

eXtreme Gradient Boosting

Gradient-boosted trees: a model built by adding small decision trees one at a time, each fitted to correct the errors of the sum so far, using first and second derivatives of the loss.

Overview

A random forest grows its trees independently and averages them. Boosting grows them in sequence. It starts from a constant guess, fits a small tree to the errors of that guess, adds a fraction of the tree's output to the prediction, and repeats on the errors that remain. XGBoost describes the loss near the current prediction by its slope and curvature, and from those it derives a formula for the best value of each leaf and a score for each candidate split. Penalties on the number of leaves and the size of leaf values are part of that formula. This template is a small exact version of the method.

A short history

Jerome Friedman set out gradient boosting in work published in 2001. Tianqi Chen started XGBoost in 2014 and published it with Carlos Guestrin in 2016. It added a regularised objective, the use of second derivatives, handling of sparse and missing values, and an engineered, parallel implementation. It became known through machine learning competitions, where a large share of winning tabular solutions used it, and it is now a standard industrial tool.

How it works

  1. Start every row at a constant: the mean target for regression, or the log-odds of the positive rate for binary classification.
  2. For each row compute the gradient gig_i and the second derivative hih_i of the loss at the current prediction.
  3. Grow a tree. At each node, sort the rows by each feature and score every threshold with the gain formula, using the sums of gg and hh on each side.
  4. Take the best split if its gain is positive and both children hold at least min_child_weight of summed hh. Stop at max_depth.
  5. Set each leaf's weight to −G/(H+λ)-G / (H + \lambda) from the sums of its rows.
  6. Add the tree's output times the learning rate to every row's prediction.
  7. Repeat for n_estimators rounds, optionally drawing a random share of rows and features for each tree.

Watch out for

  • Too many rounds with a high learning rate fit the noise in the training data. Lower learning_rate, and choose the number of trees on a validation set using predict_raw with n_trees.
  • Like all tree models it cannot extrapolate, because predictions are sums of leaf constants. Outside the training range the output is flat.
  • Deep trees multiply the number of leaves and fit high-order interactions that may be noise. A max_depth of 3 to 6 is usually enough.
  • This small version tries every threshold by sorting, and has no histogram binning, missing-value handling or parallelism, so it is slow on large data.

Use cases

When to use it

Tabular data, where boosted trees are usually the strongest single model. They handle mixed feature scales and non-linear interactions with no preprocessing.

In industry

Payments
Fraud detection at card issuers and processors: boosted trees score each transaction from amount, merchant, device and history features.
Insurance and lending
Risk models that predict claims or defaults from tables with missing values and mixed feature types.
Physics
Separating signal from background in particle collision data, as in the 2014 Higgs boson machine learning challenge.
Marketing
Predicting churn or response to an offer from customer tables, with feature importance used to explain drivers.

Choosing it: what must hold

  • Tabular data with a supervised target and at least a few thousand rows.
  • A validation set for early stopping and for tuning depth, learning rate and regularisation.
  • Features that already carry the signal; trees do not learn representations from raw pixels or text.

When to choose something else

IfUse instead
The table is very large and training time mattersLightGBM
Categorical columns dominateCatBoost
You want a strong model with almost no tuningA random forest
The inputs are images, audio or textA neural network such as a CNN or a Transformer

Math foundations

  1. The additive model

    y^i=f0+η∑m=1Mfm(xi)\hat{y}_i = f_0 + \eta \sum_{m=1}^{M} f_m(\mathbf{x}_i)

    The prediction is a starting constant plus the scaled outputs of MM trees. Each tree is added once and never changed afterwards.

  2. The objective for one new tree

    L(m)≈∑i=1n[gifm(xi)+12hifm(xi)2]+γT+12λ∑j=1Twj2\mathcal{L}^{(m)} \approx \sum_{i=1}^{n}\left[g_i f_m(\mathbf{x}_i) + \tfrac{1}{2} h_i f_m(\mathbf{x}_i)^2\right] + \gamma T + \tfrac{1}{2}\lambda \sum_{j=1}^{T} w_j^2

    A second-order Taylor expansion of the loss around the current prediction, plus a cost γ\gamma per leaf and an L2 penalty on leaf weights. Constant terms are dropped.

  3. Gradients and second derivatives

    squared error: gi=y^i−yi,  hi=1log loss: gi=pi−yi,  hi=pi(1−pi)\text{squared error: } g_i = \hat{y}_i - y_i,\; h_i = 1 \qquad \text{log loss: } g_i = p_i - y_i,\; h_i = p_i(1 - p_i)

    For squared error gg is the residual with its sign reversed, so the tree fits residuals. For log loss, pip_i is the sigmoid of the current raw prediction, and uncertain rows have the largest hih_i.

  4. The best leaf weight

    wj∗=−GjHj+λ,Gj=∑i∈leaf jgi,Hj=∑i∈leaf jhiw_j^{*} = -\frac{G_j}{H_j + \lambda}, \qquad G_j = \sum_{i \in \text{leaf } j} g_i, \quad H_j = \sum_{i \in \text{leaf } j} h_i

    Within a leaf the objective is a quadratic in wjw_j, and this is its minimum. It is a Newton step, shrunk toward zero by λ\lambda.

  5. The score of a tree

    L∗=−12∑j=1TGj2Hj+λ+γT\mathcal{L}^{*} = -\frac{1}{2}\sum_{j=1}^{T} \frac{G_j^2}{H_j + \lambda} + \gamma T

    Put the best weights back into the objective. This says how good a tree structure is, and lower is better.

  6. The gain of a split

    gain=12[GL2HL+λ+GR2HR+λ−(GL+GR)2HL+HR+λ]−γ\text{gain} = \frac{1}{2}\left[\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}\right] - \gamma

    How much the score improves when one leaf becomes two. A split is made only if this is positive, so γ\gamma acts as the minimum improvement a split must bring.

Symbols

y^i\hat{y}_i
current raw prediction for row i
f0f_0
starting constant, base_score_
fmf_m
the m-th tree: maps a row to the weight of the leaf it lands in
η\eta
learning rate (shrinkage)
gi,hig_i, h_i
first and second derivative of the loss for row i
Gj,HjG_j, H_j
sums of g and h over the rows in leaf j
GL,HL,GR,HRG_L, H_L, G_R, H_R
the same sums for the left and right side of a split
wjw_j
weight (output value) of leaf j
TT
number of leaves in the tree
λ\lambda
L2 penalty on leaf weights, reg_lambda
γ\gamma
cost per leaf and minimum gain, gamma
pip_i
predicted probability for row i

Worked by hand

Regression with four rows, targets y=(1,2,5,6)y = (1, 2, 5, 6), sorted by one feature. Use λ=1\lambda = 1, γ=0\gamma = 0 and η=0.1\eta = 0.1. The starting prediction is the mean, 3.5. Score the split between the second and third rows.

g=y^−y=(2.5,  1.5,  −1.5,  −2.5),h=(1,1,1,1)g = \hat{y} - y = (2.5,\; 1.5,\; -1.5,\; -2.5), \qquad h = (1, 1, 1, 1)
GL=4,  HL=2,GR=−4,  HR=2G_L = 4,\; H_L = 2, \qquad G_R = -4,\; H_R = 2
gain=12[163+163−025]=5.333\text{gain} = \frac{1}{2}\left[\frac{16}{3} + \frac{16}{3} - \frac{0^2}{5}\right] = 5.333
wL=−42+1=−1.333,wR=−−42+1=1.333w_L = -\frac{4}{2 + 1} = -1.333, \qquad w_R = -\frac{-4}{2 + 1} = 1.333
y^left=3.5+0.1×(−1.333)=3.367,y^right=3.5+0.1×1.333=3.633\hat{y}_{\text{left}} = 3.5 + 0.1 \times (-1.333) = 3.367, \qquad \hat{y}_{\text{right}} = 3.5 + 0.1 \times 1.333 = 3.633

The split has gain 5.33 and moves the two low rows down and the two high rows up. With λ=0\lambda = 0 the weights would be ±2\pm 2, the plain mean residuals, so the penalty has shrunk them by a third.

Visual example

Loading the example.

Try this

  • Round 1 is one small tree. Step the rounds up slowly.
  • Halve the learning rate and count how many more rounds it takes.

Code sample

import numpy as np
from impl import XGBoost
from config import XGBoostConfig

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

model = XGBoost(XGBoostConfig(n_estimators=100, learning_rate=0.1, max_depth=3)).fit(X, y)
print(model.score(X, y))                         # R^2 on the training rows, about 0.99
print(model.loss_history_[0], model.loss_history_[-1])   # training loss before the first and after the last tree
print(model.predict(X[:3]))
Read the implementation (189 lines)
"""Gradient-boosted trees in the XGBoost style (second-order boosting, exact greedy splits).

NumPy only. At each round, with g_i and h_i the first and second derivatives of the loss at the current
prediction of row i, a tree is grown to minimise

    sum over leaves of [ G w + 0.5 * (H + lambda) * w^2 ] + gamma * (number of leaves)

where G and H are the sums of g and h in the leaf and w is the leaf weight. The best weight is -G / (H + lambda).
"""
from __future__ import annotations

import numpy as np

try:
    from .config import XGBoostConfig
except ImportError:  # run from the template's own folder
    from config import XGBoostConfig


def leaf_weight(G: float, H: float, reg_lambda: float) -> float:
    """Best weight of a leaf whose rows have gradient sum G and hessian sum H."""
    return -G / (H + reg_lambda)


def split_gain(GL, HL, GR, HR, reg_lambda: float, gamma: float):
    """Loss reduction from splitting a leaf into children with sums (GL, HL) and (GR, HR). Accepts arrays."""
    G, H = GL + GR, HL + HR
    return 0.5 * (GL**2 / (HL + reg_lambda) + GR**2 / (HR + reg_lambda) - G**2 / (H + reg_lambda)) - gamma


def _sigmoid(z: np.ndarray) -> np.ndarray:
    e = np.exp(-np.abs(z))
    return np.where(z >= 0, 1.0 / (1.0 + e), e / (1.0 + e))


class _BoostTree:
    """One regression tree on (g, h), stored as flat lists. Node i is a leaf when `feature[i]` is -1."""

    def __init__(self, config: XGBoostConfig, features: np.ndarray) -> None:
        self.config = config
        self.features = features  # feature indices this tree may split on
        self.feature: list[int] = []
        self.threshold: list[float] = []
        self.left: list[int] = []
        self.right: list[int] = []
        self.weight: list[float] = []

    def fit(self, X: np.ndarray, g: np.ndarray, h: np.ndarray) -> "_BoostTree":
        """Grow the tree. X: (n, d). g, h: per-row gradient and hessian, shape (n,)."""
        self._grow(X, g, h, depth=0)
        return self

    def _grow(self, X: np.ndarray, g: np.ndarray, h: np.ndarray, depth: int) -> int:
        cfg = self.config
        node = len(self.feature)
        self.feature.append(-1)
        self.threshold.append(0.0)
        self.left.append(-1)
        self.right.append(-1)
        self.weight.append(leaf_weight(g.sum(), h.sum(), cfg.reg_lambda) if h.sum() + cfg.reg_lambda > 0 else 0.0)
        if depth >= cfg.max_depth or len(X) < 2:
            return node
        best_gain, best_feature, best_threshold = 1e-12, -1, 0.0
        G, H = g.sum(), h.sum()
        for feature in self.features:
            order = np.argsort(X[:, feature], kind="stable")
            x = X[order, feature]
            GL = np.cumsum(g[order])[:-1]
            HL = np.cumsum(h[order])[:-1]
            GR, HR = G - GL, H - HL
            valid = (x[1:] > x[:-1]) & (HL >= cfg.min_child_weight) & (HR >= cfg.min_child_weight)
            if not valid.any():
                continue
            with np.errstate(divide="ignore", invalid="ignore"):
                gain = np.where(valid, split_gain(GL, HL, GR, HR, cfg.reg_lambda, cfg.gamma), -np.inf)
            pos = int(np.argmax(gain))
            if gain[pos] > best_gain:
                best_gain, best_feature = float(gain[pos]), int(feature)
                best_threshold = float(0.5 * (x[pos] + x[pos + 1]))
        if best_feature < 0:
            return node
        go_left = X[:, best_feature] <= best_threshold
        self.feature[node], self.threshold[node] = best_feature, best_threshold
        self.left[node] = self._grow(X[go_left], g[go_left], h[go_left], depth + 1)
        self.right[node] = self._grow(X[~go_left], g[~go_left], h[~go_left], depth + 1)
        return node

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Leaf weight for every row. X: (n, d). Returns shape (n,)."""
        feature = np.array(self.feature)
        threshold = np.array(self.threshold)
        left, right = np.array(self.left), np.array(self.right)
        node = np.zeros(len(X), dtype=int)
        active = np.flatnonzero(feature[node] >= 0)
        while len(active):
            at = node[active]
            go_left = X[active, feature[at]] <= threshold[at]
            node[active] = np.where(go_left, left[at], right[at])
            active = active[feature[node[active]] >= 0]
        return np.array(self.weight)[node]

    @property
    def n_leaves(self) -> int:
        return sum(1 for f in self.feature if f < 0)


class XGBoost:
    """Boosted trees. After `fit`: `trees_`, `base_score_` (starting raw prediction), `loss_history_`."""

    def __init__(self, config: XGBoostConfig | None = None) -> None:
        self.config = config or XGBoostConfig()
        self.trees_: list[_BoostTree] = []
        self.base_score_ = 0.0
        self.loss_history_: list[float] = []

    def _grad_hess(self, raw: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
        """First and second derivatives of the per-row loss with respect to the raw prediction."""
        if self.config.objective == "binary:logistic":
            p = _sigmoid(raw)
            return p - y, np.maximum(p * (1.0 - p), 1e-16)
        return raw - y, np.ones_like(raw)  # loss = 0.5 * (raw - y)^2

    def _loss(self, raw: np.ndarray, y: np.ndarray) -> float:
        """Mean training loss: log loss for classification, half squared error for regression."""
        if self.config.objective == "binary:logistic":
            return float(np.mean(np.logaddexp(0.0, raw) - y * raw))
        return float(0.5 * np.mean((raw - y) ** 2))

    def fit(self, X: np.ndarray, y: np.ndarray) -> "XGBoost":
        """Boost. X: features, shape (n, d). y: shape (n,), real targets or 0/1 labels for `binary:logistic`."""
        cfg = self.config
        X = np.asarray(X, dtype=float)
        y = np.asarray(y, dtype=float)
        if X.ndim != 2 or len(X) != len(y):
            raise ValueError("X must have shape (n, d) and y must have n entries")
        n, d = X.shape
        if cfg.objective == "binary:logistic":
            if not np.isin(y, (0.0, 1.0)).all():
                raise ValueError("binary:logistic needs labels 0 and 1")
            rate = np.clip(y.mean(), 1e-6, 1 - 1e-6)
            self.base_score_ = float(np.log(rate / (1.0 - rate)))
        else:
            self.base_score_ = float(y.mean())
        rng = np.random.default_rng(cfg.seed)
        raw = np.full(n, self.base_score_)
        self.trees_ = []
        self.loss_history_ = [self._loss(raw, y)]
        n_rows = max(1, int(round(cfg.subsample * n)))
        n_cols = max(1, int(round(cfg.colsample_bytree * d)))
        for _ in range(cfg.n_estimators):
            g, h = self._grad_hess(raw, y)
            rows = np.sort(rng.choice(n, size=n_rows, replace=False)) if n_rows < n else np.arange(n)
            cols = np.sort(rng.choice(d, size=n_cols, replace=False)) if n_cols < d else np.arange(d)
            tree = _BoostTree(cfg, cols).fit(X[rows], g[rows], h[rows])
            raw += cfg.learning_rate * tree.predict(X)
            self.trees_.append(tree)
            self.loss_history_.append(self._loss(raw, y))
        return self

    def predict_raw(self, X: np.ndarray, n_trees: int | None = None) -> np.ndarray:
        """Sum of the base score and the first `n_trees` trees (all by default). X: (n, d). Returns (n,)."""
        if not self.trees_:
            raise RuntimeError("call fit before predicting")
        X = np.asarray(X, dtype=float)
        raw = np.full(len(X), self.base_score_)
        for tree in self.trees_[:n_trees]:
            raw += self.config.learning_rate * tree.predict(X)
        return raw

    def predict_proba(self, X: np.ndarray) -> np.ndarray:
        """Probability of class 1 (`binary:logistic` only). X: (n, d). Returns shape (n,)."""
        if self.config.objective != "binary:logistic":
            raise RuntimeError("predict_proba is for the binary:logistic objective")
        return _sigmoid(self.predict_raw(X))

    def predict(self, X: np.ndarray) -> np.ndarray:
        """Predicted values (regression) or 0/1 labels (classification). X: (n, d). Returns shape (n,)."""
        raw = self.predict_raw(X)
        if self.config.objective == "binary:logistic":
            return (raw >= 0).astype(int)
        return raw

    def score(self, X: np.ndarray, y: np.ndarray) -> float:
        """R^2 for regression, accuracy for classification."""
        y = np.asarray(y, dtype=float)
        pred = self.predict(X)
        if self.config.objective == "binary:logistic":
            return float((pred == y).mean())
        return float(1.0 - np.sum((y - pred) ** 2) / np.sum((y - y.mean()) ** 2))
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
9, run with python3 -m unittest -v

Practice

Make a regression data set with a non-linear target, such as the sine of one feature plus the product of two others. Fit XGBoost with XGBoostConfig n_estimators 200 and learning_rate 0.3. Use predict_raw with n_trees from 1 to 200 to plot training and held-out error against the number of trees. Repeat with learning_rate 0.05 and compare where the held-out error is lowest. Check a few values by hand with leaf_weight and split_gain.

Check on learning

  1. A random forest averages independent deep trees, while boosting adds dependent shallow ones. Which kind of error does each mainly reduce, and why does that explain the different tree depths?
    A way to think about it

    A deep tree fits well but varies a lot between samples, and averaging steadies it. A shallow tree is steady but too simple, and adding corrections makes the sum more flexible.

  2. Why multiply each tree by a learning rate below 1 when the leaf weights are already the best values for the current objective?
    A way to think about it

    Best for the training rows at this round is not best for new data. Small steps leave room for later trees to correct, and spread the fit over many trees.

  3. For log loss, hi=pi(1−pi)h_i = p_i(1 - p_i). Which rows have the most influence on a leaf's weight, and what does min_child_weight then protect against?
    A way to think about it

    Rows the model is already sure about have hh near zero. A leaf made only of such rows has a tiny HH, and dividing by it gives a large, poorly supported weight.

  4. You raise gamma from 0 to 5. Predict the effect on the trees and on the training and test errors.
    A way to think about it

    Every split must now pay 5 out of its gain. Check which splits in a tree survive, and what fewer leaves means for fitting noise.

  5. With squared error, show that when λ=0\lambda = 0 the best leaf weight is the mean residual of the leaf. What does this say about how second-order boosting relates to fitting residuals?
    A way to think about it

    Substitute gi=y^i−yig_i = \hat{y}_i - y_i and hi=1h_i = 1 into −G/H-G / H. For this loss the Newton step and the residual fit coincide.