July 2026. Math doesn't rot, but library details do - XGBoost version notes reflect 2.x-3.1.
The whole series:
- Part 1 - the Interview tier: trees, forests, and the ten core formulas
- Part 2 - the Practice tier: the knobs you actually turn
- Part 3 - the Theory tier: full derivations and the cheat sheets (you are here)
This is the theory tier: the full derivations behind everything stated in part 1 and part 2, plus the cheat-sheet appendices. If an interviewer ever answers your answer with "why?", this is the part that has your back. Cross-references like I.7 point to part 1, P.3 to part 2.
TIER 3 - [T] THEORY
Full derivations. What lets you answer any follow-up question.
[T.1] The regularized XGBoost objective
The key difference from GBM. In classical GBM regularization is heuristic and external (cap the depth, apply shrinkage). Here the tree's complexity is an explicit term of the objective, so the algorithm itself decides, arithmetically, whether a split pays for itself.
Three components:
- - the price of leaf count => becomes the " " in Gain I.8;
- - ridge on leaf weights => the in the denominator of I.7;
- - lasso on leaf weights => soft-thresholding T.4.
Why this is ridge/lasso "for real". In a linear model the parameters are the coefficients on features; in a tree the parameters are the leaf weights . We penalize exactly those, in exactly the same sense. Different architectures, one idea.
[T.2] The second-order Taylor expansion
Substitute the additive step:
Expand in the small increment around :
where
Dimensions. (vectors, one number per sample). For multiclass - .
Contrast with GBM. Classical boosting uses only (gradient descent in function space). XGBoost adds - the curvature => that's Newton's method, hence "Newton boosting".
What the second order buys.
- An analytic optimum for the leaf weight (a closed formula instead of line search).
- A split criterion consistent with the loss.
- A more accurate step (curvature is taken into account).
Limitations. Requires (otherwise the denominator breaks). For non-convex custom losses the hessian gets clipped. For MAE/quantile, where is constant, the Newton step degenerates => adaptive trees P.1.
[T.3] Regrouping by leaves and deriving the optimal leaf weight
Step 1. The constant doesn't depend on => drop it:
Step 2 (the key trick). A tree predicts a constant within a leaf: if , then . So the sum over samples can be rewritten as a sum over leaves:
This is the moment that makes the problem solvable: the leaves become independent, each optimized separately.
Step 3. Inside a leaf - an ordinary parabola:
Convexity check. whenever and => it's a minimum, not a maximum.
[T.4] Soft-thresholding: how the L1 case is solved
With the term, the leaf's objective is:
The absolute value is non-differentiable at zero => solve via the subgradient. The result is the classic soft-thresholding, as in lasso:
Spelled out:
| Condition | |
|---|---|
Meaning. If the total gradient in a leaf is no larger than in absolute value, the leaf's weight is zeroed out - the leaf predicts exactly zero and contributes nothing.
Comparing and :
| L2 ( ) | L1 ( ) | |
|---|---|---|
| Where it sits | denominator | numerator (a threshold) |
| Effect | proportional shrinkage | shift toward zero, exact zeroing |
| Sparsity | no | yes (zero leaves) |
| Default | 1 | 0 |
Why is less useful in practice than in linear models. In linear regression, L1 zeroes coefficients on features - that's feature selection. In a tree the features are already selected by the structure (the splits); zeroing a leaf's weight doesn't remove a feature from the model, it merely mutes one leaf. Hence the practice: nonzero , usually zero.
Structure score with L1: replace with .
Where else it shows up. Soft-thresholding is the core of ISTA / proximal gradient for lasso, and the solution of in any context.
[T.5] The structure score
Substitute back into the objective (without L1, for cleanliness). The parabola's minimum is , hence:
What this is. A quality measure of a fixed tree structure (which splits, not which weights). The larger , the better (note the leading minus).
The philosophical moment. This is an impurity derived from the loss function, not postulated. Gini and entropy are heuristics; is a consequence. That is why XGBoost doesn't use Gini.
[T.6] Deriving Gain from the structure score
Consider a leaf we're thinking of splitting into and .
Before the split, its contribution to : (one leaf).
After the split: (two leaves).
The gain = (before) − (after), i.e. how much the objective decreased:
Notice: - that's where the " " comes from. A global penalty produced a local rule.
Rule. Split when .
[T.7] Equivalence to weighted least squares: Newton boosting ≈ IRLS
Take the post-Taylor objective and complete the square:
Altogether:
What this means. Every boosting iteration is a weighted-least-squares fit of a tree to the targets with weights .
That is literally IRLS (iteratively reweighted least squares), except the base learner is a tree instead of a linear model.
The parallel with logistic regression:
| Logistic regression | XGBoost | |
|---|---|---|
| Method | Newton-Raphson / Fisher scoring / IRLS | Newton boosting |
| Gradient | , size | , a vector |
| Curvature | , | , a vector |
| Hessian | , size | (a scalar per leaf) |
| Step | solves weighted LS analytically | approximates weighted LS with a tree |
| Regularization | ridge on | ridge on |
Three consequences you should be able to say out loud.
- Why the quantiles are weighted by P.12 - because the problem is weighted LS with weights .
- Why is a weighted average of the individual Newton steps with weights :
- Why in both - one and the same curvature of the logistic likelihood.
Note [T]. This is the strongest card in the whole deck. It shows that logistic regression and boosting are connected in your head.
[T.8] Initializing F0: what the "zeroth tree" predicts
The first thing is not a tree - it's a constant (a global intercept; base_score in XGBoost).
| Loss | Comment | |
|---|---|---|
| MSE | the mean | the "it's the mean" intuition is true exactly here |
| Log-loss | the logit of the base rate | log-odds of the positive share |
| MAE | the median of | |
| Pinball ( ) | the -quantile of | |
| Poisson (log link) |
Critical. lives in margin space (before the inverse link). For classification it's log-odds, not a probability.
The first real tree ( ) is trained on gradients relative to :
- MSE: the tree fits residuals from the mean. This is where "boosting fits residuals" is exact.
- Log-loss: , where is the base rate.
A historical XGBoost trap. Before version 2.0, base_score was a constant 0.5 (even for regression, where that's meaningless). And 0.5 is specified after the inverse link: for logistic tasks it's a probability that internally becomes
. Since 2.0 the intercept is estimated automatically from the target; since 3.1 it's vector-valued for multi-output models.
base_margin. A vector of per-sample starting margins (overrides base_score). Used for stacking: feed another model's raw (pre-link!) predictions so the booster learns a correction on top.
Note [T]. With enough rounds, the value of barely matters - the model re-learns it. It matters with few trees, aggressive early stopping, and for calibration in early iterations. For a custom loss the auto-estimation doesn't work - set it by hand.
[T.9] AdaBoost: the exponential loss and the logit connection
AdaBoost (Freund & Schapire, 1997) was the first boosting algorithm that worked in the wild, and it made an entrance: Breiman, not a man given to hype, called it "the best off-the-shelf classifier in the world" (the quote survives via ESL). It also earned Freund and Schapire a Gödel Prize. Worth knowing not just as history: interviewers love asking how it relates to gradient boosting, and the honest answer (it's the same forward-stagewise frame under a specific loss) is below.
The algorithm (ESL 10.1), step by step.
- Initialize weights .
- For :
- - fit a classifier under weights ;
- - compute the weighted error
- - compute the classifier's weight
- - update the sample weights
- Output: .
Where comes from. AdaBoost is forward stagewise additive modeling with the exponential loss , . Minimizing over the coefficient gives ; ESL's notation takes , which is why the is absent.
The most beautiful fact - the population minimizer of the exponential loss:
So AdaBoost estimates half the log-odds! Hence the inverse transform - a sigmoid with a factor of two.
Where else it shows up. This is the same quantity that logistic regression predicts (log-odds), the same thing that lives in a booster's margin. The exponential and logistic losses share the same population minimizer up to a constant factor.
The difference between the losses. The exponential loss grows faster than the logistic one at large negative margins => AdaBoost is more sensitive to outliers and label noise. That is the practical reason gradient boosting on log-loss wins in production.
Note [T]. Being able to say "AdaBoost = forward stagewise + exponential loss" and "its population minimizer is half the log-odds" is very strong. Most people only know the re-weighting procedure.
[T.10] Multiclass: softmax, gradients, the diagonal hessian
Dimensions. (per-class margins); ; - one-hot .
Gradient:
The full hessian (a matrix per sample):
What XGBoost does. Uses the diagonal approximation, ignoring off-diagonal elements:
(the factor 2 is an implementation detail insuring against oversized steps).
Cost. Each iteration builds trees - one per class. 100 rounds and 10 classes => 1000 trees. Cost grows linearly in the number of classes.
The alternative (XGBoost 3.1+). Vector leaf - a single tree whose leaf holds a vector of weights . Lets the structure capture correlations between outputs. Still work in progress.
Note [T]. Knowing that the hessian is diagonally approximated is a rare detail and an excellent marker.
[T.11] SHAP: Shapley values
Symbols. - the set of all features ( ); - a subset excluding feature ; - the model's prediction with only the features in "known"; - feature 's contribution.
The meaning of the multiplier. Averaging over all possible orders of adding features: is the share of permutations in which feature arrives immediately after the set .
The additivity property (the main one):
where is the base value. The prediction decomposes exactly into feature contributions.
The Shapley axioms (the unique solution satisfying them): efficiency (the additivity above), symmetry, dummy (a null feature => zero contribution), linearity.
Complexity. Naively
. TreeSHAP exploits the tree structure and computes exact Shapley values in polynomial time. Available in XGBoost via pred_contribs=True.
The critical limitation. SHAP explains the model, not the world. It shows what the model looks at, not the causal structure of the data. If the model learned a proxy or a confounder, SHAP will faithfully show you that proxy. Causality does not follow from SHAP.
Where else it shows up. Cooperative game theory (Shapley's original 1953 setting): dividing a coalition's payoff among players.
[T.12] Functional gradient descent - the general frame
Generalizing I.6, boosting is descent in a space of functions:
where the "gradient" is the vector of negative-gradient values at the training points. Since we can't move in an arbitrary direction of an infinite-dimensional space, we project onto the space of trees:
In other words: the tree that best approximates the negative gradient. That's classical GBM.
XGBoost does the same, but in the metric given by the hessian:
The projection is now curvature-weighted - which is precisely the passage from gradient descent to Newton's method T.7.
The hierarchy of generalizations (worth drawing in your head):
forward stagewise additive modeling
├── exponential loss => AdaBoost **T.9**
├── any differentiable L, 1st order => GBM **I.6**
└── any twice-diff. L, 2nd order + Ω => XGBoost **T.2-T.6**
Appendix A. The cross-connections - "where else does this show up"
| Quantity / idea | In trees | Elsewhere |
|---|---|---|
| hessian of log-loss; Gini (binary, times 2) | Bernoulli variance; in of logistic regression; the IRLS weight | |
| XGBoost leaf weight | the ridge solution | |
| Soft-thresholding | L1 on leaf weights | lasso; ISTA / proximal gradient |
| Weighted least squares | every XGBoost iteration | IRLS in GLMs; Fisher scoring |
| Log-odds | the boosting margin; for log-loss | the linear predictor of logistic regression; population minimizer of the exponential loss (times ) |
| why RF decorrelates | risk of a portfolio of correlated assets | |
| Bias-variance | bagging vs boosting | regularization in any model |
| "Importance ≠ effect" | feature importance, SHAP | a regression coefficient on observational data ≠ a causal effect |
| Base-rate shift |
scale_pos_weight, undersampling |
negative sampling breaks calibration; the intercept moves, not the slopes |
| Fisher information | as local curvature |
Appendix B. What gets centered - the quick card
| Computing | Center? |
|---|---|
| Impurity, Gain, , | no |
| Features before a tree | no (invariance to monotone transformations) |
| (Fisher information, logistic regression) | no (curvature, not covariance; the intercept centers implicitly) |
| (CUPED, OLS) | yes, mandatory (it's a covariance) |
| Features before a regularized linear model | yes (the penalty depends on the scale of ) |
Mnemonic: centering belongs where a covariance of features is computed. Not where a loss curvature or sums of derivatives are.
Appendix C. The dimension checklist (self-test)
| Expression | Dimension | Check |
|---|---|---|
| no column of ones for a tree | ||
| , | one number per sample | |
| , | scalars | sums over the leaf's samples |
| one number per leaf | ||
| the tree structure | ||
| Gain | scalar | compared against zero |
| Multiclass hessian (full) | per sample | XGBoost takes the diagonal |
| in logistic regression | diagonal | don't confuse with ! |
| with the intercept | ||
| (SHAP) | per sample |
Appendix D. The 60-second checklist - what to say
- A tree - low bias, high variance; greedy impurity-driven splitting; globally optimal trees are NP-hard.
-
Bagging/RF attacks variance:
;
max_featureslowers ; OOB comes for free. - Boosting attacks bias: an additive model, trees fit the negative gradient; it overfits => early stopping.
- XGBoost: regularization inside the objective, second-order Taylor (Newton boosting), , Gain with , a criterion derived from the loss rather than Gini.
- The connection: = the Fisher-information weight; every iteration = weighted least squares = IRLS with trees.
- The limits: no extrapolation; probabilities aren't calibrated out of the box; importance ≠ causal effect.
That's the whole file. If it saved you a tab explosion the night before an interview, a ❤️ (or a unicorn, I don't judge) is the one signal that tells me these are worth making. And if I got something wrong, say so in the comments: a reference is only useful if it's right.
If write-ups like this are your thing, I announce the best ones on my Telegram channel, FitHappensML, along with discounts and free tiers from various providers whenever I spot them. No Telegram? I'm on X and Threads too. And if you're in ML/DS or building apps yourself, I follow back.

Top comments (0)