Module contents
Lesson 18 of 24Advanced 115 min

Second-order boosting: deriving XGBoost

Derive XGBoost from its regularized objective: second-order Taylor approximation of loss, optimal leaf weight w* = -G/(H + λ), exact split gain and pruning with γ. Then study the algorithmic and systems choices behind its scalability: exact versus Hessian-weighted quantile split search, default direction for sparse or missing values, column blocks and cache-aware access.

After this lesson you can

  • Derive the regularized objective’s second-order approximation and optimal leaf weight w* = -G/(H + λ).
  • Derive split gain and explain γ, λ, α and min_child_weight.
  • Implement a second-order GBDT with exact and Hessian-weighted quantile split search.
  • Explain the sparsity-aware algorithm and why its cost scales with nonzero entries.
  • Write a custom loss with gradient and Hessian and train it using XGBoost on CPU and GPU.

Before you start

Motivation: the same principle, another objective

In the previous lesson you built Friedman’s gradient boosting machine: each round you compute pseudo-residuals ri=−∂ℓ/∂F(xi)r_i = -\partial \ell / \partial F(\vb{x}_i), fit a regression tree to them by least squares, recompute each leaf value by line search and add the tree multiplied by a learning rate. This is gradient descent in a function space and works with any differentiable loss.

XGBoost (Chen and Guestrin, KDD 2016) starts from the same additive scheme and changes three things:

  1. An explicit regularized objective. Instead of fitting residuals and then correcting leaves, it writes one function for the new tree to minimize: loss plus a penalty for leaf count and size of weights.
  2. Second order throughout. It approximates loss by its Taylor expansion through the second derivative. This yields closed forms for each leaf’s optimal weight, w∗=−G/(H+λ)w^* = -G/(H + \lambda), and each split’s exact gain, which decides the tree shape.
  3. A system. Approximate split search with weighted quantiles, an algorithm that scans only present values in sparse data, presorted column blocks, cache-aware memory access and compressed disk blocks.

The paper supports the third part with numbers. Among 29 winning Kaggle competition solutions published on its blog during 2015, 17 used XGBoost (8 only XGBoost); all top-10 teams in KDDCup 2015 used it. The system processed Criteo’s 1700 million examples on one machine with data on disk, and on a cluster of only four machines.

This lesson derives the algorithm from its objective, with all the calculations, then walks through system decisions. At the end you will have an approximately hundred-line XGBoost that reproduces xgboost.train tree by tree with tree_method="exact" and "hist", and know how to write your own losses with gradient and Hessian.

The regularized objective

Separating qq from w\vb{w} organizes the whole derivation: for a fixed structure, choosing weights is an easy continuous problem; choosing structure is the combinatorial problem solved greedily.

Each term of Ω\Omega addresses a different kind of overfitting. γT\gamma T charges for each leaf: a split only pays off if it reduces loss by more than the extra leaf costs, making pruning part of the objective (the same idea as CART’s cost-complexity pruning, with γ\gamma playing the role of its α\alpha). 12λ∥w∥2\frac12\lambda\norm{\vb{w}}^2 is a ridge penalty on weights that, as you will see, shrinks less informative leaves more. α∥w∥1\alpha\norm{\vb{w}}_1 is the lasso version; the paper writes only γ\gamma and λ\lambda, but the library also offers α\alpha (reg_alpha). With γ=λ=α=0\gamma = \lambda = \alpha = 0 classical gradient boosting is recovered.

Since L\mathcal{L} depends on functions rather than a parameter vector, it is not minimized in one go: training is additive, as in the previous lesson. If y^i(t−1)\hat y_i^{(t-1)} is the prediction after t−1t - 1 rounds, round tt seeks the tree minimizing

L(t)(ft)=∑i=1nℓ(yi, y^i(t−1)+ft(xi))+Ω(ft),\mathcal{L}^{(t)}(f_t) = \sum_{i=1}^n \ell\big(y_i,\ \hat y_i^{(t-1)} + f_t(\vb{x}_i)\big) + \Omega(f_t),

then updates y^i(t)=y^i(t−1)+ηft(xi)\hat y_i^{(t)} = \hat y_i^{(t-1)} + \eta f_t(\vb{x}_i). Rate η∈(0,1]\eta \in (0, 1] (eta or learning_rate) is not part of the objective: it is applied after constructing the tree, like Friedman’s shrinkage. The paper describes it as a factor scaling newly added weights after each boosting step.

Second order: each leaf is a parabola

Minimizing L(t)\mathcal{L}^{(t)} over all possible trees is intractable, and ℓ(yi,y^i+f)\ell(y_i, \hat y_i + f) has no convenient form for most losses. The trick is to approximate loss by its second-order Taylor expansion around the current prediction. With

gi=∂ℓ(yi,y^)∂y^∣y^=y^i(t−1),hi=∂2ℓ(yi,y^)∂y^2∣y^=y^i(t−1),g_i = \pd{\ell(y_i, \hat y)}{\hat y}\bigg|_{\hat y = \hat y_i^{(t-1)}}, \qquad h_i = \frac{\partial^2 \ell(y_i, \hat y)}{\partial \hat y^2}\bigg|_{\hat y = \hat y_i^{(t-1)}},

we have ℓ(yi,y^i(t−1)+f)=ℓ(yi,y^i(t−1))+gif+12hif2+o(f2)\ell(y_i, \hat y_i^{(t-1)} + f) = \ell(y_i, \hat y_i^{(t-1)}) + g_i f + \frac12 h_i f^2 + o(f^2). Dropping the constant term, the round’s objective becomes

L~(t)(ft)=∑i=1n[gift(xi)+12hift(xi)2]+Ω(ft).\tilde{\mathcal{L}}^{(t)}(f_t) = \sum_{i=1}^n \Big[g_i f_t(\vb{x}_i) + \tfrac12 h_i f_t(\vb{x}_i)^2\Big] + \Omega(f_t).

Notice the sign of gig_i: it is the gradient, so the previous lesson’s pseudo-residual is ri=−gir_i = -g_i. All loss information used in the round is in the nn pairs (gi,hi)(g_i, h_i): XGBoost can train on any loss given these two derivatives, exactly what you will do at the end of the lesson.

Lossℓ(y,F)\ell(y, F)gghh
squared (reg:squarederror)12(y−F)2\frac12(y - F)^2F−yF - y11
logistic (binary:logistic), y∈{0,1}y \in \{0, 1\}, p=σ(F)p = \sigmoid(F)log⁡(1+eF)−yF\log(1 + e^F) - yFp−yp - yp(1−p)p(1 - p)
Poisson (count:poisson), μ=eF\mu = e^Fμ−yF\mu - yFμ−y\mu - yμ\mu

For logistic loss, FF is the margin (log-odds), not probability; Hessian p(1−p)p(1 - p) is at most 1/41/4 when the model is uncertain (p=0.5p = 0.5), and tends to zero when confident, right or wrong. This asymmetry between samples will appear throughout what follows.

A leaf’s optimal weight

With structure qq fixed, ft(xi)=wjf_t(\vb{x}_i) = w_j for all i∈Iji \in I_j, and the sum over examples is rearranged by leaves. Writing Gj=∑i∈IjgiG_j = \sum_{i \in I_j} g_i and Hj=∑i∈IjhiH_j = \sum_{i \in I_j} h_i:

L~(t)(q,w)=∑j=1T[Gjwj+12(Hj+λ)wj2]+γT(α=0).\tilde{\mathcal{L}}^{(t)}(q, \vb{w}) = \sum_{j=1}^T \Big[G_j w_j + \tfrac12 (H_j + \lambda) w_j^2\Big] + \gamma T \qquad (\alpha = 0).

There is no longer coupling: this is a sum of TT parabolas, one per leaf, each in its own variable.

These two formulas are the optimal leaf weight and split gain that we derive from them: value L~(t)(q)\tilde{\mathcal{L}}^{(t)}(q) scores the structure like an impurity, but derived for any loss.

Proof

Each summand ϕj(w)=Gjw+12(Hj+λ)w2\phi_j(w) = G_j w + \frac12(H_j + \lambda)w^2 is a strictly convex parabola because Hj+λ>0H_j + \lambda > 0, and ϕj′(w)=Gj+(Hj+λ)w\phi_j'(w) = G_j + (H_j + \lambda)w vanishes at wj∗w_j^*. Substitution gives ϕj(wj∗)=−Gj2/(Hj+λ)+12Gj2/(Hj+λ)=−12Gj2/(Hj+λ)\phi_j(w_j^*) = -G_j^2/(H_j + \lambda) + \frac12 G_j^2/(H_j + \lambda) = -\frac12 G_j^2/(H_j + \lambda). As leaves share no variables, the minimum of the sum is the sum of minima. With α>0\alpha > 0, the summand is ϕj(w)+α∣w∣\phi_j(w) + \alpha\abs{w}, convex; its subdifferential at ww contains 00 if and only if Gj+(Hj+λ)w+αs=0G_j + (H_j + \lambda)w + \alpha s = 0 with s∈∂∣w∣s \in \partial\abs{w}. If ∣Gj∣≤α\abs{G_j} \le \alpha, use w=0w = 0 with s=−Gj/αs = -G_j/\alpha; otherwise ww has the sign of −Gj-G_j and w=−(Gj−αsign⁡(Gj))/(Hj+λ)w = -(G_j - \alpha\operatorname{sign}(G_j))/(H_j + \lambda). This is the same soft threshold as in lasso coordinate descent, and the optimal value is −12T⁡α(Gj)2/(Hj+λ)-\frac12\operatorname{T}_\alpha(G_j)^2/(H_j + \lambda).

∎

The assumption Hj+λ>0H_j + \lambda > 0 is not decorative. With convex losses, hi≥0h_i \ge 0 and λ>0\lambda > 0 suffices, or the leaf must have curvature. With nonconvex loss, a leaf with Hj+λ<0H_j + \lambda < 0 makes the parabola open downward: wj∗w_j^* is then a maximum and the formula steps in the wrong direction. We return to this for custom losses.

InteractiveEach leaf is a parabola
Leaf objective versus weight ww
w* = −1.55
  • quadratic with λ\lambda and its minimum w∗w^*
  • same with λ=0\lambda = 0
  • exact logistic loss (+ ½λw²)
  • first-order step
