Sub topic 5
What XGBoost Adds: A Regularized Objective with Gradients and Hessians
This chapter assumes you know the plain gradient boosting loop from the previous chapter. In that loop, each tree is fit to the negative gradient of the loss. You should also be comfortable with first and second derivatives at an intuitive level. By the end you will know how XGBoost scores a split, why it divides by H + λ, and what gamma, reg_lambda and min_child_weight do inside that formula.
From residuals to a regularized objective
Plain gradient boosting fits each tree to a gradient and then adds it with a learning rate. It does not say how large each leaf value should be, and it has no built-in penalty on tree complexity. Complexity is controlled only indirectly, through depth and the number of rounds.
XGBoost instead defines one objective for the whole ensemble:
Obj = sum_i loss(y_i, yhat_i) + sum_k Omega(f_k)
Omega(f) = gamma * T + 0.5 * lambda * sum_j w_j^2 + alpha * sum_j |w_j|The symbols are:
Tis the number of leaves in a tree.w_jis the output value of leafj.gammais thegammaparameter (also calledmin_split_loss). It charges a fixed cost for every leaf.lambdais thereg_lambdaparameter. It applies L2 shrinkage to leaf values.alphais thereg_alphaparameter. It applies optional L1 shrinkage to leaf values.
Every tree is therefore judged on how much loss it removes and on how much complexity it adds.
The second-order approximation
Trees are added one at a time. When tree t is added, the loss is approximated around the current prediction yhat with a second-order Taylor expansion:
loss(y, yhat + f(x)) ≈ loss(y, yhat) + g * f(x) + 0.5 * h * f(x)^2
g = d loss / d yhat (gradient)
h = d^2 loss / d yhat^2 (hessian)The constant term does not depend on the new tree, so it is dropped. Each sample now contributes only its g_i and h_i. Any loss that has a gradient and a hessian can be plugged in without changing the tree-building code.
| Objective | Gradient `g` | Hessian `h` |
|---|---|---|
| Squared error (`reg:squarederror`) | `yhat - y` | `1` |
| Logistic (`binary:logistic`), `p = sigmoid(yhat)` | `p - y` | `p * (1 - p)` |
For logistic loss, yhat is the raw margin (log-odds), not a probability. The hessian p(1-p) is largest when the model is unsure (p near 0.5) and near zero when it is confident.
Optimal leaf weights and the split gain
Group the samples by leaf. For leaf j, define G_j = sum of g_i and H_j = sum of h_i. Adding the regularizer, the objective for one leaf is G_j * w + 0.5 * (H_j + lambda) * w^2. This is a quadratic in w, so its minimum has a closed form:
w_j* = - G_j / (H_j + lambda)For squared error, H_j is the sample count, so w* is the mean residual shrunk toward zero by lambda. A leaf with few samples is shrunk more, which is the main reason lambda reduces variance.
Plugging w* back in gives each leaf a score of 0.5 * G^2 / (H + lambda). Splitting a node into left and right children has this gain:
Gain = 0.5 * [ G_L^2/(H_L+lambda) + G_R^2/(H_R+lambda)
- (G_L+G_R)^2/(H_L+H_R+lambda) ] - gammaXGBoost evaluates this for each candidate split. It takes the best one only if the gain is positive. That is why gamma acts as pruning: a split must improve the objective by more than gamma, or it is not made.
A worked example by hand
Take four samples with current prediction 0 and targets [4, 2, -2, -4], squared error, and lambda = 1. Then g = -y and h = 1. Consider splitting between the second and third samples.
| Quantity | Left (`4, 2`) | Right (`-2, -4`) | Parent |
|---|---|---|---|
| `G` | `-6` | `6` | `0` |
| `H` | `2` | `2` | `4` |
| Leaf weight `-G/(H+1)` | `2` | `-2` | `0` |
The gain is 0.5 * (36/3 + 36/3 - 0/5) - gamma = 12 - gamma. Note that the left leaf's weight is 2, not the mean residual 3, because lambda shrinks it.
The next block repeats the calculation in NumPy and checks it against a one-tree XGBoost model. With learning_rate=1, base_score=0 and a single depth-1 tree, the model's predictions equal the leaf weights.
import numpy as np
from xgboost import XGBRegressor
X = np.array([[1.0], [2.0], [3.0], [4.0]])
y = np.array([4.0, 2.0, -2.0, -4.0])
lam, gamma = 1.0, 0.0
g = 0.0 - y # yhat - y, with yhat = 0
h = np.ones_like(y) # hessian of squared error
def leaf_weight(g_part, h_part):
return -g_part.sum() / (h_part.sum() + lam)
def score(g_part, h_part):
return g_part.sum() ** 2 / (h_part.sum() + lam)
left, right = slice(0, 2), slice(2, 4)
gain = 0.5 * (score(g[left], h[left]) + score(g[right], h[right])
- score(g, h)) - gamma
print("by hand:", leaf_weight(g[left], h[left]),
leaf_weight(g[right], h[right]), "gain:", gain)
model = XGBRegressor(
n_estimators=1, max_depth=1, learning_rate=1.0,
reg_lambda=lam, gamma=gamma, base_score=0.0,
min_child_weight=1,
)
model.fit(X, y)
print("xgboost:", np.round(model.predict(X), 3))The hand calculation prints weights 2.0 and -2.0 with gain 12.0. The model's predictions should be about [2, 2, -2, -2].
The hessian in practice: custom objectives
Because the tree builder only needs g and h, you can supply your own objective to the native API. The function receives raw margins and the DMatrix, and returns the gradient and hessian arrays.
import numpy as np
import xgboost as xgb
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import train_test_split
X, y = load_breast_cancer(return_X_y=True)
X_train, X_val, y_train, y_val = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=0
)
dtrain = xgb.DMatrix(X_train, label=y_train)
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
def logistic_obj(preds, dmat):
labels = dmat.get_label()
p = sigmoid(preds)
grad = p - labels
hess = np.maximum(p * (1.0 - p), 1e-6) # keep the hessian positive
return grad, hess
params = {"eta": 0.1, "max_depth": 3, "reg_lambda": 1.0, "gamma": 0.0}
booster = xgb.train(params, dtrain, num_boost_round=50, obj=logistic_obj)
margins = booster.predict(xgb.DMatrix(X_val))
pred = (sigmoid(margins) > 0.5).astype(int)
print("accuracy:", (pred == y_val).mean())With a custom objective, predict returns raw margins, so you apply the sigmoid yourself.
How the regularizers show up as parameters
| Parameter | Role in the formulas | Effect |
|---|---|---|
| `reg_lambda` | Added to `H` in the denominator of `w*` and the gain | Shrinks leaf values, most strongly for leaves with small `H` |
| `reg_alpha` | L1 penalty on `w` | Pushes small leaf weights to exactly zero |
| `gamma` | Subtracted from the gain | Blocks splits that gain too little |
| `min_child_weight` | Minimum `H` in each child | Blocks splits that create low-hessian leaves |
Edge cases
- A node whose gain is negative can still have a split with positive gain below it. Growing a tree fully and then pruning bottom-up with
gamma(the older exact-method behavior) can keep such structures. A top-down greedy rule would stop early. Treatgammaas a heuristic, not an exact complexity bound. - With
lambda = 0and tinyH,w* = -G/Hcan explode. The defaultreg_lambda = 1andmin_child_weight = 1guard against this. - A hessian of zero or below breaks the leaf formula. Custom objectives for non-convex losses need a clipped or surrogate hessian, as in the code above.
Exercise
A node has G = -10 and H = 4. It is split into a left child with GL = -8, HL = 3 and a right child with GR = -2, HR = 1. With lambda = 1 and gamma = 0.5, compute the gain and decide whether the split is made. Also give the leaf weight of the left child.
Show answer
Gain = 0.5 [64/4 + 4/2 - 100/5] - 0.5 = 0.5 [16 + 2 - 20] - 0.5 = -1 - 0.5 = -1.5. The gain is negative, so the split is not made and the node becomes a leaf. The left child's weight would have been -GL/(HL + lambda) = 8/4 = 2, but it is never used because the split is rejected.
Exercise
For binary:logistic, a leaf contains 100 samples that all have predicted probability 0.99. Why might minchildweight = 1 prevent a split that creates this leaf?
Show answer
The hessian per sample is p(1 - p) = 0.99 * 0.01 = 0.0099. Summed over 100 samples, H is about 0.99, which is below minchildweight = 1. The split is therefore rejected even though the leaf has many samples.