Skip to main content

XGBoost by hand, part 3: gradients, hessians and classification

machine learning
xgboost
concepts
r
animation
Where the similarity and leaf formulas come from (a second-order Taylor expansion), the same algorithm on a 0/1 target, a min_child_weight trap, and the remaining hyperparameters.
Author

Athos Damiani

Published

December 3, 2026

This is the last part of a series based on a slide deck I made, in Portuguese, that computes XGBoost by hand.

  1. A sum of small trees
  2. How one tree is grown and pruned
  3. Gradients, hessians and classification (this post)

Where the formulas come from

Part 2 used two formulas without explaining them:

\[ \text{leaf output} = \frac{\sum r}{n + \lambda} \qquad \text{similarity} = \frac{(\sum r)^2}{n + \lambda} \]

Each new tree adds a number \(w\) to the prediction of every row in a leaf. The best \(w\) minimizes the loss of those rows, plus a penalty on \(w\):

\[ \sum_{i \in \text{leaf}} L\big(y_i,\ f(x_i) + w\big) + \tfrac{1}{2} \lambda w^2 \]

XGBoost doesn’t minimize this directly. It replaces each \(L\) with its second-order Taylor expansion around the current prediction. With \(g_i\) and \(h_i\), the first and second derivatives of the loss for row \(i\), and \(G\) and \(H\) their sums over the leaf:

\[ \sum_{i} L\big(y_i, f(x_i)\big) + G\,w + \tfrac{1}{2}(H + \lambda)\,w^2 \]

That’s a parabola in \(w\). Its minimum is at

\[ w^* = -\frac{G}{H + \lambda} \]

and at that minimum the loss drops by \(\frac{1}{2}\frac{G^2}{H + \lambda}\). That is the similarity score, without the ½: a split’s gain is how much more the loss drops with two leaves than with one.

For squared error, \(L = \frac{1}{2}(y - f)^2\), so \(g_i = -(y_i - f(x_i)) = -r_i\) and \(h_i = 1\). Then \(G = -\sum r\) and \(H = n\), which gives the formulas from part 2. The parabola is the loss itself, so the leaf output is the exact minimum.

The ½ in the loss is a convention, and xgboost’s reg:squarederror uses it. Without it, \(g = -2r\) and \(h = 2\), and the leaf becomes \(\frac{2 \sum r}{2n + \lambda}\), the same thing with λ halved.

For any other loss, the parabola is only an approximation, and each tree takes one Newton step toward the minimum. That’s why XGBoost works with any loss that has a first and second derivative: you give it \(g\) and \(h\), and the tree-growing code stays the same.

Classification

For a 0/1 target, XGBoost (objective = "binary:logistic") works on the log-odds scale:

  • the model \(f(x)\) is a sum of trees, as before, but its output is a log-odds;
  • the probability is \(p = 1 / (1 + e^{-f})\);
  • base_score = 0.5 is a probability, so the starting log-odds is 0;
  • the loss is the log loss, \(L = -[y \log p + (1 - y) \log(1 - p)]\).

Its derivatives with respect to \(f\) are \(g = p - y\) and \(h = p(1 - p)\), so the residual is still \(y - p\), and the formulas become

\[ \text{leaf output} = \frac{\sum (y - p)}{\sum p(1 - p) + \lambda} \qquad \text{similarity} = \frac{\left(\sum (y - p)\right)^2}{\sum p(1 - p) + \lambda} \]

Same four doses, now with y = 0, 1, 1, 0:

In round 1 every p is 0.5, so the residuals are ±0.5 and each row’s hessian is 0.25. The leaf for doses 8 and 12 outputs (0.5 + 0.5) / (0.25 + 0.25) = 2. Times 0.3 that’s 0.6 on the log-odds scale, and p goes from 0.5 to 0.646. After two trees, p is 0.256 for the zeros and 0.744 for the ones.

A trap: min_child_weight

Fit those four rows with xgboost’s defaults and nothing happens: no split, and every prediction stays at 0.5.