Current probability pip_i per sample (color: label yiy_i; click label to change it)
00.51h=0.03h=0.05h=0.02h=0.04h=0.03h=0.01
What to edit
1.0
6
G=∑giG = \sum g_i1.820
H=∑hiH = \sum h_i0.174 (n = 6)
w∗=−G/(H+λ)w^* = -G/(H+\lambda)−1.551
Newton without λ\lambda: −G/H-G/H−10.484
Shrinkage H/(H+λ)H/(H+\lambda)0.148
Value −12G2/(H+λ)-\tfrac12 G^2/(H+\lambda)−1.411
First order: mean of −gi-g_i−0.303
Exact leaf optimum−1.362
H/(H+λ)=0.15H/(H+\lambda) = 0.15: the leaf has little curvature and λ\lambda dominates the denominator. The weight is less than half the unregularized Newton step.
The bars below are a leaf's samples. In logistic mode drag each current probability pip_i and click its label to change yiy_i; these give gi=pi−yig_i = p_i - y_i and hi=pi(1−pi)h_i = p_i(1 - p_i). Above are parabola Gw+12(H+λ)w2Gw + \tfrac12(H + \lambda)w^2 with minimum w∗w^*, the same with λ=0\lambda = 0 (dashed), the leaf's exact logistic loss (gray), and the first-order step, the mean of pseudo-residuals (aqua). The initial example is a leaf where the model is highly confident (p≈0.97p \approx 0.97) and wrong twice: HH is tiny and λ=1\lambda = 1 eats almost the entire Newton step. Switch to the uncertain leaf and compare shrinkage; raise and lower λ\lambda; remove samples until one remains.

Three interpretations of the formula made visible by the figure:

  • λ\lambda shrinks in proportion to lack of information. w∗=(H/(H+λ))⋅(−G/H)w^* = (H/(H + \lambda)) \cdot (-G/H): the unregularized Newton step multiplied by H/(H+λ)∈[0,1)H/(H + \lambda) \in [0, 1). A leaf with much accumulated curvature (many examples, or uncertain examples in logistic loss) shrinks little; one with little shrinks greatly. In the confident but wrong leaf of the initial example, H=0.174H = 0.174 and λ=1\lambda = 1 leave the weight at 15 %15\,\% of the Newton step.
  • With squared loss it is ridge. hi=1h_i = 1, Hj=njH_j = n_j and wj∗=∑i∈Ij(yi−y^i)/(nj+λ)w_j^* = \sum_{i \in I_j}(y_i - \hat y_i)/(n_j + \lambda): the mean leaf residual, shrunk toward zero as in one-parameter ridge regression. With λ=0\lambda = 0 it is exactly the value of a regression-tree leaf fitted to residuals.
  • With logistic loss, the Hessian weights confidence. Two leaves with the same number of examples and same GG receive very different weights if in one the model is uncertain (h≈0.25h \approx 0.25) and in the other confident (h≈0.03h \approx 0.03): in the latter, the same probability error is a much larger surprise on the logit scale, and Newton wants to move more. λ\lambda prevents that step from exploding when H→0H \to 0.

Newton boosting

The leaf parabola connects to optimization. Fix the structure and consider leaf jj‘s one-dimensional problem, min⁡w∑i∈Ijℓ(yi,y^i+w)+12λw2\min_w \sum_{i \in I_j}\ell(y_i, \hat y_i + w) + \frac12\lambda w^2. A Newton method step from w=0w = 0 is −(derivada)/(segunda derivada)=−Gj/(Hj+λ)-(\text{derivada})/(\text{segunda derivada}) = -G_j/(H_j + \lambda): XGBoost’s weight is exactly one Newton step on the regularized leaf loss. Denominator term λ\lambda is Levenberg–Marquardt: adding λ\lambda to curvature shortens the step when curvature is small and leaves it nearly intact when large, while rate η\eta acts as the reduced step of damped Newton, albeit fixed and without line search.

The structure is second-order too. Completing the square,

∑i[gif(xi)+12hif(xi)2]=∑i12hi(f(xi)−(−gihi))2−∑igi22hi,\sum_i \Big[g_i f(\vb{x}_i) + \tfrac12 h_i f(\vb{x}_i)^2\Big] = \sum_i \tfrac12 h_i \Big(f(\vb{x}_i) - \Big(-\frac{g_i}{h_i}\Big)\Big)^2 - \sum_i \frac{g_i^2}{2h_i},

so, when all hi>0h_i > 0, building the round’s tree is equivalent to fitting a regression tree by weighted least squares to targets −gi/hi-g_i/h_i (per-sample Newton steps) with weights hih_i. This is Newton boosting: rather than following the functional gradient, each round approximates the functional Newton step with a tree. The paper writes this identity in section 3.3 as ∑i12hi(ft(xi)−gi/hi)2\sum_i \frac12 h_i (f_t(\vb{x}_i) - g_i/h_i)^2 and calls them “labels gi/hig_i/h_i”; the correct sign is above, as expanding the square confirms.

The idea predates XGBoost. Friedman, Hastie and Tibshirani (2000) derived LogitBoost as Newton steps on logistic likelihood, and Friedman’s TreeBoost (2001), implemented by scikit-learn’s GradientBoostingClassifier, builds structure by least squares on pseudo-residuals and then assigns each leaf a Newton step, ∑Ijri/∑Ijhi\sum_{I_j} r_i / \sum_{I_j} h_i. There are therefore three natural variants:

VariantTree structureLeaf values
gradientleast squares on ri=−gir_i = -g_imean of rir_i
hybrid (TreeBoost)least squares on rir_iNewton step −Gj/Hj-G_j/H_j
Newton (XGBoost)second-order gain−Gj/(Hj+λ)-G_j/(H_j + \lambda)

Sigrist (2021) compares all three in a common tree-based framework across many datasets: Newton boosting outperforms the other two in predictive accuracy on most, and the paper provides evidence that the advantage is not due to faster convergence. In this lesson’s lab you measure them on a small logistic problem.

Split gain

Now that each structure has a score, −12∑jGj2/(Hj+λ)+γT-\frac12\sum_j G_j^2/(H_j + \lambda) + \gamma T, how do we find a good one? Enumerating all structures is impossible, so grow the tree greedily as in CART: start with one leaf and try splitting each leaf in two. If a leaf with examples II splits into ILI_L and IRI_R, only that leaf’s terms change:

antes:−12 G2H+λ+γ\text{antes:}\quad -\frac12\,\frac{G^2}{H + \lambda} + \gamma
One leaf with G=GL+GRG = G_L + G_R, H=HL+HRH = H_L + H_R: its contribution to optimal value and cost γ\gamma.
1/3

This is equation (7) of the paper, the formula XGBoost evaluates billions of times. Three consequences:

  • With squared loss and λ=0\lambda = 0 it is CART. With hi=1h_i = 1, G2/H=nrˉ2G^2/H = n\bar r^2 is the portion of residual sum of squares explained by a constant, and the bracket is the reduction in sum of squares on splitting: the regression tree’s impurity reduction, multiplied by 12\frac12. XGBoost’s criterion generalizes variance reduction to any loss.
  • γ\gamma is a gain threshold, not a rate. A split is accepted if the bracket exceeds 2γ2\gamma. The same γ\gamma charging each leaf in the objective prunes the tree. Do not confuse it with η\eta: γ\gamma decides which splits exist; η\eta scales weights afterward.
  • min_child_weight limits Hessian, not example count. XGBoost discards any split leaving a child with HLH_L or HRH_R below min_child_weight (default 1). With squared loss H=nH = n and it is equivalent to a minimum example count per leaf; with logistic loss, H=∑pi(1−pi)H = \sum p_i(1 - p_i), and a thousand examples with p=0.999p = 0.999 sum to H≈1H \approx 1. The more confident the model, the more examples are needed to split.
InteractiveSecond-order gain scan
datos (y = 1 arriba, y = 0 abajo) y probabilidad actual p(x)10pseudo-residuo −gᵢ (barras) y hessiana hᵢ (rombos, escala ×4)ganancia de cada umbral−0.3−0.2−0.100.10.2
  • second-order gain (XGBoost)
  • first order, rescaled to same height
  • threshold γ\gamma
  • thresholds rejected by min_child_weight
Cursor: x<0.250x < 0.250, 1 samples on the left.
Model state
1.00
0.00
0.00
threshold x < 0.250
Left: GLG_L, HLH_L0.050, 0.048
Right: GRG_R, HRH_R−6.250, 6.712
Gain − γ at cursor0.057
Best second-order splitx < 4.250
Best first-order splitx < 7.750
Split the node?yes
Second order: x<4.25x < 4.25. First order: x<7.75x < 7.75. At x<4x < 4 the model predicts p=0.05p = 0.05: three ones there are large surprises on the logit scale despite modest probability residuals.
A node with 40 examples in x=0.125,0.375,…,9.875x = 0.125, 0.375, \dots, 9.875 and logistic loss: in x<4x < 4 there are three ones among sixteen; between 4 and 7, alternating ones and zeros; in x≥7x \ge 7, ten ones among twelve. Above, data and current model probability; middle, pseudo-residuals −gi-g_i and Hessians hih_i; below, second-order gain for each threshold (magenta) and first-order gain, the reduction in sum of squared pseudo-residuals, rescaled to the same height (aqua). The cursor accumulates GLG_L and HLH_L as it advances. In the 'confident' state the previous model predicts p=0.05p = 0.05 in x<4x < 4: Newton gain prefers splitting at that region's boundary and first-order gain at x≈7.75x \approx 7.75. Switch to the initial state (p=0.5p = 0.5 for everyone): do they still differ? Lower λ\lambda to 0, raise min_child_weight above 1, and raise γ\gamma until the node stops splitting.

The initial state demonstrates a general fact: if all Hessians are equal, hi=ch_i = c, and λ=0\lambda = 0, second-order gain is first-order gain divided by 2c2c, and both choose the same split. The difference appears once the model has learned something and Hessians vary. In the confident state, region x<4x < 4 has H=16⋅0.0475=0.76H = 16 \cdot 0.0475 = 0.76 and G=16⋅0.05−3=−2.2G = 16 \cdot 0.05 - 3 = -2.2: in probability, three ones where 0.80.8 were expected is a modest error, but the Newton step to correct it, −G/H=2.9-G/H = 2.9, is a log-odds change comparable to the right region (G=−4G = -4, H=3H = 3, −G/H=1.33-G/H = 1.33 with more examples). Newton measures errors on the margin scale, where the model adds. With λ=0\lambda = 0 it goes further and splits at x<3.5x < 3.5, inside the confident region. Now raise min_child_weight: the entire confident region has H=0.76H = 0.76, and the 17 examples left of Newton’s split, HL=1.01H_L = 1.01. As soon as the minimum exceeds that value, the split is forbidden and the best becomes x<7.75x < 7.75, as chosen by first order. The rule that seemed to count examples prevents classification from correcting precisely the regions where the model is most confident.

Notice also that, with λ=1\lambda = 1, many thresholds have negative gain: splitting worsens the objective even without γ\gamma. This is not a figure error. Each child pays its own λ\lambda in the denominator, and a split leaving few examples without a clear signal on one side loses out; the second proof exercise makes this precise.

