Sub topic 5
What XGBoost adds: regularized objective with gradients and hessians
This chapter assumes you know how plain gradient boosting fits each tree to the negative gradient of the loss, and that you can read a decision tree. It covers what XGBoost changes about how trees are scored and built.
From first-order to second-order
Plain gradient boosting fits each new tree to the negative gradient, which is the residual for squared error. XGBoost approximates the loss around the current prediction with a second-order Taylor expansion. For each sample i it computes two numbers from the loss l, using the current prediction ŷᵢ:
gᵢ, the gradient: the first derivative oflwith respect toŷᵢ.hᵢ, the hessian: the second derivative oflwith respect toŷᵢ.
For squared error, g = ŷ − y and h = 1. For logistic loss with probability p, g = p − y and h = p(1 − p). The hessian tells the algorithm how sharply curved the loss is, so it can take a better-sized step than a gradient alone.
The regularized objective
XGBoost adds a penalty for tree complexity to the loss:
Obj = Σ l(yᵢ, ŷᵢ) + Σ Ω(f), with Ω(f) = γT + ½λ Σ wⱼ²
Here T is the number of leaves and wⱼ is the weight (output value) of leaf j. γ (gamma) charges a fixed cost per leaf. λ (reg_lambda) shrinks leaf weights toward zero. An optional L1 term (alpha, reg_alpha) is also available.
Leaf weights and split gain
Let G and H be the sums of gᵢ and hᵢ over the samples in one leaf. Minimizing the approximated objective gives the best leaf weight and its score:
- Optimal weight:
w* = −G / (H + λ) - Leaf score:
G² / (H + λ)
A split sends samples to a left and a right child. Its gain is:
Gain = ½ [ G_L²/(H_L+λ) + G_R²/(H_R+λ) − (G_L+G_R)²/(H_L+H_R+λ) ] − γ
The split is kept only if the gain is positive. That is how gamma prunes: a split must improve the loss by more than γ. A larger λ also lowers gain and shrinks weights.
import numpy as np
def leaf_weight(g, h, lam=1.0):
return -g.sum() / (h.sum() + lam)
def split_gain(g, h, mask, lam=1.0, gamma=0.0):
def score(gs, hs):
return gs.sum() ** 2 / (hs.sum() + lam)
left, right = mask, ~mask
return 0.5 * (score(g[left], h[left]) + score(g[right], h[right])
- score(g, h)) - gamma
y = np.array([1.0, 1.2, 3.0, 3.2])
pred = np.full(4, y.mean())
g, h = pred - y, np.ones(4) # squared error
mask = np.array([True, True, False, False])
print(split_gain(g, h, mask))
print(leaf_weight(g[mask], h[mask]))The split separates the low targets from the high ones, so the gain is positive. The left leaf gets a negative weight because its samples sit below the mean.
Exercise
A leaf has G = −6 and H = 4. With λ = 2, what is the optimal leaf weight, and what happens to its magnitude if λ is raised to 8?
Show answer
w = −G / (H + λ) = 6 / 6 = 1. With λ = 8, w = 6 / 12 = 0.5. A larger λ shrinks the leaf weight toward zero.