AI Wiki中文/EN

XGBoost: score the next tree with gradients and curvature

XGBoost

Derive regularized second-order leaf weights and split gain, then audit exact stump boosting and shrinkage.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Give the next tree a correction to make

Four samples have feature values 0, 1, 2, 3 and targets 0, 0, 4, 4. Suppose the current model predicts zero everywhere. The next tree should leave the first two samples alone and raise its prediction for the last two. But how large should that correction be, and is the extra leaf worth its penalty?

XGBoost couples that question to a regularized objective. It uses derivatives of the current loss to score a proposed tree, solves for the best leaf corrections within that structure, and searches structures greedily. Chen and Guestrin’s 2016 paper also addresses how those calculations reach large, sparse datasets through split-search and memory-layout designs. Original paper, sections 2–4.

This chapter implements the objective calculation and several rounds of one-feature regression stumps. Every arithmetic result is exact. It does not implement the XGBoost library, distributed training or its full set of objectives. The broader stagewise idea belongs to gradient boosting; the distinct focus here is the second-order, regularized tree score.

From derivatives to a leaf score

Let Fᵢ be the current prediction and f the next tree’s correction. The prior trees stay fixed during this round. For a twice-differentiable loss, define its first and second derivatives with respect to the prediction, evaluated at Fᵢ. Dropping terms independent of f gives the local quadratic objective:

Q(f)=∑i[gif(xi)+12hif(xi)2]+γT+λ2∑j=1Twj2,gi=∂Fiℓ(yi,Fi),hi=∂Fi2ℓ(yi,Fi).Q(f)=\sum_i\left[g_i f(x_i)+\frac12 h_i f(x_i)^2\right]+\gamma T+\frac\lambda2\sum_{j=1}^T w_j^2,\qquad g_i=\partial_{F_i}\ell(y_i,F_i),\quad h_i=\partial_{F_i}^2\ell(y_i,F_i).

Here T counts leaves, wⱼ is a leaf correction, and the nonnegative parameters γ and λ penalize leaf count and squared correction size. This is generally a Taylor approximation, not the original loss itself. For our half-squared loss, ℓ(y,F)=(F−y)²/2, it is exact: g=F−y and h=1. We use a sum over samples, not a mean. Changing the loss’s multiplicative convention without changing the penalties changes the optimization problem. Paper, equations 2–4; fixed-release tutorial.

Group samples by their leaf. Let Gⱼ be the sum of gradients and Hⱼ the sum of Hessians in leaf j. Its weight-dependent contribution is Gⱼwⱼ+(Hⱼ+λ)wⱼ²/2. When Hⱼ+λ is strictly positive, completing the square gives:

Gjwj+Hj+λ2wj2=Hj+λ2(wj+GjHj+λ)2−Gj22(Hj+λ),wj∗=−GjHj+λ.G_jw_j+\frac{H_j+\lambda}{2}w_j^2=\frac{H_j+\lambda}{2}\left(w_j+\frac{G_j}{H_j+\lambda}\right)^2-\frac{G_j^2}{2(H_j+\lambda)},\qquad w_j^*=-\frac{G_j}{H_j+\lambda}.

The minus sign matters: a prediction that is too low has a negative gradient under squared loss and receives a positive correction. Hⱼ measures curvature, not necessarily a record count; it equals the count only for our h=1 example. Increasing λ shrinks the magnitude of a fixed leaf’s weight. If Hⱼ+λ is zero or negative, this unique convex minimum is not justified. The program deliberately requires every supplied Hessian to be strictly positive.

Summing the minimized contributions yields the score for a fixed structure:

Q∗(q)=−12∑j=1TGj2Hj+λ+γT.Q^*(q)=-\frac12\sum_{j=1}^T\frac{G_j^2}{H_j+\lambda}+\gamma T.

A lower score is better. This expression has optimized the leaf weights for that structure; it has not found the best structure among all trees. For a proposed split, compare the two-leaf score with the original one-leaf score. Write D for the improvement before the extra leaf penalty:

D=12[GL2HL+λ+GR2HR+λ−(GL+GR)2HL+HR+λ],Gain⁡=D−γ.D=\frac12\left[\frac{G_L^2}{H_L+\lambda}+\frac{G_R^2}{H_R+\lambda}-\frac{(G_L+G_R)^2}{H_L+H_R+\lambda}\right],\qquad \operatorname{Gain}=D-\gamma.