To find a leaf’s best split, evaluate gain at every threshold of every feature. CART’s split search already did this with an ordered scan, and the paper’s algorithm 1 uses the same idea with second-order statistics: for each feature, sort the leaf’s examples by value, scan accumulating GL+=giG_L \mathrel{+}= g_i and HL+=hiH_L \mathrel{+}= h_i, take GR=G−GLG_R = G - G_L and HR=H−HLH_R = H - H_L, and evaluate gain at each boundary between distinct values. Each scan is linear; sorting is expensive. This is greedy exact search, used by scikit-learn, R’s gbm and XGBoost’s tree_method="exact".

When data do not fit in memory or are distributed across machines, scanning all sorted values in each node is infeasible. Algorithm 2 proposes for each feature kk a small set of candidates Sk={sk1,…,skl}S_k = \{s_{k1}, \dots, s_{kl}\}, distributes examples into their buckets, sums gg and hh per bucket, and searches for the best split only among bucket boundaries. There are two variants:

  • Global proposal: candidates are calculated once per tree at the beginning and used at all levels.
  • Local proposal: candidates are recalculated at each node using its examples, adapting to the region.

Global proposal does less proposal work but needs more candidates, because it does not refine them. The paper measures this on the 10-million-example Higgs dataset (figure 3): local proposal needs fewer candidates, and global matches its accuracy with enough; with a reasonable approximation both reach exact search’s test AUC.

Hessian-weighted quantiles

Where should candidates go? Naturally, use feature quantiles so each bucket has the same amount of data. But the weighted-least-squares identity above says each example weighs hih_i, not 1, for the round’s tree. Thus candidates should distribute Hessian, not examples.

For unweighted data, classical quantile sketches (Greenwald–Khanna and successors) already solved the problem. For weighted data none had guarantees, and the paper presents one as a contribution, with construction and proofs in its appendix. For intuition the definition suffices: with logistic loss candidates cluster where the model is uncertain.

InteractiveWeighted quantile candidates
Distribution of samples and Hessian hi=pi(1−pi)h_i = p_i(1-p_i), with current probability p(x)p(x)
Rank functions: fraction of samples and Hessian with x<zx < z; each split occurs where they cross a multiple of 1/q1/q
  • fraction of samples
  • fraction of Hessian
  • p(x)p(x) of current model (0 to 1 over panel height)
  • exact split
  • plain candidates
  • hh-weighted candidates
8
Candidates
Best exact splitx < 1.75, gain 1.401
Best plain candidate1.233 (88 %)
Best weighted candidate1.401 (100 %)
Splits with 0.1 < p < 0.9plain 2 of 7; weighted 5 of 7
With at most 7 splits, weighted candidates recover 100% of the best exact gain and plain ones 88%: plain candidates spend splits at x<1.5x < 1.5, where p≈0p \approx 0 and there is nothing to correct.
600 values of an exponential feature and a current model with p(x)=σ(2.5(x−2))p(x) = \sigmoid(2.5(x - 2)): almost all data lie in x<1.5x < 1.5, where p≈0p \approx 0, and the Hessian is concentrated between x=1x = 1 and x=2.5x = 2.5 (violet bars). Labels come from a true margin with an extra step of +1.5+1.5 at x>2.3x > 2.3, so there is something to correct exactly where the model is uncertain. Simple candidates (aqua, above) divide samples into qq pieces; weighted candidates (magenta, below) divide Hessian. Below, both rank functions: each candidate lies where one crosses a multiple of 1/q1/q. Readings compare the best gain (λ=1\lambda = 1) among candidates of each kind with exact search. Lower qq to 4 and raise it to 32.

With q=8q = 8, simple candidates are exponential j/8j/8 quantiles, −log⁡(1−j/8)-\log(1 - j/8): seven numbers between 0.130.13 and 2.082.08 (the figure’s sample is similar), only the last two in the region where 0.1<p<0.90.1 < p < 0.9. Weighted candidates spread between 0.60.6 and 2.32.3, five in that region, and one splits the data like the best exact split, x<1.75x < 1.75: they recover 100% of its gain versus 88% for simple candidates. With q=4q = 4 both are far off (18% and 23%). Increasing qq takes weighted to 100% and simple stays at 88% even with q=32q = 32: none of its splits lands in the good gap. Improvement is not monotonic: with q=12q = 12 they fall to 40% and 54%, because candidates for q=12q = 12 do not contain those for q=8q = 8. With squared loss, hi=1h_i = 1 and both quantile types coincide.

According to its documentation the current library offers three search methods: exact scans all values; approx runs the sketch before each tree on all rows using Hessian as weight (the paper’s per-tree global proposal); hist computes candidates once before training using supplied sample weights rather than Hessian, making it fastest. The same documentation recommends hist when Hessian is constant, as in squared regression, because weighting adds nothing there. Since version 2.0, tree_method="auto" uses hist (with lab version 3.4.1, a model trained without a method shows updater grow_quantile_histmaker). Fixed-bin histograms were popularized by LightGBM and you will study them as histogram split finding in the next lesson.

Sparsity and missing values

In real data many X\mat{X} values are absent: nobody measured them, they are zeros not stored in a sparse matrix, or zero columns of a one-hot encoding. CART handled missing values with surrogate splits, requiring extra split searches per node. XGBoost adds a default direction to each node: an example missing the split feature goes left or right according to the node, and that direction is learned from the data.

Each scan costs linear time in the number of present entries, not nn: missing values enter only through already-known totals GG and HH. With a matrix containing 1% nonzero entries this divides work by one hundred. The paper measures this on a 10,000-row sample of Allstate, sparse mainly due to one-hot encoding: sparsity-aware search is over 50 times faster than the naive version scanning all rows (figure 5).

InteractiveDefault direction for missing values
Node samples: present values on the axis and missing values in the NaN box
y=1y=0NaN→ derecha
Gain at each threshold in the two passes (λ = 1)
  • missing sent left
  • missing sent right
  • best gain with mean imputation
Missingness mechanism
0.25
Missing values15 of 60
Fraction of ones: missing / present0.87 / 0.38
Best with missing sent leftx < 5.38: 6.585
Best with missing sent rightx < 4.39: 18.789
Chosen splitx < 4.39, missing sent right
Only “present versus missing”4.419
Imputing mean xx < 3.85: 17.486
Missing values are mostly ones (87% versus 38% among present values): they go right with large xx, and gain exceeds mean imputation (17.486).
A root node with 60 examples, x∼Unif⁡(0,10)x \sim \Unif(0, 10), y∼Bern⁡(σ(0.9(x−5)))y \sim \Bern(\sigmoid(0.9(x - 5))), current model with p=0.5p = 0.5 and λ=1\lambda = 1. Each example is missing xx with probability depending on mechanism: random (π\pi), label-linked (1.8π1.8\pi if y=1y = 1 and 0.2π0.2\pi if y=0y = 0), or linked to xx (2πx/102\pi x/10). Above, present values on the axis and missing values in the NaN box, bordered in the chosen direction's color. Below, gain at each threshold for algorithm 3's two scans and, dotted gray, best gain with mean imputation for xx. Start with missingness linked to yy and compare with random missingness.

When missingness is informative, the default direction exploits it: missing values are grouped with the branch whose mean residual resembles theirs, without anyone creating an indicator feature. When random, missing values resemble the node mean and both curves nearly coincide; the chosen direction matters little for training but decides where new missing values go at prediction. If a node has no missing values in the split feature, the scans tie and the implementation’s tie-breaking rule sets the direction.

The system: what made it scale

The equations above fit on a blackboard. What made XGBoost a standard tool was XGBoost system design, described in section 4 of the paper. Its pieces make sense using what you know about the memory hierarchy.

Presorted column blocks. Sorting is the most expensive part of exact search. XGBoost stores data in compressed-column blocks (CSC, one of the sparse representations you know), with each column already sorted by value once before training. Finding a feature’s best split is then a linear scan of its column, and one scan serves all leaves at a level at once because each entry knows its row’s leaf. With ∥X∥0\norm{\mat{X}}_0 present entries, KK trees and maximum depth DD, the paper gives exact-search cost O(KD∥X∥0log⁡n)\bigO(K D \norm{\mat{X}}_0 \log n) sorting at each node and O(KD∥X∥0+∥X∥0log⁡n)\bigO(K D \norm{\mat{X}}_0 + \norm{\mat{X}}_0 \log n) with blocks: log⁡n\log n no longer multiplies. For approximate search with qq candidates (32 to 100 in practice, according to the paper), binary search for each value’s bucket costs O(KD∥X∥0log⁡q)\bigO(K D \norm{\mat{X}}_0 \log q) and sorted blocks reduce this to O(KD∥X∥0+∥X∥0log⁡B)\bigO(K D \norm{\mat{X}}_0 + \norm{\mat{X}}_0 \log B), where BB is maximum rows per block.

Feature parallelism. Each column is scanned independently, so features are distributed among threads with shared memory and each thread accumulates its own statistics. The same format makes column subsampling cheap: simply skip blocks.

Cache-aware access. Sorted blocks have a cost: the column is scanned in value order, but gig_i and hih_i are in row order. Each accumulation makes an indirect access to an unpredictable memory location, and the sum immediately depends on it, so every cache miss stalls the loop. In exact search XGBoost gives each thread a buffer, first copies a batch’s statistics into it, then accumulates over the buffer: the immediate dependency between indirect read and addition becomes a longer one the processor can overlap. This is textbook cache locality. According to figure 7, the cache-aware version is twice as fast on large datasets (10 million rows), where the caption says cache misses matter; million-row datasets are much less affected. In approximate search the remedy is block size: with small blocks each thread does little work, while with large ones statistics do not fit in cache; the paper settles on 2162^{16} examples per block.

Out-of-core blocks. When data do not fit in RAM, blocks are stored on disk and a separate thread fetches them while another computes. Since disk is the bottleneck, the paper adds two techniques. Block compression compresses each column with a general-purpose compressor and stores row indices as 16-bit offsets from the block start, requiring 2162^{16} rows per block; the paper reports approximately 26%–29% compression ratio on most datasets. Disk sharding alternates blocks among disks with a reader thread per disk. On Criteo, compression speeds things up threefold and splitting across two disks another twofold.

Single-machine performance. With exact search, 500 trees and the Higgs-1M subset, the paper measures (table 3) 0.6841 s per tree and test AUC 0.8304 for XGBoost, 28.51 s and 0.8302 for scikit-learn, and 1.032 s and 0.6224 for R’s gbm, which expands only one branch per tree. These figures are from 2016 on a machine with two eight-core Xeons: what remains useful today is the order of magnitude and its cause.