min_child_weight (default 1) is not a minimum number of rows. It’s a minimum cover, the sum of the hessians in a leaf. For squared error \(h = 1\), so cover equals the number of rows. For log loss \(h = p(1 - p)\), which is at most 0.25:

Our root has a cover of 4 × 0.25 = 1, so every possible leaf has less than 1, and XGBoost doesn’t split. With min_child_weight = 0, xgboost reproduces the numbers above:

library(xgboost)

d <- data.frame(dose = c(2, 8, 12, 16), y = c(0, 1, 1, 0))
dtrain <- xgb.DMatrix(as.matrix(d["dose"]), label = d$y)

fit_clf <- function(min_child_weight) {
  xgb.train(
    params = list(
      objective = "binary:logistic", base_score = 0.5, eta = 0.3, max_depth = 2,
      lambda = 0, gamma = 0, min_child_weight = min_child_weight, tree_method = "exact"
    ),
    data = dtrain,
    nrounds = 2
  )
}

predict(fit_clf(min_child_weight = 1), dtrain)
[1] 0.5 0.5 0.5 0.5
fit <- fit_clf(min_child_weight = 0)
xgb.model.dt.tree(model = fit)[, .(Tree, ID, Feature, Split, Gain, Cover)]
     Tree     ID Feature Split       Gain     Cover
    <int> <char>  <char> <num>      <num>     <num>
 1:     0    0-0    dose    14  1.3333334 1.0000000
 2:     0    0-1    dose     5  2.6666668 0.7500000
 3:     0    0-2    Leaf    NA -0.6000000 0.2500000
 4:     0    0-3    Leaf    NA -0.6000000 0.2500000
 5:     0    0-4    Leaf    NA  0.6000000 0.5000000
 6:     1    1-0    dose    14  0.7317489 0.9151370
 7:     1    1-1    dose     5  1.4634978 0.6863527
 8:     1    1-2    Leaf    NA -0.4646435 0.2287842
 9:     1    1-3    Leaf    NA -0.4646435 0.2287842
10:     1    1-4    Leaf    NA  0.4646435 0.4575685
predict(fit, dtrain)
[1] 0.2564231 0.7435769 0.7435769 0.2564231

The Cover column is \(\sum p(1 - p)\): 1 at the first root, 0.915 at the second, once p has moved away from 0.5. The leaves are ±0.6 and then ±0.465, which are ±2 and ±1.549 times 0.3. xgboost splits first at 14 instead of 5. Both have the same gain here (1.33), and the final predictions are the same.

This matters on real data too. With rare events, most predicted probabilities end up close to 0, each row adds almost nothing to the cover, and the default min_child_weight = 1 can need a hundred rows or more per leaf.

Two more hyperparameters: subsample and colsample

subsample gives each tree a random share of the rows. colsample_bytree and colsample_bynode do the same with columns, per tree or per split. Each tree sees a different part of the data, so the trees are less alike and the model depends less on a few rows or a few features.

The hyperparameters, from xgboost to tidymodels

Every hyperparameter in this series, with its xgboost default and its name in parsnip’s boost_tree():

what it does xgboost default parsnip
number of trees nrounds trees
learning rate ε, multiplies each tree eta 0.3 learn_rate
maximum depth of each tree max_depth 6 tree_depth
minimum gain to keep a split, γ gamma 0 loss_reduction
penalty in the leaf and similarity denominators, λ lambda 1 engine argument
minimum cover (sum of hessians) per leaf min_child_weight 1 min_n
share of rows per tree subsample 1 sample_size
share of columns per split colsample_bynode 1 mtry
starting prediction base_score estimated engine argument

mtry is a number of columns, and parsnip converts it to the proportion xgboost expects (counts = TRUE in parsnip::xgb_train()). Engine arguments go in set_engine("xgboost", lambda = 1).

What I left out

  • tree_method = "hist", the default, groups each feature into bins and only tries thresholds between bins. It’s much faster on large data.
  • Missing values: each split learns a default direction for them (the Missing column in xgb.model.dt.tree()).
  • alpha, an L1 penalty on the leaf outputs, next to λ’s L2.

The code for the animations is in this post’s folder on GitHub, and the XGBoost implementation it uses is in part 1’s folder.