A strictly beneficial split has net Gain greater than zero, equivalently D greater than γ. Do not subtract γ and then demand that the net result exceed γ again. Splitting one leaf into two adds one leaf charge, even though two new leaves appear. Our tie convention keeps the unsplit parent; ties among equally good splits keep the smaller threshold. Paper, equation 7.

Shrinkage is applied after solving for weights

A learning rate η scales the chosen corrections before adding them to F. It does not turn the unshrunk weight into another minimizer of the same quadratic. At a fixed structure, the scaled score is:

Q(ηw∗)=γT−(η−η22)∑jGj2Hj+λ,0<η≤1.Q(\eta w^*)=\gamma T-\left(\eta-\frac{\eta^2}{2}\right)\sum_j\frac{G_j^2}{H_j+\lambda},\qquad 0<\eta\leq1.

Substitute ηw* into each leaf quadratic to obtain this equality. At η=1 it recovers the optimized score. At a smaller rate, the penalty γT remains, while the reduction is damped. Consequently a negative unshrunk score does not by itself guarantee a negative actual objective change after shrinkage. For nonquadratic losses, Taylor approximation introduces a further distinction. The paper describes shrinkage separately from the regularized leaf solution in section 2.3.

Audit a round before appending it

propose accepts one-dimensional feature values, gradients and strictly positive Hessians. It evaluates the parent and every threshold between adjacent distinct feature values. Duplicated feature values stay together. The inputs and nonnegative penalties must be integers or Fraction values; booleans and floats are rejected. The returned score includes γ once per leaf, and net_gain compares the chosen tree with the parent.

fit specializes those derivatives to half-squared loss and appends the requested number of stumps. The fixed base prediction is unpenalized, and rounds=0 returns that base model. Each appended tree is charged for its leaves, including a root-only tree with a zero weight. This is an explicit fixed-round procedure: it does not compare against the option of appending no tree, tune the round count, or stop automatically when the overall objective would increase. The trace reports the actual change as well as the unshrunk score.

from collections import namedtuple
from fractions import Fraction as F

Stump = namedtuple('Stump', 'threshold left right score')


def number(value):
    if type(value) not in (int, F):
        raise ValueError('use integers or Fractions')
    return F(value)


def vector(values):
    if type(values) not in (list, tuple) or not values:
        raise ValueError('nonempty list or tuple required')
    return tuple(number(x) for x in values)


def propose(xs, gradients, hessians, lam=1, gamma=0):
    xs, g, h = map(vector, (xs, gradients, hessians))
    lam, gamma = map(number, (lam, gamma))
    if len(xs) != len(g) or len(g) != len(h):
        raise ValueError('matching lengths required')
    if lam < 0 or gamma < 0 or any(v <= 0 for v in h):
        raise ValueError('nonnegative penalties and strictly positive Hessians required')

    def leaf(indices):
        G = sum((g[i] for i in indices), F())
        H = sum((h[i] for i in indices), F())
        return -G / (H + lam), -G*G / (2*(H + lam))

    w, objective = leaf(range(len(xs)))
    root = Stump(None, w, w, objective + gamma)
    candidates, chosen = [], root
    values = sorted(set(xs))
    for lo, hi in zip(values, values[1:]):
        threshold = (lo + hi) / 2
        left = tuple(i for i,x in enumerate(xs) if x <= threshold)
        right = tuple(i for i,x in enumerate(xs) if x > threshold)
        a, qa = leaf(left)
        b, qb = leaf(right)
        candidate = Stump(threshold, a, b, qa + qb + 2*gamma)
        candidates.append(candidate)
        if candidate.score < chosen.score:
            chosen = candidate
    return {'root': root, 'candidates': tuple(candidates), 'chosen': chosen,
            'net_gain': root.score - chosen.score}


def value(tree, x):
    return tree.left if tree.threshold is None or x <= tree.threshold else tree.right