Since then the design’s focus has shifted. The default method is hist, which discretizes each feature into fixed bins (256 by default, max_bin) and accumulates histograms of gg and hh, and the library also runs it on GPU with device="cuda". This lesson’s logic does not change: gain, weights, default direction and min_child_weight are the same; candidate origins change. Scaling to many GPUs and distributed tree models connects with distributed training later in the course.

Custom losses

Since each round uses only (gi,hi)(g_i, h_i), changing loss means writing a function returning them. With the native API, xgb.train(params, dtrain, num_boost_round, obj=mi_objetivo) calls mi_objetivo(pred, dtrain) each round with current (untransformed) margins and expects two arrays, gradient and Hessian with respect to the margin. Three cautions:

  1. The Hessian must be positive. Weight −G/(H+λ)-G/(H + \lambda) is a minimum only if H+λ>0H + \lambda > 0, and gain measures an improvement only if leaf parabolas are convex. With a loss nonconvex in the margin, a leaf full of examples with hi<0h_i < 0 can have H+λ≤0H + \lambda \le 0: the “optimum” is a maximum, or division by zero. The usual remedy is a lower bound, hi←max⁡(hi,ε)h_i \leftarrow \max(h_i, \eps), or an always-positive substitute Hessian (Gauss–Newton or expected Hessian, such as Fisher information). If the Hessian is zero, as in absolute loss, the step is governed by λ\lambda and loses its Newton meaning.
  2. max_delta_step bounds steps. It limits ∣wj∣\abs{w_j} each round; documentation recommends it for logistic regression with highly imbalanced classes, where H→0H \to 0 in pure leaves.
  3. base_score is the initial margin. With a custom objective XGBoost does not know what prediction means and uses base_score = 0.5 as initial margin (you will verify this locally). For a logit this starts at p=σ(0.5)=0.62p = \sigmoid(0.5) = 0.62. Set base_score manually: 00, or the base-rate logit.

The canonical nonconvex example is focal loss (Lin et al., 2017), ℓ=−(1−pt)γflog⁡pt\ell = -(1 - p_t)^{\gamma_f}\log p_t with pt=pp_t = p if y=1y = 1 and 1−p1 - p if y=0y = 0, which downweights easy examples. For γf=0\gamma_f = 0 it is logistic. For γf>0\gamma_f > 0 it ceases to be convex in the margin: with γf=2\gamma_f = 2 and y=1y = 1, the Hessian reaches its minimum, −0.0472-0.0472, at z≈−3.85z \approx -3.85, i.e., very badly misclassified positive examples. Its derivatives, bounding and CPU and GPU training are in the local lab, alongside an asymmetric squared loss penalizing undershooting more than overshooting. This is its most common practical use: when error cost is asymmetric (stockouts, a position whose P&L depends on error sign), the trained loss should match what is paid. You will return to this when building return prediction models.

Implementation from scratch

Start with the pieces: logistic gradient and Hessian checked with finite differences, and the first figure’s confident-but-wrong leaf weight, with and without λ\lambda, versus its exact loss optimum.

[ ]Gradient, Hessian and one leafBrowser
import numpy as np

def logistica_gh(y, F):
    p = 1 / (1 + np.exp(-F))
    return p - y, p * (1 - p)

F = np.linspace(-4, 4, 9)
y = (np.arange(9) % 2).astype(float)
perdida = lambda F: np.logaddexp(0, F) - y * F          # log(1 + e^F) - y F, sin desbordamientos
e = 1e-4
g, h = logistica_gh(y, F)
print("error máximo de g:", np.abs(g - (perdida(F + e) - perdida(F - e)) / (2 * e)).max())
print("error máximo de h:", np.abs(h - (perdida(F + e) - 2 * perdida(F) + perdida(F - e)) / e**2).max())

# la hoja «segura que falla» de la primera figura
p = np.array([0.97, 0.95, 0.98, 0.96, 0.97, 0.99])
yh = np.array([0, 1, 1, 0, 1, 1.0])
z = np.log(p / (1 - p))
g, h = p - yh, p * (1 - p)
G, H = g.sum(), h.sum()
print(f"\nG = {G:.3f}   H = {H:.4f}   n = {len(p)}")
for lam in [0.0, 1.0]:
    w = 0.0                                               # óptimo exacto: Newton con pasos acotados
    for _ in range(200):                                  # (la pérdida es convexa; sin acotar, diverge)
        q = 1 / (1 + np.exp(-(z + w)))
        w -= np.clip(((q - yh).sum() + lam * w) / ((q * (1 - q)).sum() + lam), -1, 1)
    print(f"lambda = {lam:.0f}:  w* = -G/(H+lambda) = {-G / (H + lam):7.3f}   "
          f"óptimo exacto = {w:7.3f}   encogimiento H/(H+lambda) = {H / (H + lam):.3f}")
print(f"primer orden (media de -g): {-G / len(p):.3f}")

With λ=0\lambda = 0, the Newton step is −10.484-10.484: the parabola is so flat (H=0.1736H = 0.1736) that its minimum is far away, while the leaf’s exact logistic loss optimum is −2.849-2.849. The second-order approximation is faithful only near w=0w = 0, and this step is not close. Notice that even calculating the exact optimum requires bounded steps: pure Newton starting at 0 gives the same first step −10.5-10.5 and diverges. With λ=1\lambda = 1, w∗=−1.551w^* = -1.551 and the exact regularized loss optimum is −1.362-1.362: the two approach because λ\lambda keeps the step where the parabola resembles loss. This is the measured Levenberg–Marquardt role of λ\lambda. Rate η\eta applied afterward shortens the step further, and subsequent rounds correct remaining error.

Now the complete algorithm: losses with gradient and Hessian, leaf weight and score with λ\lambda and α\alpha, algorithm 3’s exact search with default direction for NaN, approximate search with quantile candidates (simple or weighted, global or local), min_child_weight, bottom-up pruning with γ\gamma and the boosting loop. Gain is stored on the paper’s scale, with 12\frac12.

[ ]Minimal XGBoost from scratchBrowser
import numpy as np

class Cuadratica:
    def valor(self, y, F):
        return 0.5 * np.mean((F - y) ** 2)
    def grad_hess(self, y, F):
        return F - y, np.ones_like(F)
    def inicial(self, y):
        return float(np.mean(y))

class Logistica:
    def valor(self, y, F):
        return float(np.mean(np.logaddexp(0.0, F) - y * F))
    def grad_hess(self, y, F):
        p = 1.0 / (1.0 + np.exp(-F))
        return p - y, p * (1.0 - p)
    def inicial(self, y):
        m = np.mean(y)
        return float(np.log(m / (1 - m)))

def umbral_l1(G, alfa):
    return np.sign(G) * np.maximum(np.abs(G) - alfa, 0.0)

def puntuacion(G, H, lam, alfa=0.0):
    """T_alfa(G)^2 / (H + lambda): menos dos veces el valor óptimo de una hoja."""
    T = umbral_l1(G, alfa)
    return T * T / (H + lam)

def peso_hoja(G, H, lam, alfa=0.0):
    return -umbral_l1(G, alfa) / (H + lam)

def candidatos_cuantiles(x, h, q, ponderar=True):
    """Hasta q - 1 umbrales que reparten la masa (de h, o de 1) de los valores presentes en q trozos."""
    presente = ~np.isnan(x)
    x, h = x[presente], h[presente]
    if len(x) == 0:
        return np.empty(0)
    orden = np.argsort(x, kind="stable")
    xs = x[orden]
    w = h[orden] if ponderar else np.ones_like(xs)
    r = np.cumsum(w) / w.sum()                       # función de rango (con <=)
    idx = np.searchsorted(r, np.arange(1, q) / q, side="left")
    c = np.unique(xs[np.minimum(idx + 1, len(xs) - 1)])
    return c[c > xs[0]]                              # «x < mínimo» no separa nada

def mejor_corte(x, g, h, lam, alfa, mcw, cortes=None):
    """Algoritmo 3: mejor (ganancia, umbral, faltantes_a_la_izquierda) de una variable, o None.
    cortes=None: búsqueda exacta, umbral en el punto medio entre valores presentes consecutivos;
    cortes=array: solo esos umbrales, con la regla x < c."""
    presente = ~np.isnan(x)
    G, H = g.sum(), h.sum()
    xp, gp, hp = x[presente], g[presente], h[presente]
    if len(xp) == 0:
        return None
    Gm, Hm = G - gp.sum(), H - hp.sum()              # estadísticos de los faltantes
    if cortes is None:
        o = np.argsort(xp, kind="stable")
        xs = xp[o]
        GL, HL = np.cumsum(gp[o]), np.cumsum(hp[o])
        if (~presente).any():                        # incluye «presentes a un lado, faltantes al otro»
            ok = np.r_[xs[1:] > xs[:-1], True]
            umb = np.r_[(xs[:-1] + xs[1:]) / 2, np.inf]
        else:
            GL, HL = GL[:-1], HL[:-1]
            ok = xs[1:] > xs[:-1]
            umb = (xs[:-1] + xs[1:]) / 2
    else:
        b = np.searchsorted(cortes, xp, side="right")   # cubo de cada valor
        Gb = np.bincount(b, gp, len(cortes) + 1)
        Hb = np.bincount(b, hp, len(cortes) + 1)
        GL, HL = np.cumsum(Gb)[:-1], np.cumsum(Hb)[:-1]
        umb, ok = np.asarray(cortes, float), np.ones(len(cortes), bool)
    base = puntuacion(G, H, lam, alfa)
    mejor = None
    for izq in (False, True):                        # faltantes a la derecha y a la izquierda
        gl, hl = GL + (Gm if izq else 0.0), HL + (Hm if izq else 0.0)
        gan = 0.5 * (puntuacion(gl, hl, lam, alfa) + puntuacion(G - gl, H - hl, lam, alfa) - base)
        valido = ok & (hl >= mcw) & (H - hl >= mcw)
        if not valido.any():
            continue
        gan = np.where(valido, gan, -np.inf)
        k = int(np.argmax(gan))
        if mejor is None or gan[k] > mejor[0] + 1e-12:
            mejor = (float(gan[k]), float(umb[k]), izq)
    return mejor

