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 , 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:
- 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.
- Second order throughout. It approximates loss by its Taylor expansion through the second derivative. This yields closed forms for each leaf’s optimal weight, , and each split’s exact gain, which decides the tree shape.
- 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 from 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 addresses a different kind of overfitting. 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 playing the role of its ). is a ridge penalty on weights that, as you will see, shrinks less informative leaves more. is the lasso version; the paper writes only and , but the library also offers (reg_alpha). With classical gradient boosting is recovered.
Since depends on functions rather than a parameter vector, it is not minimized in one go: training is additive, as in the previous lesson. If is the prediction after rounds, round seeks the tree minimizing
then updates . Rate (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 over all possible trees is intractable, and has no convenient form for most losses. The trick is to approximate loss by its second-order Taylor expansion around the current prediction. With
we have . Dropping the constant term, the round’s objective becomes
Notice the sign of : it is the gradient, so the previous lesson’s pseudo-residual is . All loss information used in the round is in the pairs : XGBoost can train on any loss given these two derivatives, exactly what you will do at the end of the lesson.
| Loss | |||
|---|---|---|---|
squared (reg:squarederror) | |||
logistic (binary:logistic), , | |||
Poisson (count:poisson), |
For logistic loss, is the margin (log-odds), not probability; Hessian is at most when the model is uncertain (), 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 fixed, for all , and the sum over examples is rearranged by leaves. Writing and :
There is no longer coupling: this is a sum of 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 scores the structure like an impurity, but derived for any loss.
Proof
Each summand is a strictly convex parabola because , and vanishes at . Substitution gives . As leaves share no variables, the minimum of the sum is the sum of minima. With , the summand is , convex; its subdifferential at contains if and only if with . If , use with ; otherwise has the sign of and . This is the same soft threshold as in lasso coordinate descent, and the optimal value is .
∎The assumption is not decorative. With convex losses, and suffices, or the leaf must have curvature. With nonconvex loss, a leaf with makes the parabola open downward: is then a maximum and the formula steps in the wrong direction. We return to this for custom losses.
Three interpretations of the formula made visible by the figure:
- shrinks in proportion to lack of information. : the unregularized Newton step multiplied by . 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, and leave the weight at of the Newton step.
- With squared loss it is ridge. , and : the mean leaf residual, shrunk toward zero as in one-parameter ridge regression. With 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 receive very different weights if in one the model is uncertain () and in the other confident (): in the latter, the same probability error is a much larger surprise on the logit scale, and Newton wants to move more. prevents that step from exploding when .
Newton boosting
The leaf parabola connects to optimization. Fix the structure and consider leaf ‘s one-dimensional problem, . A Newton method step from is : XGBoost’s weight is exactly one Newton step on the regularized leaf loss. Denominator term is Levenberg–Marquardt: adding to curvature shortens the step when curvature is small and leaves it nearly intact when large, while rate acts as the reduced step of damped Newton, albeit fixed and without line search.
The structure is second-order too. Completing the square,
so, when all , building the round’s tree is equivalent to fitting a regression tree by weighted least squares to targets (per-sample Newton steps) with weights . 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 and calls them “labels ”; 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, . There are therefore three natural variants:
| Variant | Tree structure | Leaf values |
|---|---|---|
| gradient | least squares on | mean of |
| hybrid (TreeBoost) | least squares on | Newton step |
| Newton (XGBoost) | second-order gain |
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, , 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 splits into and , only that leaf’s terms change:
This is equation (7) of the paper, the formula XGBoost evaluates billions of times. Three consequences:
- With squared loss and it is CART. With , 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 . XGBoost’s criterion generalizes variance reduction to any loss.
- is a gain threshold, not a rate. A split is accepted if the bracket exceeds . The same charging each leaf in the objective prunes the tree. Do not confuse it with : decides which splits exist; scales weights afterward.
min_child_weightlimits Hessian, not example count. XGBoost discards any split leaving a child with or belowmin_child_weight(default 1). With squared loss and it is equivalent to a minimum example count per leaf; with logistic loss, , and a thousand examples with sum to . The more confident the model, the more examples are needed to split.
The initial state demonstrates a general fact: if all Hessians are equal, , and , second-order gain is first-order gain divided by , and both choose the same split. The difference appears once the model has learned something and Hessians vary. In the confident state, region has and : in probability, three ones where were expected is a modest error, but the Newton step to correct it, , is a log-odds change comparable to the right region (, , with more examples). Newton measures errors on the margin scale, where the model adds. With it goes further and splits at , inside the confident region. Now raise min_child_weight: the entire confident region has , and the 17 examples left of Newton’s split, . As soon as the minimum exceeds that value, the split is forbidden and the best becomes , 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 , many thresholds have negative gain: splitting worsens the objective even without . This is not a figure error. Each child pays its own 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.
Exact and approximate search
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 and , take and , 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 a small set of candidates , distributes examples into their buckets, sums and 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 , 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.
With , simple candidates are exponential quantiles, : seven numbers between and (the figure’s sample is similar), only the last two in the region where . Weighted candidates spread between and , five in that region, and one splits the data like the best exact split, : they recover 100% of its gain versus 88% for simple candidates. With both are far off (18% and 23%). Increasing takes weighted to 100% and simple stays at 88% even with : none of its splits lands in the good gap. Improvement is not monotonic: with they fall to 40% and 54%, because candidates for do not contain those for . With squared loss, 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 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 : missing values enter only through already-known totals and . 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).
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 present entries, trees and maximum depth , the paper gives exact-search cost sorting at each node and with blocks: no longer multiplies. For approximate search with candidates (32 to 100 in practice, according to the paper), binary search for each value’s bucket costs and sorted blocks reduce this to , where 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 and 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 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 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 and , 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 , 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:
- The Hessian must be positive. Weight is a minimum only if , and gain measures an improvement only if leaf parabolas are convex. With a loss nonconvex in the margin, a leaf full of examples with can have : the “optimum” is a maximum, or division by zero. The usual remedy is a lower bound, , 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 and loses its Newton meaning.
max_delta_stepbounds steps. It limits each round; documentation recommends it for logistic regression with highly imbalanced classes, where in pure leaves.base_scoreis the initial margin. With a custom objective XGBoost does not know what prediction means and usesbase_score = 0.5as initial margin (you will verify this locally). For a logit this starts at . Setbase_scoremanually: , or the base-rate logit.
The canonical nonconvex example is focal loss (Lin et al., 2017), with if and if , which downweights easy examples. For it is logistic. For it ceases to be convex in the margin: with and , the Hessian reaches its minimum, , at , 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 , versus its exact loss optimum.
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 , the Newton step is : the parabola is so flat () that its minimum is far away, while the leaf’s exact logistic loss optimum is . The second-order approximation is faithful only near , 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 and diverges. With , and the exact regularized loss optimum is : the two approach because keeps the step where the parabola resembles loss. This is the measured Levenberg–Marquardt role of . Rate 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 and , 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 and the boosting loop. Gain is stored on the paper’s scale, with .
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 , the feature generating labels, but , unrelated except through its missing values: half the ones lack . Split with missing values left effectively isolates missing values (plus the few values below ), an almost pure leaf of ones with weight ; and 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, with l2_regularization in the role of , and the same gain without . 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.
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.
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 and versus and 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 ( and ), 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 ( and ): 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 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.
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 (, and in the first repetition): missingness says nothing, so treatment matters little. With label-linked missingness native NaN beats mean imputation in both repetitions ( versus and versus ), while imputation plus indicator lies between. The advantage is real but small, for a reason: with mean imputation all missing values share , and a tree can isolate them with two splits, and , 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 because its steps are much shorter; with 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 as Newton: .
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: after 20 trees versus gradient’s even using , and after 100 versus . The reason is in the first figure: with , Newton step is at least four times first-order , and in confident leaves much more. But test matters. Best test loss is for Newton and hybrid, and 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 , , and min_child_weight together. It then reproduces hist by giving our tree candidates calculated by XGBoost, and finally tests pruning with XOR.
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 ""))npm run lab and open the connection link.With tree_method="exact", margins match to (XGBoost’s float32 precision) on training and test, and trees have the same leaves: 14, 13, 14, 12, 15… The root is the same, with missing values left, and the dump’s gain, , 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 . But giving our tree the 256 per-feature candidates calculated by XGBoost (get_quantile_cut) and requiring while growing instead of pruning afterward makes training margins match again to . 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 , 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 and according to label, and asymmetric squared loss where undershooting costs times more than overshooting, , with and . Its population minimizer is not the mean but the expectile.
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"])npm run lab and open the connection link.Focal derivatives match finite differences, and the Hessian with drops to at . 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 can break a round, depending on data and initialization.
Two more results deserve attention. The focal model ranks as well as logistic (AUC versus ), but mean is when positive rate is : its margins are not calibrated log-odds, reflected in log-loss ( versus ). If you need probabilities, recalibrate. CPU and GPU also produce different models: margin correlation is and mean difference , 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
tree_method='exact', above what value of XGBoost parameter gamma is that split pruned (assuming both children are leaves)?objective='reg:squarederror', what does min_child_weight control?binary:logistic and min_child_weight = 1 (default), what happens when seeking a split?More than one answer may be correct.
objective='reg:squarederror', how do Hessian-weighted approximate-search candidates differ from simple feature quantiles?Step 1 of 4. How do you rearrange the sum over examples?
Step 1 of 4. What inequality do you need?
split_gain(GL, HL, GR, HR, lam, gamma), returning , 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 min_child_weight and min_child_weight. Return (gain, threshold, missing_left) with greatest gain (including ), 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 NoneSummary
- The objective is loss plus . With fixed structure, leaves decouple: (soft threshold at if ), provided .
- shrinks the Newton step by : greatly in leaves with little Hessian (few data or, in logistic loss, extreme predictions). In the example leaf, and leave weight versus the unregularized step .
- Split gain is . With squared loss and it is CART’s variance reduction; with it is never negative, with it can be. The library uses the scale without : its
gammais , andexactprunes afterward whilehistprunes during growth. min_child_weightis a minimum Hessian sum: it counts examples for squared loss and almost nothing where a classifier is confident.- Approximate search proposes about candidates per feature that distribute Hessian, not examples, because the round’s tree is weighted least squares with weights (on targets ). With logistic loss they concentrate where the model is uncertain. Today
approxweights with Hessian each tree andhist, 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 from exact search), feature parallelism, per-thread buffer against cache misses (twice as fast on 10 million rows), -row blocks, compression (26% to 29%) and disk sharding for out-of-core work.
- A custom loss needs only and with respect to margin. Check both with finite differences, lower-bound if nonconvex (focal with reaches ) and set
base_score, which for a custom objective is 0.5 on the margin.