def fit(xs, targets, rounds=3, lam=1, gamma=F(1,2), eta=F(1,2), base=0):
    xs, y = map(vector, (xs, targets))
    lam, gamma, eta, base = map(number, (lam, gamma, eta, base))
    if len(xs) != len(y) or type(rounds) is not int or rounds < 0:
        raise ValueError('matching data and nonnegative integer rounds required')
    if lam < 0 or gamma < 0 or not 0 < eta <= 1:
        raise ValueError('nonnegative penalties and 0 < eta <= 1 required')
    predictions = (base,) * len(y)
    loss = sum(((p-t)**2 for p,t in zip(predictions,y)),F()) / 2
    trace = []
    for _ in range(rounds):
        g = tuple(p-t for p,t in zip(predictions,y))
        audit = propose(xs,g,(1,)*len(y),lam,gamma)
        tree = audit['chosen']
        predictions = tuple(p + eta*value(tree,x) for p,x in zip(predictions,xs))
        new_loss = sum(((p-t)**2 for p,t in zip(predictions,y)),F()) / 2
        weights = (tree.left,) if tree.threshold is None else (tree.left,tree.right)
        penalty = gamma*len(weights) + lam*sum(((eta*w)**2 for w in weights),F())/2
        trace.append({'audit':audit,'predictions':predictions,'half_sse':new_loss,
                      'applied_objective_change':new_loss-loss+penalty})
        loss = new_loss
    return {'base':base,'eta':eta,'trace':tuple(trace),'predictions':predictions}


def predict(model, xs):
    # model is the unmodified result of fit; empty query sequences are allowed.
    if type(xs) not in (list,tuple):
        raise ValueError('list or tuple of queries required')
    queries = tuple(number(x) for x in xs)
    return tuple(model['base'] + model['eta']*sum(
        (value(step['audit']['chosen'],x) for step in model['trace']),F())
        for x in queries)


if __name__ == '__main__':
    model = fit((0,1,2,3),(0,0,4,4))
    for i,step in enumerate(model['trace']):
        audit=step['audit'];tree=audit['chosen']
        print('round',i,'threshold',tree.threshold,'weights',str(tree.left),str(tree.right),
              'net gain',str(audit['net_gain']),'half SSE',str(step['half_sse']))
    first=model['trace'][0]
    print('first unshrunk / applied:',str(first['audit']['chosen'].score),
          str(first['applied_objective_change']))
    print('predictions:',tuple(str(x) for x in predict(model,(0,1,2,3))))
    tiny=fit((0,1),(-1,1),rounds=1,lam=0,gamma=F(1,10),eta=F(1,100))['trace'][0]
    print('tiny eta unshrunk / applied:',str(tiny['audit']['chosen'].score),
          str(tiny['applied_objective_change']))

Actual output:

round 0 threshold 3/2 weights 0 8/3 net gain 113/30 half SSE 64/9
round 1 threshold 3/2 weights 0 16/9 net gain 377/270 half SSE 256/81
round 2 threshold 3/2 weights 0 32/27 net gain 833/2430 half SSE 1024/729
first unshrunk / applied: -29/3 -7
predictions: ('0', '0', '76/27', '76/27')
tiny eta unshrunk / applied: -4/5 1801/10000

In round zero, the right leaf has G=−8 and H=2, so λ=1 gives weight 8/3 rather than the unregularized residual mean 4. Shrinkage η=1/2 applies only 4/3. The root’s score is −59/10, while the split’s score is −29/3. Their difference is 113/30, the reported net gain. The actual regularized objective change after shrinking is −7; it is not −29/3.

The next rounds recompute gradients from the updated predictions. The right-hand weights become 16/9 and 32/27, and the final prediction there is 76/27. These are additions to the current model, not independent predictions to average. The reported half SSE omits regularization; applied_objective_change adds the new tree’s penalty to the change in that loss. Penalties on earlier trees remain unchanged.

The last line uses targets −1 and 1, λ=0, γ=1/10 and η=1/100. Its unshrunk split score is −4/5, but applying the tiny correction and charging two leaves changes the objective by positive 1801/10000. The raw half SSE still falls. This example prevents two different claims from being conflated: a useful correction to squared error and a decrease in the regularized fixed-round objective.

For n samples, propose takes O(n²) arithmetic/comparison operations and O(n) extra slots: at most n−1 thresholds rescan the sample, and candidate records have constant size. For M rounds, fit takes O(n+Mn²) operations, including input validation when M=0. Its saved per-round predictions and candidate audits take O(n+Mn) slots. Querying m points takes O(1+m(M+1)) operations and O(1+m) extra slots. These are counts for exact rational operations and expected constant-time hashing. Numerator and denominator growth adds bit costs; the program is intended for small examples. predict expects an unmodified fit result, and accepts an empty query list.