class ArbolXGB:
    def __init__(self, max_depth=3, lam=1.0, alfa=0.0, gamma=0.0, min_child_weight=1.0,
                 metodo="exacto", q=32, ponderar=True, propuesta="local"):
        self.max_depth, self.lam, self.alfa, self.gamma, self.mcw = max_depth, lam, alfa, gamma, min_child_weight
        self.metodo, self.q, self.ponderar, self.propuesta = metodo, q, ponderar, propuesta

    def ajustar(self, X, g, h):
        self.nodos = []
        if self.metodo != "exacto" and self.propuesta == "global":   # una propuesta por árbol
            self.globales = [candidatos_cuantiles(X[:, k], h, self.q, self.ponderar) for k in range(X.shape[1])]
        self._crecer(X, g, h, np.arange(len(g)), 0)
        self._podar(0)
        return self

    def _cortes(self, X, h, idx, k):
        if self.metodo == "exacto":
            return None
        if self.propuesta == "global":
            return self.globales[k]
        return candidatos_cuantiles(X[idx, k], h[idx], self.q, self.ponderar)   # una propuesta por nodo

    def _crecer(self, X, g, h, idx, prof):
        G, H = g[idx].sum(), h[idx].sum()
        nodo = {"hoja": peso_hoja(G, H, self.lam, self.alfa)}
        self.nodos.append(nodo)
        yo = len(self.nodos) - 1
        if prof >= self.max_depth:
            return yo
        mejor = None
        for k in range(X.shape[1]):
            r = mejor_corte(X[idx, k], g[idx], h[idx], self.lam, self.alfa, self.mcw, self._cortes(X, h, idx, k))
            if r is not None and r[0] > 1e-12 and (mejor is None or r[0] > mejor[0] + 1e-12):
                mejor = (r[0], k, r[1], r[2])
        if mejor is None:
            return yo
        gan, k, u, izq = mejor
        xk = X[idx, k]
        a_izq = np.where(np.isnan(xk), izq, xk < u)
        nodo.update(ganancia=gan, var=k, umbral=u, faltantes_izq=bool(izq))
        nodo["izq"] = self._crecer(X, g, h, idx[a_izq], prof + 1)
        nodo["der"] = self._crecer(X, g, h, idx[~a_izq], prof + 1)
        return yo

    def _podar(self, i):
        """Poda de abajo arriba, como el método exact de XGBoost: se deshace un corte
        cuyos dos hijos son hojas si su ganancia no llega a gamma."""
        n = self.nodos[i]
        if "var" not in n:
            return True
        hi, hd = self._podar(n["izq"]), self._podar(n["der"])
        if hi and hd and n["ganancia"] < self.gamma:
            for c in ("ganancia", "var", "umbral", "faltantes_izq", "izq", "der"):
                n.pop(c)
            return True
        return False

    def predecir(self, X):
        out = np.empty(len(X))
        pila = [(0, np.arange(len(X)))]
        while pila:
            i, idx = pila.pop()
            n = self.nodos[i]
            if "var" not in n:
                out[idx] = n["hoja"]
                continue
            xk = X[idx, n["var"]]
            a_izq = np.where(np.isnan(xk), n["faltantes_izq"], xk < n["umbral"])
            pila += [(n["izq"], idx[a_izq]), (n["der"], idx[~a_izq])]
        return out

    def hojas(self, i=0):
        n = self.nodos[i]
        return 1 if "var" not in n else self.hojas(n["izq"]) + self.hojas(n["der"])

class MiniXGB:
    def __init__(self, perdida, n_arboles=50, eta=0.3, base=None, **kw_arbol):
        self.perdida, self.n_arboles, self.eta, self.base, self.kw = perdida, n_arboles, eta, base, kw_arbol

    def ajustar(self, X, y):
        self.F0 = self.perdida.inicial(y) if self.base is None else self.base
        F = np.full(len(y), self.F0)
        self.arboles = []
        for _ in range(self.n_arboles):
            g, h = self.perdida.grad_hess(y, F)
            arbol = ArbolXGB(**self.kw).ajustar(X, g, h)
            F = F + self.eta * arbol.predecir(X)
            self.arboles.append(arbol)
        return self

    def margen(self, X):
        return self.F0 + self.eta * sum(a.predecir(X) for a in self.arboles)

def mostrar(arbol, i=0, sangria=""):
    n = arbol.nodos[i]
    if "var" not in n:
        print(f"{sangria}hoja: w = {n['hoja']:+.4f}")
        return
    lado = "izquierda" if n["faltantes_izq"] else "derecha"
    print(f"{sangria}x{n['var']} < {n['umbral']:.3f}  (ganancia {n['ganancia']:.3f}, faltantes a la {lado})")
    mostrar(arbol, n["izq"], sangria + "    ")
    mostrar(arbol, n["der"], sangria + "    ")

# un árbol de prueba: logística, dos variables, la segunda con faltantes informativos
rng = np.random.default_rng(0)
X = rng.normal(size=(400, 2))
y = (rng.random(400) < 1 / (1 + np.exp(-2 * X[:, 0]))).astype(float)
X[(y == 1) & (rng.random(400) < 0.5), 1] = np.nan
L = Logistica()
F = np.full(400, L.inicial(y))
g, h = L.grad_hess(y, F)
mostrar(ArbolXGB(max_depth=2, lam=1.0).ajustar(X, g, h))

The test tree shows algorithm 3 in action. The root does not split on x0x_0, the feature generating labels, but x1x_1, unrelated except through its missing values: half the ones lack x1x_1. Split x1<−2.683x_1 < -2.683 with missing values left effectively isolates missing values (plus the few values below −2.68-2.68), an almost pure leaf of ones with weight +1.87+1.87; and x0x_0 appears in the right branch. Missingness was the node’s strongest signal and the tree uses it without an indicator feature. The serious check is different: compare with a reference implementation. scikit-learn’s HistGradientBoostingRegressor uses the same leaf weight, −G/(H+λ)-G/(H + \lambda) with l2_regularization in the role of λ\lambda, and the same gain without 12\frac12. If each feature has fewer than 255 distinct values, discretization loses nothing and possible splits match exact search; with min_samples_leaf=1, no leaf limit and no early stopping, both algorithms should build the same trees.

[ ]Comparison with HistGradientBoostingRegressorBrowser
import numpy as np
from sklearn.ensemble import HistGradientBoostingRegressor

rng = np.random.default_rng(0)
n, d = 1500, 4
X = rng.integers(0, 40, size=(n, d)).astype(float)       # 40 valores distintos por variable
y = np.sin(X[:, 0] / 6) + 0.05 * X[:, 1] * (X[:, 2] > 20) + rng.normal(0, 0.3, n)
Xp = rng.integers(0, 40, size=(500, d)).astype(float)

mio = MiniXGB(Cuadratica(), n_arboles=30, eta=0.3, max_depth=3, lam=1.0, min_child_weight=1e-3).ajustar(X, y)
ref = HistGradientBoostingRegressor(max_iter=30, learning_rate=0.3, max_depth=3, max_leaf_nodes=None,
                                    min_samples_leaf=1, l2_regularization=1.0, early_stopping=False).fit(X, y)
print("máx |diferencia| en entrenamiento:", np.abs(mio.margen(X) - ref.predict(X)).max())
print("máx |diferencia| en puntos nuevos: ", np.abs(mio.margen(Xp) - ref.predict(Xp)).max())
print("hojas de los primeros árboles:", [a.hojas() for a in mio.arboles[:8]])

On training they match to rounding error: the same splits and weights, round after round. A small difference appears on new points, with an instructive cause. When a node has values 3 and 7 but no 4, 5 or 6, any threshold between 3 and 7 separates training data identically. Exact search (ours and XGBoost’s) puts the threshold midway between node values, 5; scikit-learn uses fixed global-discretization thresholds, 3.5. A new point with value 4 falls on different sides.

Exact versus approximate

Now the quantile figure’s experiment at scale: a logistic problem whose first feature is exponential with the model boundary in a low-data region, and at most eight bins per feature. Test logistic loss (20,000 points) for exact search is compared with four approximate variants, in two repetitions with different data.

[ ]Exact, global and local search, simple and weightedBrowser
import numpy as np

def datos(n, semilla):
    r = np.random.default_rng(semilla)
    X = np.column_stack([r.exponential(1.0, n), r.normal(size=n), r.uniform(-3, 3, n), r.lognormal(0, 1, n)])
    F = 2.5 * (X[:, 0] - 2.0) + np.sin(2 * X[:, 2]) + 0.8 * np.log(X[:, 3])
    y = (r.random(n) < 1 / (1 + np.exp(-F))).astype(float)
    return X, y

L = Logistica()
variantes = {
    "exacta": dict(metodo="exacto"),
    "global, simple": dict(metodo="aprox", q=8, ponderar=False, propuesta="global"),
    "global, ponderada": dict(metodo="aprox", q=8, ponderar=True, propuesta="global"),
    "local, simple": dict(metodo="aprox", q=8, ponderar=False, propuesta="local"),
    "local, ponderada": dict(metodo="aprox", q=8, ponderar=True, propuesta="local"),
}
res = {k: [] for k in variantes}
for semilla in [10, 11]:
    X, y = datos(3000, semilla)
    Xp, yp = datos(20000, 100 + semilla)
    for nombre, kw in variantes.items():
        m = MiniXGB(L, n_arboles=40, eta=0.3, max_depth=2, lam=1.0, **kw).ajustar(X, y)
        res[nombre].append((L.valor(y, m.margen(X)), L.valor(yp, m.margen(Xp))))
print(f"{'':20s} {'entrenamiento':>22s} {'prueba':>22s}")
for nombre, v in res.items():
    v = np.array(v)
    print(f"{nombre:20s} {np.array2string(v[:, 0], precision=4):>22s} {np.array2string(v[:, 1], precision=4):>22s}")

The worst variant is the one analysis predicts: global and simple proposal, with test loss 0.26190.2619 and 0.27150.2715 versus 0.24860.2486 and 0.25720.2572 for exact search. Its seven splits per feature are computed once per tree and, for the exponential feature, almost all land where the model is already confident. Hessian weighting nearly fixes it (0.24900.2490 and 0.25810.2581), as does proposing at each node: both local variants match exact. This matches the paper’s Higgs account: local proposal needs fewer candidates, and global, if well done, approaches exact. On training exact search is always best, as it should be, being the only one trying all splits; on test local weighted is even slightly ahead (0.24500.2450 and 0.25620.2562): with only eight buckets, approximation also regularizes by preventing pursuit of very fine splits. Do not take this as law: with two repetitions, differences of 0.0030.003 are within noise.

Missing values: default direction versus imputation

Finally, the practical value of default direction. Three Gaussian features, logistic labels and missing values in the first, random (20%) or label-linked (40% of ones, 2% of zeros). Compare three treatments: leave NaN for algorithm 3 to decide, impute the feature mean, or impute and add a missingness indicator column.

[ ]Informative missing values: NaN, mean or mean plus indicatorBrowser
import numpy as np

def datos_faltantes(n, semilla, informativa):
    r = np.random.default_rng(semilla)
    X = r.normal(size=(n, 3))
    y = (r.random(n) < 1 / (1 + np.exp(-(1.5 * X[:, 0] - X[:, 1] + 0.5 * X[:, 2])))).astype(float)
    pm = np.where(y == 1, 0.4, 0.02) if informativa else np.full(n, 0.2)
    X[r.random(n) < pm, 0] = np.nan
    return X, y

