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
- Start every row at a constant: the mean target for regression, or the log-odds of the positive rate for binary classification.
- For each row compute the gradient and the second derivative of the loss at the current prediction.
- Grow a tree. At each node, sort the rows by each feature and score every threshold with the gain formula, using the sums of and on each side.
- Take the best split if its gain is positive and both children hold at least min_child_weight of summed . Stop at max_depth.
- Set each leaf's weight to from the sums of its rows.
- Add the tree's output times the learning rate to every row's prediction.
- 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
| If | Use instead |
|---|---|
| The table is very large and training time matters | LightGBM |
| Categorical columns dominate | CatBoost |
| You want a strong model with almost no tuning | A random forest |
| The inputs are images, audio or text | A neural network such as a CNN or a Transformer |
Math foundations
The additive model
The prediction is a starting constant plus the scaled outputs of trees. Each tree is added once and never changed afterwards.
The objective for one new tree
A second-order Taylor expansion of the loss around the current prediction, plus a cost per leaf and an L2 penalty on leaf weights. Constant terms are dropped.
Gradients and second derivatives
For squared error is the residual with its sign reversed, so the tree fits residuals. For log loss, is the sigmoid of the current raw prediction, and uncertain rows have the largest .
The best leaf weight
Within a leaf the objective is a quadratic in , and this is its minimum. It is a Newton step, shrunk toward zero by .
The score of a tree
Put the best weights back into the objective. This says how good a tree structure is, and lower is better.
The gain of a split
How much the score improves when one leaf becomes two. A split is made only if this is positive, so acts as the minimum improvement a split must bring.
Symbols
- current raw prediction for row i
- starting constant, base_score_
- the m-th tree: maps a row to the weight of the leaf it lands in
- learning rate (shrinkage)
- first and second derivative of the loss for row i
- sums of g and h over the rows in leaf j
- the same sums for the left and right side of a split
- weight (output value) of leaf j
- number of leaves in the tree
- L2 penalty on leaf weights, reg_lambda
- cost per leaf and minimum gain, gamma
- predicted probability for row i
Worked by hand
Regression with four rows, targets , sorted by one feature. Use , and . The starting prediction is the mean, 3.5. Score the split between the second and third rows.
The split has gain 5.33 and moves the two low rows down and the two high rows up. With the weights would be , 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
- 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.
- 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.
- For log loss, . 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 near zero. A leaf made only of such rows has a tiny , and dividing by it gives a large, poorly supported weight.
- 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.
- With squared error, show that when 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 and into . For this loss the Newton step and the residual fit coincide.