A scoring formula is not a complete search system

The stump search is exhaustive only over its own one-split candidates. General tree building commonly chooses an immediate split and repeats. A local winner can block a better later partition, and regularized leaf weights do not remove that structural search problem. The CART chapter gives a concrete fixed-tree counterexample. “Exact” threshold search therefore does not mean globally optimal ensemble learning.

The derivative interface also has assumptions. A loss may be nondifferentiable, have unsuitable curvature, or need constraints not represented by a scalar leaf weight. For classification, raw additive scores and probabilities are different quantities; an objective-specific link is required. This example implements neither logistic probabilities nor ranking groups. The half-squared convention makes its Taylor calculation exact and its positive Hessians automatic.

The original system addresses costs absent from the small program. Its weighted quantile sketch proposes approximate thresholds using Hessian mass. Sparsity-aware search learns a default branch for missing entries while scanning observed entries. Its column blocks reuse sorted data, and buffered access addresses cache stalls when fetching derivatives. These designs organize the same gradient statistics while changing which candidates are examined and how memory is used. They are not claims that an omitted sparse entry and a genuine numerical zero always mean the same thing. Paper, sections 3.3–4.2.

Depth, sampling, regularization and number of rounds all affect the model family. Tune them using an appropriate validation procedure and retain a final test set. A low training objective is evidence about the stated optimization target, not a performance guarantee on new data. Smaller η usually requires considering a different round budget; our shrinkage example also shows why a blanket monotonic-objective promise would be false.

Check the sign and count the extra leaf

  1. A leaf has G=−6, H=2. Calculate its weight at λ=1 and at λ=4. Is H always the number of samples? Answer: the weights are 2 and 1. H is the sum of loss curvatures; it equals the sample count only when each Hessian is one, as in our half-squared loss.
  2. Two samples have gradients −1 and 1, Hessians one, λ=0 and γ=3/4. Should a split separating them be kept? Answer: D=1 and net gain is 1/4, so yes. Comparing that net gain with γ again would incorrectly reject it. At γ=1 the split ties the parent, and our convention keeps the parent.
  3. Why does the first example apply 4/3 to its right leaf even though the optimal leaf weight is 8/3? Is the score −29/3 the actual change? Answer: η=1/2 scales the optimized weight afterward. The unshrunk score is −29/3; the applied regularized objective change is −7. They refer to different corrections.
  4. Replace the half-squared loss by the full squared loss, doubling both gradients and Hessians. How should λ and γ change to preserve the same unshrunk tree choices and weights? Answer: double both penalties as well. Every objective and gain then doubles, while −G/(H+λ) stays unchanged. Keeping the old penalties would change their strength relative to the data loss.

The score and the system solve different bottlenecks

The 2016 paper explicitly connects its second-order formulation to earlier boosting work; its contribution also includes sparse split finding, a weighted quantile sketch and an integrated scalable implementation. The fixed-release tutorial develops the leaf score and greedy structural search. Together they explain why reproducing a leaf formula is useful but insufficient to reproduce a large training system.

A productive next comparison is LightGBM: hold the objective fixed, then change histogram construction, leaf expansion and sampling. Separately, compare an exact candidate scan with coarser proposals on the same derivatives. This separates optimization error caused by the candidate set from changes caused by a different loss, penalty or data split.

Make a prediction, then check

A split improves the unpenalized quadratic by 1 and adds one leaf with gamma=3/4. What is its net gain?

Choose one answer

Learning objectives

  • Derive a regularized leaf weight and the incremental penalty for a split.
  • Distinguish an unshrunk quadratic score from the actual objective change after applying the learning rate.
  • Audit exact stump updates while identifying the additional search and memory mechanisms of the full system.

Prerequisites & connections

Explore related knowledge →