def imputar(Z, mu, indicador):
    Z = Z.copy()
    falta = np.isnan(Z[:, 0])
    Z[falta, 0] = mu
    return np.column_stack([Z, falta.astype(float)]) if indicador else Z

L = Logistica()
for informativa in [False, True]:
    res = {"NaN nativo": [], "media": [], "media + indicador": []}
    for semilla in [0, 1]:
        X, y = datos_faltantes(3000, semilla, informativa)
        Xp, yp = datos_faltantes(20000, 50 + semilla, informativa)
        mu = np.nanmean(X[:, 0])
        for nombre, (A, B) in {"NaN nativo": (X, Xp),
                               "media": (imputar(X, mu, False), imputar(Xp, mu, False)),
                               "media + indicador": (imputar(X, mu, True), imputar(Xp, mu, True))}.items():
            m = MiniXGB(L, n_arboles=40, eta=0.3, max_depth=2, lam=1.0).ajustar(A, y)
            res[nombre].append(L.valor(yp, m.margen(B)))
    print("ausencia", "ligada a y" if informativa else "al azar   ",
          {k: np.round(v, 4).tolist() for k, v in res.items()})

With random missingness all three yield the same test loss to the third digit (0.52170.5217, 0.52090.5209 and 0.52080.5208 in the first repetition): missingness says nothing, so treatment matters little. With label-linked missingness native NaN beats mean imputation in both repetitions (0.40620.4062 versus 0.41170.4117 and 0.41670.4167 versus 0.42140.4214), while imputation plus indicator lies between. The advantage is real but small, for a reason: with mean imputation all missing values share xˉ\bar x, and a tree can isolate them with two splits, x<xˉ+δx < \bar x + \delta and x≥xˉ−δx \ge \bar x - \delta, though mixed with present values near the mean. Default direction achieves it in one split without mixing, and the indicator column with one split on itself. With depth-2 trees, the saved split matters.

Gradient, hybrid and Newton

The final experiment revisits the three boosting variants. On the same logistic approximate-search problem, train 100 depth-3 trees: gradient (first-order structure and leaves, with η=1\eta = 1 because its steps are much shorter; with η=0.3\eta = 0.3 it does not even reach its best test in 100 trees), TreeBoost hybrid, and Newton, all using exact search. For an equal comparison, hybrid leaves use the same λ=1\lambda = 1 as Newton: −Gj/(Hj+λ)-G_j/(H_j + \lambda).

[ ]Gradient, hybrid and Newton boostingBrowser
import numpy as np

def hoja_de(arbol, X):
    out = np.empty(len(X), int)
    pila = [(0, np.arange(len(X)))]
    while pila:
        i, idx = pila.pop()
        n = arbol.nodos[i]
        if "var" not in n:
            out[idx] = i
            continue
        xk = X[idx, n["var"]]
        a_izq = np.where(np.isnan(xk), n["faltantes_izq"], xk < n["umbral"])
        pila += [(n["izq"], idx[a_izq]), (n["der"], idx[~a_izq])]
    return out

def boosting(X, y, Xp, yp, modo, eta, K=100, lam=1.0):
    L = Logistica()
    F, Fp = np.full(len(y), L.inicial(y)), np.full(len(yp), L.inicial(y))
    ent, pru = [], []
    for _ in range(K):
        g, h = L.grad_hess(y, F)
        if modo == "Newton":
            a = ArbolXGB(max_depth=3, lam=lam, min_child_weight=0).ajustar(X, g, h)
        else:                                   # estructura por mínimos cuadrados sobre r = -g
            a = ArbolXGB(max_depth=3, lam=0.0, min_child_weight=0).ajustar(X, g, np.ones_like(h))
            if modo == "híbrido":               # TreeBoost: un paso de Newton en cada hoja
                j = hoja_de(a, X)
                for i in np.unique(j):
                    a.nodos[i]["hoja"] = -g[j == i].sum() / (h[j == i].sum() + lam)
        F, Fp = F + eta * a.predecir(X), Fp + eta * a.predecir(Xp)
        ent.append(L.valor(y, F))
        pru.append(L.valor(yp, Fp))
    return np.array(ent), np.array(pru)

X, y = datos(1500, 5)
Xp, yp = datos(10000, 105)
for modo, eta in [("gradiente", 1.0), ("híbrido", 0.3), ("Newton", 0.3)]:
    ent, pru = boosting(X, y, Xp, yp, modo, eta)
    print(f"{modo:9s} eta = {eta:.1f}: entrenamiento tras 20 árboles {ent[19]:.4f}, tras 100 {ent[-1]:.4f};"
          f" mejor prueba {pru.min():.4f} con {pru.argmin() + 1} árboles")

On training, Newton boosting falls much faster: 0.16920.1692 after 20 trees versus gradient’s 0.20870.2087 even using η=1\eta = 1, and 0.08520.0852 after 100 versus 0.12150.1215. The reason is in the first figure: with hi≤0.25h_i \le 0.25, Newton step −G/H-G/H is at least four times first-order −G/n-G/n, and in confident leaves much more. But test matters. Best test loss is 0.25370.2537 for Newton and hybrid, and 0.26020.2602 for pure gradient. Newton reaches it with 18 trees and then starts overfitting, so it needs early stopping. On this problem most advantage comes from a Newton step in leaves (hybrid already reaches the same minimum); second-order structure speeds descent. This is one dataset and one repetition: general conclusions come from Sigrist’s study.

XGBoost locally: equivalence and custom losses

The following cells run on your machine with the xgboost library (3.4.1 in this course’s environment) and, for the second, GPU. The first redefines a compact tree because the local session does not share memory with the browser, and compares it with xgboost.train on logistic data with 15% missing values, using λ\lambda, α\alpha, γ\gamma and min_child_weight together. It then reproduces hist by giving our tree candidates calculated by XGBoost, and finally tests pruning with XOR.

[ ]Your tree versus xgboost.train: exact and histLocal GPU
import json
import numpy as np
import xgboost as xgb

# Versión compacta del árbol de la sección anterior, para tenerla en esta sesión local.
def T(G, a):                                   # umbral L1: signo(G) max(|G| - a, 0)
    return np.sign(G) * np.maximum(np.abs(G) - a, 0.0)

def S(G, H, lam, a):
    return T(G, a) ** 2 / (H + lam)

def mejor_corte(x, g, h, P, cortes=None):
    """Exacto (cortes=None, umbral en el punto medio) o con umbrales candidatos fijos (regla x < c)."""
    pres = ~np.isnan(x)
    G, H = g.sum(), h.sum()
    if cortes is None:
        o = np.argsort(x[pres], kind="stable")
        xs, GL, HL = x[pres][o], np.cumsum(g[pres][o]), np.cumsum(h[pres][o])
        Gm, Hm = G - GL[-1], H - HL[-1]
        if (~pres).any():                      # incluye «todos los presentes a un lado»
            ok, u = np.r_[xs[1:] > xs[:-1], True], np.r_[(xs[:-1] + xs[1:]) / 2, np.inf]
        else:
            GL, HL, ok, u = GL[:-1], HL[:-1], xs[1:] > xs[:-1], (xs[:-1] + xs[1:]) / 2
    else:
        b = np.searchsorted(cortes, x[pres], side="right")
        Gb, Hb = np.bincount(b, g[pres], len(cortes) + 1), np.bincount(b, h[pres], len(cortes) + 1)
        GL, HL, ok, u = np.cumsum(Gb)[:-1], np.cumsum(Hb)[:-1], np.ones(len(cortes), bool), cortes
        Gm, Hm = G - Gb.sum(), H - Hb.sum()
    mejor = None
    for izq in (False, True):
        gl, hl = GL + izq * Gm, HL + izq * Hm
        gan = 0.5 * (S(gl, hl, P["lam"], P["alpha"]) + S(G - gl, H - hl, P["lam"], P["alpha"]) - S(G, H, P["lam"], P["alpha"]))
        gan = np.where(ok & (hl >= P["mcw"]) & (H - hl >= P["mcw"]), gan, -np.inf)
        k = int(np.argmax(gan))
        if np.isfinite(gan[k]) and (mejor is None or gan[k] > mejor[0] + 1e-12):
            mejor = (gan[k], u[k], izq)
    return mejor

def arbol(X, g, h, idx, prof, P, C=None, poda="post"):
    G, H = g[idx].sum(), h[idx].sum()
    nodo = {"hoja": -T(G, P["alpha"]) / (H + P["lam"])}
    if prof < P["max_depth"]:
        cands = [(mejor_corte(X[idx, k], g[idx], h[idx], P, None if C is None else C[k]), k) for k in range(X.shape[1])]
        cands = [(r[0], k, r[1], r[2]) for r, k in cands if r is not None and r[0] > 1e-12]
        if poda == "pre":                      # hist: gamma se exige al crecer
            cands = [c for c in cands if c[0] >= P["gamma"]]
        if cands:
            gan, k, u, izq = max(cands, key=lambda c: c[0])
            xk = X[idx, k]
            a_izq = np.where(np.isnan(xk), izq, xk < u)
            nodo.update(gan=gan, var=k, umbral=u, falt_izq=bool(izq),
                        izq=arbol(X, g, h, idx[a_izq], prof + 1, P, C, poda),
                        der=arbol(X, g, h, idx[~a_izq], prof + 1, P, C, poda))
            hijos_hoja = "var" not in nodo["izq"] and "var" not in nodo["der"]
            if poda == "post" and hijos_hoja and gan < P["gamma"]:   # exact: poda de abajo arriba
                for c in ("gan", "var", "umbral", "falt_izq", "izq", "der"):
                    nodo.pop(c)
    return nodo

def predecir(n, X):
    if "var" not in n:
        return np.full(len(X), n["hoja"])
    xk = X[:, n["var"]]
    a_izq = np.where(np.isnan(xk), n["falt_izq"], xk < n["umbral"])
    out = np.empty(len(X))
    out[a_izq], out[~a_izq] = predecir(n["izq"], X[a_izq]), predecir(n["der"], X[~a_izq])
    return out

def hojas(n):
    return 1 if "var" not in n else hojas(n["izq"]) + hojas(n["der"])

def mi_xgb_logistico(X, y, K, eta, P, C=None, poda="post"):
    F0 = float(np.log(y.mean() / (1 - y.mean())))
    F, arboles = np.full(len(y), F0), []
    for _ in range(K):
        p = 1 / (1 + np.exp(-F))
        a = arbol(X, p - y, p * (1 - p), np.arange(len(y)), 0, P, C, poda)
        F += eta * predecir(a, X)
        arboles.append(a)
    return lambda Z: F0 + eta * sum(predecir(a, Z) for a in arboles), arboles, F0

