July 2026. Math doesn't rot, but library details do - XGBoost version notes below reflect 2.x-3.1.
The whole series:
- Part 1 - the Interview tier: trees, forests, and the ten core formulas (you are here)
- Part 2 - the Practice tier: the knobs you actually turn
- Part 3 - the Theory tier: full derivations and the cheat sheets
I've been preparing for ML interviews, and the formulas for trees and boosting are scattered across ESL chapters, the XGBoost paper, documentation and a hundred blog posts, each with its own notation, each explaining the part the author happened to care about. At some point I gave up looking for one complete reference and made it myself.
While collecting I noticed my notes kept mixing three different kinds of "know", so I sorted everything into three tiers. For myself, originally, but the split turned out to be the most useful part:
- [I] Interview - what I want to reproduce cold, at a whiteboard, mid-stress.
- [P] Practice - the knobs I actually turn, and the places I've been burned.
- [T] Theory - full derivations and cross-connections, for when a paper or an interviewer goes one level deeper.
Every formula follows the same template: symbols and dimensions => where it comes from => step by step => does anything get centered => where else this shows up => a note. The "where else" parts are, to me, the most valuable: the same three or four quantities keep reappearing across trees, logistic regression and statistics, and once you see that, the whole thing stops being a pile of facts.
The file came out so long that dev.to's editor waved a white flag, so it's a three-part series now. Cross-references like T.7 are section codes; I. sections live in this part, P. in part 2, T. in part 3, and every section carries its label in the heading, so Ctrl-F jumps you there. And it took a real amount of time to put together, so if you find it useful, leave a reaction: it genuinely raises the motivation to write more of these.
Section 0. Notation and conventions used throughout
0.1 Basic symbols and dimensions
| Symbol | What it is | Dimension |
|---|---|---|
| number of samples | scalar | |
| number of features | scalar | |
| number of classes | scalar | |
| design matrix | ||
| features of sample | column vector | |
| target of sample | scalar (or -vector for multiclass) | |
| , | model prediction (in margin space, before the link) | scalar |
| predicted probability (after the sigmoid) | scalar in | |
| gradient of the loss w.r.t. the prediction | scalar; vector | |
| hessian of the loss w.r.t. the prediction | scalar; vector | |
| number of leaves in a tree | scalar | |
| weight (prediction) of leaf | scalar; vector | |
| tree structure: sample => leaf index | ||
| set of samples in leaf | subset of | |
| sum of gradients in a leaf | scalar | |
| sum of hessians in a leaf | scalar | |
| learning rate / shrinkage | scalar | |
| L2, L1, per-leaf penalty | scalars | |
| number of trees in the ensemble | scalar |
Do not confuse. is the number of leaves, not the depth and not the number of nodes. is the sum of hessians, not the number of samples - they coincide only for MSE, where .
0.2 What gets centered and what doesn't - the once-and-for-all answer
A frequent source of confusion, because formulas from different models look alike.
| Object | Centered? | Why |
|---|---|---|
| Features for a tree | No | A tree is invariant to any monotone transformation: the split "x < t" doesn't change under shift/scale. Centering, standardizing, logging - useless (numerical trivia aside) |
| Features for RF / GBM / XGBoost | No | Same reason. Hence "trees don't need feature scaling" |
| in XGBoost | No | These are sums of gradients and hessians, not moments of a distribution |
| (Fisher information in logistic regression) | No | This is the curvature of the log-likelihood, not a covariance of features; the intercept column centers implicitly |
| (CUPED / OLS scatter) | Yes, mandatory | This is an actual covariance; without centering it stops being one |
Mnemonic: centering belongs where you compute a covariance/variance of features. Where you compute loss curvature or sums of gradients, centering is beside the point.
One more difference from linear models: the design matrix for a tree needs no column of ones - a tree has no intercept; its role is played by (see T.8).
TIER 1 - [I] INTERVIEW
The ten I keep coming back to. Everything else here is built on top of them.
First, the thirty-second version of what a decision tree even is, so the formulas have something to sit on. A tree is a stack of if-else questions about features: is age < 34, is income < 52k. Each question splits the data in two, and the tree picks the question that makes the two halves as pure as possible, as close to single-class as it can manage. It grows greedily, one best question at a time, top to bottom. That's the entire machine. Everything below is just making "as pure as possible" precise, and then fixing the problems that greed creates.
The purity measures come first, and they have a surprisingly good pedigree: one is borrowed from a 1912 Italian statistician, the other from Claude Shannon.
[I.1] Impurity: Gini and entropy
The absolute classic: the first thing anyone learns about trees, and still the first thing interviewers reach for. These are the two standard answers to "how mixed is this node": the tree plugs one of them into information gain I.2 to score every split it ever makes.
Symbols. - a tree node; - the share of class- samples in node (scalar, ). Both quantities are scalars.
Where they come from.
- Gini - the probability of mislabeling a sample if you assign it a class drawn at random from the node's own distribution: . And yes, it's named after that Gini (Corrado Gini of income-inequality fame), though it's not the inequality coefficient (that one is the Lorenz-curve construction). It's a categorical cousin from the same 1912 work, later reborn in ecology as the Gini-Simpson diversity index; both ask how likely two random draws are to disagree. For a 0/1 label the kinship becomes exact: the mean absolute difference between two random draws is , literally the binary impurity below.
- Entropy - Shannon, 1948: the average number of bits (with ) needed to encode the class. So the other half of the tree runs on information theory. XGBoost and sklearn default to the natural log where one is needed.
Extremes. Both are zero in a pure node (single class). Maximum at the uniform distribution: Gini , entropy .
Binary case (worth memorizing).
Centering. Not applicable - these are functions of class shares.
Where else it shows up. inside Gini is the Bernoulli variance - the same quantity as the hessian of the logistic loss I.10 and the weight in the Fisher information matrix of logistic regression. Not a coincidence: both measure "uncertainty" at a point.
Note [I] - why they're basically the same thing. Take entropy, , and replace the log with its first-order approximation . You get , which is exactly Gini. Gini is entropy with the logarithm linearized: same shape (zero on pure nodes, maximal at uniform, both concave), just a hair less sharp near uniform distributions and cheaper to compute, because no log. Which is also the honest answer to the classic trap question "which one is better?": on real data the chosen splits almost never differ, and sklearn defaults to Gini for the boring reason: speed.
[I.2] Information Gain - the CART split criterion
CART is Classification and Regression Trees - Breiman, Friedman, Olshen and Stone, 1984, and it arrived as a book, not a paper. It's one of the two family lines behind every modern tree: Quinlan's ID3/C4.5 line preferred entropy and multiway splits; the CART line preferred Gini and strictly binary splits. What's in sklearn and every boosting library today is essentially CART with forty years of engineering on top.
Symbols. - any impurity (Gini, entropy, MSE); - sample counts in the left and right child; . All scalars.
Where it comes from. "How much did heterogeneity drop after the split." The weights and exist because a child's impurity must be weighted by its size: a split that carves off a single sample into a pure leaf should not count as good.
Step by step (how CART picks a split).
- For each feature , sort the values .
- For each candidate threshold (usually midpoints between adjacent unique values), partition into and , compute IG.
- Pick the pair with maximal IG.
- Recurse into the children.
Complexity. per node after sorting (or including the sort; XGBoost amortizes sorting via column blocks).
For regression. , and maximizing IG is equivalent to maximizing the reduction in the sum of squares.
Centering. Not needed: thresholds are compared within a feature, and monotone transformations don't change the ordering.
Where else it shows up. The XGBoost Gain formula I.8 is the exact same pattern - "left score + right score − parent score" - except the score is derived from the loss function instead of postulated.
Note [I]. The algorithm is greedy - locally best split, never revisited. Finding the globally optimal tree is NP-hard. Say this out loud at the interview. Second: the criterion is biased toward features with many unique values (more candidate thresholds => more chances to stumble on a good one). This is where the MDI bias in feature importance P.8 comes from.
Before the next formula - the one-paragraph version of Random Forest. A single deep tree is a great memorizer and a poor generalizer: nudge the training data and you get a completely different tree (that's high variance, I.9). Leo Breiman's fix was blunt: grow a lot of deep trees on bootstrap copies of the data (bagging, 1996), also force every split to choose from a random subset of features (random forests, 2001), and average the whole thing. He did this in his seventies, after a career as a probability theorist and years of freelance consulting. And "Random Forests" is, delightfully, a registered trademark he and Adele Cutler licensed out. The next formula is the entire mathematical justification for all that averaging.
[I.3] Variance of a mean of correlated variables - why RF decorrelates
Symbols. - number of trees; - variance of a single tree's prediction; - pairwise correlation of tree predictions. All scalars.
Where it comes from. Direct computation:
How to read it (this is the point). Two terms:
- => goes to zero as trees are added. Averaging kills it.
- => a floor that no amount of extra trees gets you below.
This is all of Random Forest. Since the floor is set by
, you must reduce correlation between trees. Bootstrap gives part of the decorrelation; random feature selection at each split (max_features, mtry) gives most of it. If the data has one dominant feature, then without feature subsampling every tree picks it for the first split and the trees become nearly identical (
) - and averaging buys almost nothing.
Centering. Not applicable.
Where else it shows up. The same formula is the foundation of any ensembling and of portfolio diversification in finance (risk of a portfolio of correlated assets). Literally one piece of math.
Note [I]. The single most important formula about random forests. If you can derive it and explain that max_features targets specifically the first term (the
), you're already above the median candidate who says "the forest adds randomness for diversity". It also answers why a forest doesn't overfit with more trees: growing
only shrinks the second term; there's nothing for it to hurt.
[I.4] Bootstrap: the out-of-bag fraction
Symbols. - training set size, which is also the bootstrap sample size (sampling with replacement, same size).
Where it comes from. The probability of not picking a given sample in one draw is . There are exactly independent draws => . The limit is the classic limit.
Consequences.
- A bootstrap contains about 63.2 percent unique samples ( ); the rest are duplicates.
- About 36.8 percent of samples are out-of-bag (OOB) for a given tree.
How the ensemble's OOB estimate is computed (step by step).
- For sample , find all trees whose bootstrap did not include it (about of them).
- Predict by averaging/voting over those trees only.
- Repeat for all ; compare with true labels => OOB error.
The key point. OOB is not an estimate for a single tree. Each sample is predicted by its own "honest sub-forest" that never saw it. That's why OOB ≈ cross-validation, for free.
OOB bias. You're evaluating a forest of roughly trees, not , so OOB is slightly pessimistic. With large (hundreds) the difference vanishes. With small (dozens) OOB is noisy and noticeably low - use regular CV there.
Where else it shows up. Bootstrap as an uncertainty tool (bootstrap CIs), and the ".632 rule" in bootstrap error estimates (the .632 and .632+ estimators).
Note [I]. OOB does not work for boosting - trees there are sequential and dependent; an "honest sub-ensemble that never saw the sample" doesn't exist. For boosting: a held-out set and early stopping. This makes an excellent bagging-vs-boosting comprehension check.
And now boosting: the other way to combine trees, and for tabular data the one that ate the world. Instead of averaging many independent deep trees, you build shallow ones sequentially, each correcting what the ensemble so far gets wrong. The XGBoost paper contains my favorite measure of how completely this took over: of the 29 winning Kaggle solutions published in 2015, 17 used XGBoost. A decade later, gradient-boosted trees still routinely beat deep learning on tabular benchmarks: an awkward fact for a deep-learning decade, and the reason this half of the file is the longer one.
[I.5] The additive model of boosting (forward stagewise)
The final model:
Symbols. - the tree built at step (a map ); - learning rate; - the constant intercept (see T.8).
The key property - forward stagewise. At step we freeze everything built so far and do not re-optimize earlier trees. This is what distinguishes boosting from a neural net, where all weights move together.
What a tree predicts. Not the target - a correction to the ensemble's current prediction. Everything follows from this: that a leaf's value is a learned parameter (not "the average of y"), and that it can therefore be regularized.
A tree as a map into leaf weights.
where is the structure (which features, which thresholds) and is the vector of leaf weights.
Centering. Not applicable.
Where else it shows up. Forward stagewise additive modeling is the general frame: AdaBoost falls out of it under the exponential loss T.9, gradient boosting under an arbitrary differentiable one.
Note [I]. It follows that boosting cannot be parallelized across trees - they are sequential by construction. Parallelism lives inside the construction of a single tree (across features, across histogram bins). A frequent question.
[I.6] Pseudo-residuals: gradient boosting as descent in function space
Symbols. - the loss; - the current ensemble; - the pseudo-residual of sample at step . A vector .
Where it comes from. Friedman's idea: we want to move in the direction that decreases the loss, but our parameters are not numbers - they're functions. Then the "steepest descent direction" in function space is the negative gradient of the loss with respect to the function's values at the training points. The tree is trained to approximate that negative gradient.
Sanity check on MSE. - ordinary residuals.
This is where the popular phrase "boosting fits the residuals" comes from. It is exact only for the squared loss; for every other loss, residuals are replaced by the negative gradient.
Sanity check on log-loss. - the gap between the label and the predicted probability.
Centering. Not applicable (gradients are already "deviations").
Where else it shows up. Direct analogy with ordinary gradient descent ; here it's .
Note [I]. The sentence "gradient boosting is gradient descent in function space" is mandatory vocabulary. The next level of depth: XGBoost adds the second Taylor term and turns this into Newton's method T.2.
[I.7] XGBoost: the optimal leaf weight
(out loud: "minus the sum of gradients over the leaf's samples, divided by the sum of their hessians plus lambda")
Symbols and dimensions.
- scalar;
- scalar;
- the L2 coefficient (reg_lambda, default 1);
- scalar, the prediction of leaf
(in margin space!).
Where it comes from (short version; full derivation in **T.3).** Second-order Taylor => regroup the sum by leaves => inside a leaf you get a parabola => take the minimum the high-school way.
Three interpretations (be able to say all three).
Naive. Numerator - "how much error has accumulated in this leaf"; denominator - "how confidently we may correct it" (curvature) plus regularization.
Newtonian. A single sample's individual Newton step is . Then
That is a weighted average of individual Newton steps with weights , shrunk by . The leaf trusts the samples with the most curvature.
- Weighted least squares. See T.7.
Sanity check on MSE. , , :
The mean of residuals! So the intuition "a leaf's value is computed automatically" is a special case. It breaks the moment the loss isn't MSE or .
How the L2 works. sits in the denominator => the weight is pulled toward zero. And since the denominator can't drop below , the small leaves get strangled hardest (where ) - exactly where the overfitting risk is highest. Large leaves ( ) are barely touched.
Centering. No. are sums of derivatives, not moments.
Where else it shows up. Ridge regression: - the same "regularizer in the denominator" structure. In logistic-regression IRLS the update for contains .
Note [I]. Classic question: "how can L2 penalize a tree if a tree has no coefficients?" Answer: the tree's parameters are the leaf weights (learned constant corrections); ridge penalizes exactly those.
[I.8] XGBoost: the Gain formula (split value)
(out loud: "one half of left-leaf score plus right-leaf score minus parent score, minus gamma")
Symbols.
- sums of gradients and hessians in the left child; same for
. Parent:
,
.
- gamma / min_split_loss.
Where it comes from. From the structure score T.5: the quality of a structure is . Gain is (quality before) minus (quality after), accounting for the fact that a split adds exactly one leaf ( ), i.e. we pay .
The three terms in the bracket. Left child's score + right child's score − parent's score. The same pattern as Information Gain I.2, but the score is derived from the loss, not postulated.
Split rule. Split if . So is a break-even threshold.
How went from a global penalty to a local rule. In the objective the penalty is (global, per whole tree). Since every split adds , the local price of any split is . Hence the " " in the formula. This is a genuinely beautiful moment and it lands great at interviews.
How influences split selection. A larger suppresses the contribution of leaves with small => splits that produce small/uncertain leaves become less profitable => the tree grows more slowly. So L2 acts twice: it shrinks weights I.7 and it suppresses splits.
Sanity check on MSE. , , : the bracket becomes - exactly the reduction in the sum of squares, the classical CART criterion for regression. A special case, again.
Computational trick. To evaluate Gain at any threshold, you only need (the parent's are known). So walking left to right along the sorted feature and accumulating prefix sums covers all thresholds in a single pass.
With L1. Replace with - soft-thresholding T.4.
Note [I]. The pair I.7+I.8 is the core of XGBoost. If you can derive both in two minutes, XGBoost questions are closed.
[I.9] The bias-variance decomposition
Symbols. - the true function; - the trained model (random through the randomness of the training set); - noise variance. Expectations are over training sets.
Where it comes from. Add and subtract inside the square, expand; the cross term vanishes.
How it maps onto trees.
| Model | Bias | Variance | Treatment |
|---|---|---|---|
| A single deep tree | low | very high | ensembles |
| Bagging / Random Forest | low (unchanged) | reduced by averaging | more trees, lower I.3 |
| Boosting | reduced sequentially | grows with the number of trees | early stopping, shrinkage, regularization |
The key contrast (say it explicitly).
- Bagging attacks variance => trees are deep (low bias), unpruned, averaged. Extra trees don't hurt.
- Boosting attacks bias => trees are shallow (weak learners), added sequentially. Extra trees overfit.
Centering. Not applicable.
Where else it shows up. Regularization in any model is "add bias, remove variance". L1/L2 in linear models, in XGBoost, dropout in neural nets.
Note [I]. Extra depth: in deep networks the classic U-shaped picture breaks (double descent) - fine to mention, carefully, without derailing the conversation.
[I.10] The sigmoid, log-loss, and g, h for the logistic loss
Symbols. - the raw prediction (margin, log-odds); ; .
Where it comes from (step by step).
- Chain rule: . Everything cancels - this cancellation is exactly why the logit parametrization is so convenient.
- .
The meaning of . It's the Bernoulli variance - "how unsure the model is". Maximum at (at the decision boundary), tending to zero as or . So samples near the boundary weigh more - they're the ones carrying information about where to move the boundary.
Technical nuance. As
the hessian
=> division blowup in
. XGBoost clips the hessian from below by a constant around
; additionally max_delta_step bounds
.
Centering. Not applicable.
Where else it shows up - the most important connection in this file. The same quantity is:
- the Bernoulli variance in statistics;
- Gini impurity (binary case ) I.1;
- the diagonal of the matrix in the Fisher information of logistic regression: , with ; dimensions: is , is , the result is ;
- the hessian in XGBoost.
It is one and the same curvature of the logistic likelihood. See T.7 on Newton boosting ≈ IRLS.
Note [I]. Dropping this connection at an interview instantly shows that the models in your head are connected, not filed in separate boxes. One of the strongest cards you can play.
A plug, but an on-topic one, since half of Tier 1 just turned out to be statistics in disguise: I built a statistics exam app, Stat Exam Pro. The main focus is medical statistics, but if you're prepping for DS interviews it's worth a look anyway: the topics overlap more than you'd expect, and seeing the same ideas from another field's angle is weirdly refreshing. Everything is in test format with thoroughly worked answers. The section I'm proudest of is Paradoxes & Intuition Traps - start there ;)
Next up, part 2: the knobs you actually turn, and where they bite - Part 2 - the Practice tier: the knobs you actually turn

Top comments (0)