References

  1. XGBoost: A Scalable Tree Boosting System
    Tianqi Chen and Carlos Guestrin · 2016
  2. Introduction to Boosted Trees — XGBoost release 3.0 documentation
    XGBoost contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Seven tests passed. An independent intercept-plus-indicator normal-equation solver verifies 27 full proposal audits. Six three-round trajectories verify all 18 updates and recompute the complete accumulated objective from stored trees.
  • Checked the one-time gamma charge, parent ties, curvature versus counts, ridge shrinkage, scaling all loss terms and penalties, zero rounds and gradients, invalid inputs and input preservation. Exact tiny-rate counterexample: unshrunk score −4/5, applied change 1801/10000.
  • Original complete bilingual prose; identical Python, six actual stdout lines, five displays, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML passed; all five mathematical annotations match. Humanizer reread and AI author checks only; review remains written pending independent review. No library run or repository changes.
  • All seven author tests passed. Independent Fenchel primal/dual equality certificates check every proposed leaf’s convex optimum directly from individual gradients/Hessians, without the author’s intercept/indicator normal-equation solver. Twenty-one complete audits contain 57 structure certificates and 93 leaf certificates, including lambda zero with its dual feasibility constraint, heterogeneous positive curvature, duplicates, singleton inputs and parent/split ties.
  • Direct substitution verifies 171 scaled structure scores. Nine fitted updates also match the certified candidate audit, while independently interpolated scalar loss polynomials verify each applied objective change. Reviewed the fixed-round decision to append even a zero-weight root, the unpenalized base, exact half-SSE convention, unchanged older-tree penalties and the positive tiny-rate counterexample.
  • The complete bilingual derivation is consistent: strictly positive aggregate curvature is needed for the leaf minimum; the API uses stronger pointwise positivity. One extra leaf charges gamma once. Exhaustive one-stump candidates do not imply globally optimal trees or ensembles; shrinkage and Taylor approximation are separately qualified. Sparse missing entries, numerical zeros, Hessian mass and memory-layout claims match the original source scope.
  • Reviewed input validation, stable tie order, zero rounds, query/model contracts and quadratic-time candidate scans with retained audit storage. Strict actual MDX/KaTeX/React HTML passes with five displays, six anchors and four answers per language; all five math annotations match. Every final file SHA and metadata source ID/URL is bound exactly.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
  • The initial test migration used a blank-line boundary and omitted adjacent fence/namespace initialization. Replaced it with the Python AST function end line and restored all statements. All eight migrated tests preserve the non-loader AST, and all 292 classical-learning checks pass. Article, algorithm and independent references are unchanged.

Source locations checked:

  • XGBoost: A Scalable Tree Boosting System · Actually read the 13-page arXiv v3 PDF dated 10 June 2016: sections 2.1–2.3, PDF pages 2–3, equations 2–7, regularizer, derivatives, leaf optimum, split gain and separate shrinkage. Read sections 3.1–3.4, pages 3–5, exact scans, Hessian-weighted quantile proposals and missing-value default branches; sections 4.1–4.2, pages 5–6, sorted column blocks and derivative-access buffers. Text extraction; no benchmark reproduction, copied assets or full-library execution.
  • Introduction to Boosted Trees — XGBoost release 3.0 documentation · Actually opened the fixed release_3.0.0 tutorial, rendered version 3.0.5. Read additive learning, objectives and regularized tree score through greedy search, extracted lines 49–116. The page uses full squared loss in an example; this article explicitly uses half-squared loss. Its prose threshold sentence is ambiguous after displaying net gain; our independently derived test is raw improvement > gamma, equivalently net gain > 0, never charging gamma twice.
  • XGBoost: A Scalable Tree Boosting System · Independently opened the explicit https://arxiv.org/pdf/1603.02754v3, 13 pages, with cover footer dated 10 June 2016. Read sections 2.1–2.3, equations 2–7 for penalties, curvature, leaf scores, split gain and separate shrinkage; section 3.3 for Hessian-weighted thresholds; section 3.4/Algorithm 3 for observed-entry scans and learned missing branches; sections 4.1–4.2 for reusable sorted column blocks and derivative prefetch buffers. Citation retains the exact metadata URL, with the actual version recorded here. No benchmark, appendix-proof or full-library reproduction.
  • Introduction to Boosted Trees — XGBoost release 3.0 documentation · Independently read the fixed release_3.0.0 tutorial rendered 3.0.5, lines 49–116, covering additive fitting, full versus half squared-loss convention, regularized structure scores and greedy split search. The chapter’s net-gain > 0 criterion is correctly derived; it does not repeat the tutorial’s ambiguous statement that the already-penalized gain must exceed gamma. No library execution.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.