# datos: cinco variables (float32, como las guarda XGBoost) con un 15 % de faltantes
rng = np.random.default_rng(1)
n, d = 4000, 5
X = rng.normal(size=(n, d)).astype(np.float32).astype(float)
y = (rng.random(n) < 1 / (1 + np.exp(-(1.5 * X[:, 0] - X[:, 1] ** 2 + np.sin(2 * X[:, 2]))))).astype(float)
X[rng.random((n, d)) < 0.15] = np.nan
Xt = rng.normal(size=(2000, d)).astype(np.float32).astype(float)
Xt[rng.random((2000, d)) < 0.15] = np.nan
dtr, dte = xgb.DMatrix(X, label=y, missing=np.nan), xgb.DMatrix(Xt, missing=np.nan)

P = dict(max_depth=4, lam=2.0, alpha=0.5, gamma=1.0, mcw=5.0)      # gamma en la escala del artículo
K, eta = 20, 0.3
mio, arboles, F0 = mi_xgb_logistico(X, y, K, eta, P)
param = dict(objective="binary:logistic", max_depth=P["max_depth"], eta=eta, reg_lambda=P["lam"],
             reg_alpha=P["alpha"], gamma=2 * P["gamma"], min_child_weight=P["mcw"],
             base_score=1 / (1 + np.exp(-F0)))                   # gamma de XGBoost = 2 x gamma del artículo
bst = xgb.train({**param, "tree_method": "exact"}, dtr, K)
for nombre, D, Z in [("entrenamiento", dtr, X), ("prueba", dte, Xt)]:
    dif = np.abs(bst.predict(D, output_margin=True) - mio(Z)).max()
    print(f"exact, {nombre:13s}: máx |margen XGBoost - margen propio| = {dif:.1e}")
arbs = [json.loads(s) for s in bst.get_dump(with_stats=True, dump_format="json")]
cuenta = lambda t: 1 if "leaf" in t else sum(cuenta(c) for c in t["children"])
print("hojas por árbol, propio:  ", [hojas(a) for a in arboles[:10]])
print("hojas por árbol, XGBoost: ", [cuenta(t) for t in arbs[:10]])
r, a0 = arbs[0], arboles[0]
print(f"raíz en XGBoost: {r['split']} < {r['split_condition']:.6f}, faltantes al nodo {r['missing']} (sí = {r['yes']}), gain = {r['gain']:.4f}")
print(f"raíz propia:     f{a0['var']} < {a0['umbral']:.6f}, faltantes a la {'izquierda' if a0['falt_izq'] else 'derecha'}, 2 x ganancia = {2 * a0['gan']:.4f}")

# hist: los mismos parámetros, con los umbrales candidatos que XGBoost calculó una vez y gamma al crecer
bh = xgb.train({**param, "tree_method": "hist", "max_bin": 256}, dtr, K)
ptr, cortes = dtr.get_quantile_cut()                      # por variable: -inf y luego los límites superiores
C = [cortes[ptr[k] + 1:ptr[k + 1]] for k in range(d)]
print("\ncandidatos por variable en hist:", [len(c) for c in C])
mio_h, _, _ = mi_xgb_logistico(X, y, K, eta, P, C=C, poda="pre")
print(f"hist, entrenamiento: máx |diferencia| = {np.abs(bh.predict(dtr, output_margin=True) - mio_h(X)).max():.1e}")
dif_t = np.abs(bh.predict(dte, output_margin=True) - mio_h(Xt))
print(f"hist, prueba: máx |diferencia| = {dif_t.max():.2f} en {np.sum(dif_t > 1e-4)} de {len(Xt)} filas")
print(f"hist sin reproducir sus candidatos (búsqueda exacta): máx |diferencia| = {np.abs(bh.predict(dtr, output_margin=True) - mio(X)).max():.2f}")

# la poda de gamma: exact poda al final, hist al crecer (un XOR lo delata)
Xo = rng.integers(0, 2, size=(400, 2)).astype(float)
yo = np.where(Xo[:, 0] == Xo[:, 1], 1.0, -1.0) + rng.normal(0, 0.1, 400)
do = xgb.DMatrix(Xo, label=yo)
for tm in ["exact", "hist"]:
    b = xgb.train(dict(tree_method=tm, max_depth=2, eta=1.0, gamma=5.0, min_child_weight=0, base_score=0.0), do, 1)
    t = json.loads(b.get_dump(with_stats=True, dump_format="json")[0])
    print(f"XOR con gamma = 5, {tm:5s}: {cuenta(t)} hojas" + (f", gain de la raíz = {t['gain']:.2f}" if "gain" in t else ""))
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With tree_method="exact", margins match to 10−610^{-6} (XGBoost’s float32 precision) on training and test, and trees have the same leaves: 14, 13, 14, 12, 15… The root is the same, x0<0.390468x_0 < 0.390468 with missing values left, and the dump’s gain, 519.4291519.4291, is exactly twice our gain. Matching trees required passing gamma = 2 * gamma: the gain section’s scale warning verified.

With hist, our exact search no longer suffices: margin difference is 1.141.14. But giving our tree the 256 per-feature candidates calculated by XGBoost (get_quantile_cut) and requiring γ\gamma while growing instead of pruning afterward makes training margins match again to 10−610^{-6}. On test 2 of 2,000 rows differ. Since each node separates the same training examples, the difference can only lie in thresholds separating node data identically: when no node training example falls between two consecutive candidates, both have the same gain; our version keeps the first and XGBoost may keep another. A new point in that gap goes to different sides. Finally XOR: with gamma = 5, exact keeps the full four-leaf tree although root gain is 0.440.44, because both children exceed the threshold and pruning is bottom-up; hist never makes the first split and returns one leaf.

The second cell writes two custom objectives and trains them on CPU and GPU: focal loss, whose margin derivatives follow by the chain rule with ∂pt/∂z=s pt(1−pt)\partial p_t/\partial z = s\,p_t(1 - p_t) and s=±1s = \pm 1 according to label, and asymmetric squared loss where undershooting costs a=3a = 3 times more than overshooting, ℓ=12a[y>F](y−F)2\ell = \frac12 a^{[y > F]}(y - F)^2, with g=−a[y>F](y−F)g = -a^{[y > F]}(y - F) and h=a[y>F]h = a^{[y > F]}. Its population minimizer is not the mean but the a/(1+a)=0.75a/(1 + a) = 0.75 expectile.

[ ]Custom losses on CPU and GPULocal GPU
import json
import numpy as np
import xgboost as xgb
from sklearn.metrics import roc_auc_score

def focal_gh(z, y, gam=2.0):
    """Pérdida focal -(1 - p_t)^gam log p_t y sus dos derivadas respecto al margen z."""
    s = np.where(y == 1, 1.0, -1.0)
    q = 1 / (1 + np.exp(-s * z))                 # p_t = sigmoide(s z), dq/dz = s q (1 - q)
    m = 1 - q
    nlq = np.logaddexp(0, -s * z)                # -log p_t, estable
    df = -gam * m ** (gam - 1) * nlq - m ** gam / q
    d2f = gam * (gam - 1) * m ** (gam - 2) * nlq + 2 * gam * m ** (gam - 1) / q + m ** gam / q ** 2
    dq, d2q = s * q * m, q * m * (1 - 2 * q)
    return df * dq, d2f * dq ** 2 + df * d2q

# comprobación con diferencias finitas
z = np.linspace(-6, 6, 13)
yz = (np.arange(13) % 2).astype(float)
s = np.where(yz == 1, 1.0, -1.0)
focal = lambda z: (1 - 1 / (1 + np.exp(-s * z))) ** 2 * np.logaddexp(0, -s * z)
e = 1e-4
g, h = focal_gh(z, yz)
print("error de g:", np.abs(g - (focal(z + e) - focal(z - e)) / (2 * e)).max(),
      "  error de h:", np.abs(h - (focal(z + e) - 2 * focal(z) + focal(z - e)) / e ** 2).max())
zz = np.linspace(-10, 10, 20001)
_, h1 = focal_gh(zz, np.ones_like(zz))
print(f"con y = 1, la hessiana mínima es {h1.min():.4f}, en z = {zz[h1.argmin()]:.3f}")

# clasificación con un 5 % de positivos
rng = np.random.default_rng(0)
n, d = 200_000, 20
X = rng.normal(size=(n, d)).astype(np.float32)
F = 1.2 * X[:, 0] - X[:, 1] * X[:, 2] + np.sin(2 * X[:, 3]) - 4.0
y = (rng.random(n) < 1 / (1 + np.exp(-F))).astype(np.float32)
Xtr, ytr, Xte, yte = X[:150_000], y[:150_000], X[150_000:], y[150_000:]
dtr, dte = xgb.DMatrix(Xtr, label=ytr), xgb.DMatrix(Xte, label=yte)
print("tasa de positivos:", round(float(y.mean()), 4))

def objetivo_focal(cota):
    def obj(pred, dtrain):
        g, h = focal_gh(pred, dtrain.get_label())
        return g, (h if cota is None else np.maximum(h, cota))
    return obj

def resumen(nombre, z):
    p = 1 / (1 + np.exp(-z))
    ll = float(np.mean(np.logaddexp(0, z) - yte * z))
    print(f"{nombre:28s} log-loss {ll:.4f}   AUC {roc_auc_score(yte, z):.4f}   media de p {p.mean():.4f}")

base = dict(tree_method="hist", max_depth=6, eta=0.1, base_score=0.0)
z = {}
for dev in ["cpu", "cuda"]:
    b = xgb.train({**base, "device": dev}, dtr, 200, obj=objetivo_focal(1e-6))
    z[dev] = b.predict(dte, output_margin=True)
    resumen(f"focal, h >= 1e-6, {dev}", z[dev])
    if dev == "cuda":
        _, hf = focal_gh(b.predict(dtr, output_margin=True), ytr)
        print(f"   hessianas negativas tras 200 rondas: {np.sum(hf < 0)} de {len(hf)}")
print(f"CPU frente a GPU: media |diferencia de margen| = {np.abs(z['cpu'] - z['cuda']).mean():.3f},"
      f" correlación = {np.corrcoef(z['cpu'], z['cuda'])[0, 1]:.4f}")
z_sin = xgb.train({**base, "device": "cuda"}, dtr, 200, obj=objetivo_focal(None)).predict(dte, output_margin=True)
resumen("focal sin acotar h, cuda", z_sin)
z_log = xgb.train(dict(objective="binary:logistic", tree_method="hist", device="cuda", max_depth=6, eta=0.1), dtr, 200).predict(dte, output_margin=True)
resumen("logística nativa, cuda", z_log)

# regresión: quedarse corto cuesta a = 3 veces más que pasarse
a = 3.0
yr = (np.sin(X[:, 0]) + 0.5 * X[:, 1] + rng.standard_t(3, n)).astype(np.float32)
dtr_r, dte_r = xgb.DMatrix(Xtr, label=yr[:150_000]), xgb.DMatrix(Xte, label=yr[150_000:])

def objetivo_asimetrico(pred, dtrain):
    r = dtrain.get_label() - pred
    w = np.where(r > 0, a, 1.0)
    return -w * r, w

pred_sim = xgb.train(dict(objective="reg:squarederror", tree_method="hist", device="cuda", max_depth=6, eta=0.1), dtr_r, 300).predict(dte_r)
pred_asi = xgb.train(dict(tree_method="hist", device="cuda", max_depth=6, eta=0.1, base_score=0.0), dtr_r, 300, obj=objetivo_asimetrico).predict(dte_r)
for nombre, pr in [("cuadrática", pred_sim), ("asimétrica, a = 3", pred_asi)]:
    print(f"{nombre:18s} fracción de casos con y > predicción: {np.mean(yr[150_000:] > pr):.3f}")

# el margen inicial con un objetivo propio si no se fija base_score
b = xgb.train(dict(tree_method="hist"), dtr_r, 1, obj=objetivo_asimetrico)
print("base_score sin fijarlo, con objetivo propio:", json.loads(b.save_config())["learner"]["learner_model_param"]["base_score"])
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Focal derivatives match finite differences, and the Hessian with y=1y = 1 drops to −0.0472-0.0472 at z=−3.847z = -3.847. On this problem, with 5.3% positives, none of the 150,000 training Hessians is negative after 200 rounds, and bounding or not yields the same model: focal keeps margins away from the dangerous region. Bounding remains mandatory because one leaf with H+λ≤0H + \lambda \le 0 can break a round, depending on data and initialization.

Two more results deserve attention. The focal model ranks as well as logistic (AUC 0.85990.8599 versus 0.85860.8586), but mean pp is 0.1950.195 when positive rate is 0.05260.0526: its margins are not calibrated log-odds, reflected in log-loss (0.26170.2617 versus 0.15570.1557). If you need probabilities, recalibrate. CPU and GPU also produce different models: margin correlation is 0.9790.979 and mean difference 0.0930.093, at the same quality. They are not the same program: GPU has its own candidate and histogram implementation, and in boosting small tree differences change all later gradients. Compare models by metrics, not margin by margin.

Asymmetric squared loss does what it promises: with symmetric squared loss 49.6% of test cases lie above prediction; with asymmetric, 30.6%. Finally, base_score for a custom objective without setting it is 0.5, the initial margin warned about in the custom-loss section.

Common mistakes

Exercises

NumericA leaf's weight
A leaf has G=−12G = -12 and H=5H = 5, with λ=1\lambda = 1 and α=0\alpha = 0. What is its optimal weight w∗w^* (before applying η\eta)?
NumericHessian of a confident, wrong sample
With logistic loss, a sample has label y=0y = 0 and the model assigns it probability p=0.9p = 0.9. What is its Hessian hh with respect to the margin?
NumericIs the split worthwhile?
A node with G=−12G = -12 and H=5H = 5 splits into a left child with GL=−10G_L = -10, HL=2H_L = 2 and a right child with GR=−2G_R = -2, HR=3H_R = 3. With λ=1\lambda = 1 and γ=1\gamma = 1 (paper's scale), what is the split's net gain?
NumericGamma in the library
In the paper's notation, a split's gain before subtracting γ\gamma is 5.25.2. With tree_method='exact', above what value of XGBoost parameter gamma is that split pruned (assuming both children are leaves)?
Quizmin_child_weight with squared loss
With objective='reg:squarederror', what does min_child_weight control?
QuizA thousand examples that cannot split
A leaf has 1,000 examples and the model predicts p=0.999p = 0.999 for all. With binary:logistic and min_child_weight = 1 (default), what happens when seeking a split?
QuizWhat changes the structure
With round gig_i and hih_i already computed, which parameters can change the structure of that round's tree (its splits, not just its weights)?

More than one answer may be correct.

QuizWeighted quantiles with squared loss
With objective='reg:squarederror', how do Hessian-weighted approximate-search candidates differ from simple feature quantiles?
ProofOptimal weight and value of a structure
Prove: With second-order approximation and Ω(f)=γT+12λ∥w∥2\Omega(f) = \gamma T + \tfrac12\lambda\norm{\vb{w}}^2, if Hj+λ>0H_j + \lambda > 0 in all leaves, optimal weight is wj∗=−Gj/(Hj+λ)w_j^* = -G_j/(H_j + \lambda) and optimal objective is −12∑jGj2/(Hj+λ)+γT-\tfrac12\sum_j G_j^2/(H_j + \lambda) + \gamma T.
0
Start from ∑i=1n[gif(xi)+12hif(xi)2]+γT+12λ∑j=1Twj2\sum_{i=1}^n \big[g_i f(\vb{x}_i) + \tfrac12 h_i f(\vb{x}_i)^2\big] + \gamma T + \tfrac12\lambda\sum_{j=1}^T w_j^2, with f(xi)=wq(xi)f(\vb{x}_i) = w_{q(\vb{x}_i)} and fixed structure qq.

Step 1 of 4. How do you rearrange the sum over examples?

ProofCan a split worsen the objective?
Prove: If λ=0\lambda = 0, γ=0\gamma = 0 and HL,HR>0H_L, H_R > 0, every split's gain is nonnegative. With λ>0\lambda > 0 it can be negative.
0
With λ=γ=0\lambda = \gamma = 0, gain is 12[GL2/HL+GR2/HR−(GL+GR)2/(HL+HR)]\tfrac12\big[G_L^2/H_L + G_R^2/H_R - (G_L + G_R)^2/(H_L + H_R)\big]. Write a=GLa = G_L, b=GRb = G_R, x=HLx = H_L, y=HRy = H_R.

Step 1 of 4. What inequality do you need?

CodeThe best second-order split with missing values
Implement split_gain(GL, HL, GR, HR, lam, gamma), returning 12[GL2/(HL+λ)+GR2/(HR+λ)−(GL+GR)2/(HL+HR+λ)]−γ\tfrac12\big[G_L^2/(H_L + \lambda) + G_R^2/(H_R + \lambda) - (G_L + G_R)^2/(H_L + H_R + \lambda)\big] - \gamma, and best_split_second_order(x, g, h, lam, gamma, min_child_weight) for one feature x possibly containing NaN. Consider thresholds at midpoints between consecutive distinct present values; examples with x < umbral go left and NaN go left if missing_left is True, right otherwise. A split is valid only if HL≥H_L \ge min_child_weight and HR≥H_R \ge min_child_weight. Return (gain, threshold, missing_left) with greatest gain (including −γ-\gamma), or None if no valid split has positive gain. Scan sorted present values once per direction (cumulative sums), without evaluating each partition from scratch. Tests compare with brute-force search.
import numpy as np

def split_gain(GL, HL, GR, HR, lam, gamma):
  # tu código
  return 0.0

def best_split_second_order(x, g, h, lam=1.0, gamma=0.0, min_child_weight=0.0):
  """Devuelve (gain, threshold, missing_left) o None."""
  x, g, h = np.asarray(x, float), np.asarray(g, float), np.asarray(h, float)
  presente = ~np.isnan(x)
  # tu código: ordena los presentes, acumula G_L y H_L, y prueba las dos direcciones de los faltantes
  return None
Shift+Enter to run
NumericNewton with squared loss
With squared loss and λ=0\lambda = 0, a leaf has four examples with residuals yi−y^i=1,3,−1,5y_i - \hat y_i = 1, 3, -1, 5. What is its optimal weight?

Summary

Key idea
XGBoost is Newton boosting with a regularized objective. Each round approximates loss by its second-order expansion, making each leaf a parabola: its weight is −G/(H+λ)-G/(H + \lambda), a Newton step with Levenberg–Marquardt damping, and each structure has a closed-form score −12∑Gj2/(Hj+λ)+γT-\tfrac12\sum G_j^2/(H_j + \lambda) + \gamma T, yielding each split’s gain. Everything else (weighted quantiles, default direction, column blocks, cache, disk) is engineering to evaluate that gain across billions of rows.
  • The objective is loss plus Ω(f)=γT+12λ∥w∥2+α∥w∥1\Omega(f) = \gamma T + \tfrac12\lambda\norm{\vb{w}}^2 + \alpha\norm{\vb{w}}_1. With fixed structure, leaves decouple: wj∗=−Gj/(Hj+λ)w_j^* = -G_j/(H_j + \lambda) (soft threshold at GjG_j if α>0\alpha > 0), provided Hj+λ>0H_j + \lambda > 0.
  • λ\lambda shrinks the Newton step by H/(H+λ)H/(H + \lambda): greatly in leaves with little Hessian (few data or, in logistic loss, extreme predictions). In the example leaf, H=0.1736H = 0.1736 and λ=1\lambda = 1 leave weight −1.551-1.551 versus the unregularized step −10.484-10.484.
  • Split gain is 12[GL2/(HL+λ)+GR2/(HR+λ)−G2/(H+λ)]−γ\tfrac12[G_L^2/(H_L + \lambda) + G_R^2/(H_R + \lambda) - G^2/(H + \lambda)] - \gamma. With squared loss and λ=0\lambda = 0 it is CART’s variance reduction; with λ=0\lambda = 0 it is never negative, with λ>0\lambda > 0 it can be. The library uses the scale without 12\tfrac12: its gamma is 2γ2\gamma, and exact prunes afterward while hist prunes during growth.
  • min_child_weight is a minimum Hessian sum: it counts examples for squared loss and almost nothing where a classifier is confident.
  • Approximate search proposes about 1/ε1/\eps candidates per feature that distribute Hessian, not examples, because the round’s tree is weighted least squares with weights hih_i (on targets −gi/hi-g_i/h_i). With logistic loss they concentrate where the model is uncertain. Today approx weights with Hessian each tree and hist, the default, discretizes once.
  • Default direction is learned by scanning only present values twice, with missing values on each side: cost is linear in nonzero entries (over 50 times faster on Allstate-10K) and exploits informative missingness. In sparse matrices unstored means missing, not zero.
  • The system: presorted CSC column blocks (removes log⁡n\log n from exact search), feature parallelism, per-thread buffer against cache misses (twice as fast on 10 million rows), 2162^{16}-row blocks, compression (26% to 29%) and disk sharding for out-of-core work.
  • A custom loss needs only gg and hh with respect to margin. Check both with finite differences, lower-bound hh if nonconvex (focal with γf=2\gamma_f = 2 reaches h=−0.0472h = -0.0472) and set base_score, which for a custom objective is 0.5 on the margin.