Skip to content
Classical machine learning Core 29 min read

Decision trees, random forests and boosting

A decision tree cuts feature space into boxes and predicts a constant in each. Alone it is unstable; averaged into a random forest or added up by gradient boosting it is still, as of 2026, the default winner on most spreadsheet-shaped problems.

10,000 ft

Most of the world's business data lives in tables: rows of customers, loans, transactions, sensor readings. On that kind of data, ensembles of trees (random forests and, above all, gradient-boosted trees such as XGBoost, LightGBM and CatBoost) have been the strongest practical models for two decades, and deep networks only began to challenge them recently with tabular foundation models. The two combining ideas are bigger than trees: bagging (average many noisy models to cut variance) and boosting (add models one at a time, each correcting the last, which is gradient descent in function space). Both ideas recur everywhere: in model ensembling and dropout, in residual networks, which also add corrections to a running sum, and in the bias–variance story that runs through this whole track.

2,000 ft

A tree asks a sequence of yes/no questions about single features ("income ≤ 52k?") and stores a prediction in each leaf. It is grown greedily: at each node, try every feature and threshold, keep the split that most reduces impurity, recurse. Deep trees fit anything and therefore overfit; their predictions jump around when the data changes slightly. Two cures:

  1. Bagging / random forests: train hundreds of deep trees on bootstrap resamples, each split choosing from a random subset of features, and average. Averaging decorrelated noisy predictors cuts variance without adding bias.
  2. Boosting: start from a constant; repeatedly fit a small tree to the current errors (the negative gradient of the loss) and add a shrunken copy of it. Each tree removes some bias; early stopping controls variance.
  3. Modern GBDT libraries add second-order (Newton) steps, explicit regularisation of leaf values, histogram-binned features, and careful handling of missing values and categories.

One weak learner, two ways to combine it
One weak learner, two ways to combine it. Decision tree low bias if deep, high variance, Bagging bootstrap rows, average, Random forest + random feature subsets, Boosting fit what is still wrong, AdaBoost reweight mistakes, Gradient boosting fit the negative gradient, XGBoost / LightGBM / CatBoost 2nd-order, histograms, regularised, parallel, reduce variance, decorrelate trees, sequential, reduce One weak learner, two ways to combine it. Decision tree low bias if deep, high variance, Bagging bootstrap rows, average, Random forest + random feature subsets, Boosting fit what is still wrong, AdaBoost reweight mistakes, Gradient boosting fit the negative gradient, XGBoost / LightGBM / CatBoost 2nd-order, histograms, regularised, parallel, reduce variance, decorrelate trees, sequential, reduce

Ground level

A tree is a piecewise-constant function

Take inputs \(\mathbf{x} \in \mathbb{R}^p\). A binary tree with \(J\) leaves partitions \(\mathbb{R}^p\) into \(J\) axis-aligned boxes \(R_1,\dots,R_J\) and predicts a constant \(c_j\) in each:

\[ f(\mathbf{x}) = \sum_{j=1}^{J} c_j \,\mathbb{1}[\mathbf{x} \in R_j]. \]

Every internal node tests one feature against one threshold, so every boundary is parallel to an axis. A regression tree stores the mean target of the training points in each leaf; a classification tree stores class proportions (and predicts the majority class).

R1: 0.8 R2: −0.4 R3: −0.6 R4: 0.1 x₁ (0 to 1) x₂ (0 to 1) x₁ ≤ 0.5? x₂ ≤ 0.3? x₂ ≤ 0.7? R2R1 R4R3 yesno
The same model twice. Left: a depth-2 tree carves the unit square into four boxes, each with a constant prediction. Right: the tree of questions that produces those boxes. Every boundary is axis-aligned, which is why trees need many splits to draw a diagonal line.

Three properties follow from this picture and explain most of the practical behaviour of trees:

  • Invariance to monotone feature transforms. A split asks only "is \(x_j\) below \(t\)?", so replacing income by log-income changes the thresholds but not the partition. No scaling, no normalisation, no log-transforming needed.
  • Interactions for free. The prediction in R1 depends on \(x_1\) and \(x_2\) jointly. A linear model needs you to engineer \(x_1 x_2\); a tree discovers conjunctions by nesting splits.
  • Poor at smooth or diagonal structure. Approximating \(y = x_1 + x_2\) takes a staircase of many boxes. Trees extrapolate as a constant beyond the training range: a tree trained on house prices up to 2 crore will never predict 3 crore.

Growing a tree greedily

Finding the best tree of a given size is NP-hard (Hyafil and Rivest showed this in 1976 for optimal decision trees), so every practical algorithm (CART, ID3, C4.5 and all the GBDT libraries) grows the tree greedily, one split at a time:

  1. At the current node, for every feature \(j\) and every threshold \(t\) between consecutive sorted values, split the node's points into left \(L = \{x_j \le t\}\) and right \(R\).
  2. Score the split by the weighted impurity of the children, \(\frac{n_L}{n} I(L) + \frac{n_R}{n} I(R)\).
  3. Keep the best split; recurse on both children until a stopping rule fires.

The impurity \(I\) measures how mixed a node is. With class proportions \(p_k\) in a node:

Impurity Formula Used by
Gini \(1 - \sum_k p_k^2\) CART, scikit-learn default
Entropy \(-\sum_k p_k \log_2 p_k\) ID3, C4.5 ("information gain")
Squared error (regression) \(\frac{1}{n}\sum_i (y_i - \bar{y})^2\) regression trees, all GBDTs

Worked example: choosing one split by hand

Eight loan applicants, one feature \(x\) (say, years of credit history), label \(y = 1\) if they repaid:

\(x\) 1 2 3 4 5 6 7 8
\(y\) 0 0 0 1 0 1 1 1

The root has four of each class: Gini \(= 1 - (0.5^2 + 0.5^2) = 0.5\) and entropy \(= 1\) bit. Now try every threshold. For \(x < 3.5\): left is \(\{0,0,0\}\) (Gini 0), right is \(\{1,0,1,1,1\}\) with \(p_1 = 0.8\), Gini \(= 1 - 0.64 - 0.04 = 0.32\). Weighted: \(\tfrac{3}{8}\cdot 0 + \tfrac{5}{8}\cdot 0.32 = 0.20\). Doing all seven (the code in Build it prints this table):

split left right weighted Gini information gain (bits)
\(x<1.5\) 0 0 0 1 0 1 1 1 0.4286 0.1379
\(x<2.5\) 0 0 0 1 0 1 1 1 0.3333 0.3113
\(x<3.5\) 0 0 0 1 0 1 1 1 0.2000 0.5488
\(x<4.5\) 0 0 0 1 0 1 1 1 0.3750 0.1887
\(x<5.5\) 0 0 0 1 0 1 1 1 0.2000 0.5488
\(x<6.5\) 0 0 0 1 0 1 1 1 0.3333 0.3113
\(x<7.5\) 0 0 0 1 0 1 1 1 0.4286 0.1379

Two splits tie. Both criteria agree, as they nearly always do: Gini and entropy pick the same split in the vast majority of cases, and the choice between them rarely matters. The tie is instructive: greedy growth is myopic. Whichever split we take, one child still holds the awkward pair at \(x=4,5\), and only the next split can clean it up. A split that looks mediocre now can enable a great one later (XOR is the extreme case: no single axis split on XOR data reduces impurity at all, yet two levels solve it perfectly).

Cost. For \(n\) points and \(p\) features, sorting once per feature and sweeping thresholds with running sums costs \(O(pn\log n)\) at the root and about the same per level, so a depth-\(d\) tree costs roughly \(O(d\,pn\log n)\). GBDT libraries cut this by binning each feature into a few hundred quantile buckets up front (typically 255 or 256), so a split search becomes a pass over a histogram rather than over sorted points.

When to stop: depth, leaves and pruning

Grown until every leaf is pure, a tree memorises the training set: zero training error, poor test error. Two families of control:

  • Pre-pruning (stopping rules): maximum depth, minimum samples per leaf, minimum impurity decrease. Cheap, and what every library exposes.
  • Post-pruning: grow a big tree \(T_0\), then prune back. CART's cost-complexity pruning minimises \(R_\alpha(T) = R(T) + \alpha |T|\) over subtrees \(T \subseteq T_0\), where \(R(T)\) is training error and \(|T|\) the number of leaves. As \(\alpha\) rises from 0, the optimal subtree shrinks through a nested sequence (weakest-link pruning), and you choose \(\alpha\) by cross-validation. scikit-learn exposes it as ccp_alpha.

Why one tree is not enough: variance

Trees are unstable. Change a few training points and the root split can flip to a different feature, after which the whole subtree below is different. The fitted function is a high-variance estimator: low bias (a deep tree can represent nearly anything) but predictions that swing with the sample. That is precisely the situation in which averaging helps, and it is why trees became the canonical base learner for ensembles.

Bagging and random forests

Bagging (bootstrap aggregating, Breiman 1996): draw \(B\) bootstrap samples (size \(n\), with replacement), grow a deep tree on each, and average their predictions (or vote). If each tree's prediction at a point has variance \(\sigma^2\) and any two trees have correlation \(\rho\), the average of \(B\) trees has variance

\[ \operatorname{Var}\Big(\frac{1}{B}\sum_{b=1}^{B} T_b(\mathbf{x})\Big) = \rho\sigma^2 + \frac{1-\rho}{B}\sigma^2 . \]

The second term vanishes as \(B\) grows; the first does not. With \(\sigma^2 = 1\) and \(\rho = 0.3\), 100 trees give \(0.3 + 0.007 = 0.307\): adding the 1,000th tree barely helps, but lowering \(\rho\) helps a lot. Bootstrap trees are strongly correlated because they all split first on the same dominant feature.

Random forests (Breiman 2001) decorrelate them: at every split, only a random subset of \(m\) of the \(p\) features is eligible. The classic defaults are \(m = \sqrt{p}\) for classification and \(m = p/3\) for regression (Hastie, Tibshirani and Friedman, ESL §15.3). Small \(m\) raises each tree's variance a little but cuts \(\rho\) a lot. (scikit-learn's RandomForestRegressor defaults to max_features=1.0, i.e. plain bagging, so set it yourself.)

Two gifts come with the bootstrap:

  • Out-of-bag (OOB) error. A given row is missed by one bootstrap sample with probability \((1 - 1/n)^n \to e^{-1} \approx 0.368\). So each row is "test data" for about a third of the trees; predicting each row with only those trees gives a nearly free estimate of test error without a hold-out set.
  • Feature importance. Impurity-based importance (total impurity decrease from splits on a feature) is fast but biased towards features with many distinct values and computed on training data. Permutation importance (shuffle one feature in held-out data, measure the drop in score) is the more honest default; SHAP values (Lundberg and Lee, 2017; exact and fast for trees via TreeSHAP) give per-prediction attributions.

Bagging is a variance machine

Bagging leaves bias almost untouched (each tree is still a deep tree) and attacks variance. That is why it works with deep, low-bias, high-variance trees and does little for stable, high-bias models such as linear regression or stumps. Boosting is the mirror image.

Boosting: AdaBoost

Boosting asks a different question, first posed by Kearns and Valiant in learning theory: can many weak learners (barely better than chance) be combined into a strong one? Schapire (1990) proved yes; AdaBoost (Freund and Schapire, 1997) made it practical. For labels \(y_i \in \{-1, +1\}\):

  1. Start with uniform weights \(w_i = 1/n\).
  2. For \(t = 1,\dots,T\): fit a weak classifier \(h_t\) (often a stump) to the weighted data; compute its weighted error \(\varepsilon_t\); set \(\alpha_t = \tfrac12 \ln\frac{1-\varepsilon_t}{\varepsilon_t}\).
  3. Reweight: \(w_i \leftarrow w_i \exp(-\alpha_t y_i h_t(\mathbf{x}_i))\), then normalise. Misclassified points gain weight.
  4. Predict \(\operatorname{sign}\big(\sum_t \alpha_t h_t(\mathbf{x})\big)\).

A stump with \(\varepsilon = 0.3\) gets \(\alpha = \tfrac12\ln(0.7/0.3) = 0.424\); each misclassified point's weight is multiplied by \(e^{0.424} = 1.53\) and each correct one by \(e^{-0.424} = 0.65\). After renormalising, the misclassified points carry exactly half the total weight, so the next learner is forced to attend to them. Friedman, Hastie and Tibshirani (2000) showed what AdaBoost really is: forward stagewise additive modelling under the exponential loss \(e^{-yF(\mathbf{x})}\) (derived in The maths). That view generalises.

Gradient boosting: gradient descent in function space

Friedman (2001) took the view to its conclusion. We want \(F\) minimising \(\sum_i L(y_i, F(\mathbf{x}_i))\). Treat the vector of predictions \((F(\mathbf{x}_1),\dots,F(\mathbf{x}_n))\) as the parameters and take a gradient step on it. The negative gradient at each training point is the pseudo-residual

\[ r_i = -\left.\frac{\partial L(y_i, F)}{\partial F}\right|_{F = F_{m-1}(\mathbf{x}_i)} . \]

But a raw gradient step only moves predictions at the training points. To generalise, fit a small regression tree \(h_m\) to the \(r_i\) (a tree is a smooth-enough function that can be evaluated anywhere) and take the step in that direction: \(F_m = F_{m-1} + \nu\, h_m\) with learning rate (shrinkage) \(\nu \approx 0.01\)–\(0.1\).

The gradient boosting loop
The gradient boosting loop. F0 = best constant (mean, or log-odds), compute pseudo-residuals r = minus dLoss/dF at each point, fit a small tree h to r, set each leaf value by a line search on the true loss, F = F + learning rate x h, validation loss stops falling?, final model = F0 + sum of shrunken trees, no: next round, yesThe gradient boosting loop. F0 = best constant (mean, or log-odds), compute pseudo-residuals r = minus dLoss/dF at each point, fit a small tree h to r, set each leaf value by a line search on the true loss, F = F + learning rate x h, validation loss stops falling?, final model = F0 + sum of shrunken trees, no: next round, yes

The pseudo-residual depends on the loss, and that is the whole flexibility of the method:

Loss \(L(y,F)\) Pseudo-residual \(r\) Behaviour
Squared \(\tfrac12(y-F)^2\) \(y - F\) literally "fit the residuals"
Absolute \(\lvert y-F\rvert\) \(\operatorname{sign}(y-F)\) robust to outliers
Log-loss, \(F\) = log-odds, \(p = \sigma(F)\) \(y - p\) binary classification
Exponential \(e^{-yF}\), \(y \in \{\pm1\}\) \(y\,e^{-yF}\) recovers AdaBoost

Worked numbers (squared loss). Three houses with prices 3, 5, 10 (lakh-scale units, whatever). \(F_0\) = mean = 6. Residuals: \(-3, -1, +4\). Suppose the first tree splits the third house off: leaf values \(-2\) (mean of \(-3,-1\)) and \(+4\). With \(\nu = 0.5\) the new predictions are \(6 - 1 = 5\), \(5\), \(6 + 2 = 8\); new residuals \(-2, 0, +2\). Squared error went from \(9+1+16=26\) to \(4+0+4=8\). Each round shrinks what is left, and small \(\nu\) means many small steps, which regularises (the same reason small learning rates generalise better in neural network optimisation).

Stochastic gradient boosting (Friedman, 2002) fits each tree on a random subsample of rows (typically 50–80%), which both speeds training and, like bagging, reduces variance.

The modern GBDT libraries

The three libraries that dominate practice share the gradient-boosting skeleton and differ in engineering:

XGBoost (Chen and Guestrin, 2016) LightGBM (Ke et al., 2017) CatBoost (Prokhorenkova et al., 2018)
Step Newton: uses gradient and Hessian of the loss Newton Newton
Regularisation \(\gamma\) per leaf, \(\lambda \lVert w\rVert^2\) on leaf values same family same family + ordered boosting
Tree growth depth-wise (leaf-wise optional) leaf-wise (best-first) oblivious: one split per level, shared by all nodes
Speed tricks sparsity-aware splits, histogram mode, out-of-core histograms, gradient-based one-side sampling (GOSS), exclusive feature bundling symmetric trees are fast to evaluate
Categoricals one-hot or native (newer versions) native ordered target statistics, its signature feature
Missing values learns a default direction per split yes yes

XGBoost's key derivation (in The maths) gives a closed-form optimal leaf value \(w^{*} = -G/(H+\lambda)\) and a split gain that is just a sum of \(G^2/(H+\lambda)\) terms: the whole split search reduces to accumulating gradient and Hessian sums in histogram bins. CatBoost's ordered boosting fixes a subtle leak: computing a row's residual with a model that was trained on that same row biases the residuals ("prediction shift"); CatBoost uses, for each row, a model built only from rows that come before it in a random permutation.

History

  • 1963: Morgan and Sonquist's AID (Automatic Interaction Detection) grows regression trees on survey data, the first recognisable tree algorithm.
  • 1984: Breiman, Friedman, Olshen and Stone publish Classification and Regression Trees (CART): Gini, regression trees, cost-complexity pruning.
  • 1986, 1993: Quinlan's ID3 (entropy and information gain) and C4.5 bring trees to the machine-learning community.
  • 1990: Schapire answers Kearns and Valiant: weak learnability equals strong learnability. 1997: Freund and Schapire's AdaBoost (Gödel Prize 2003).
  • 1995–2001: Ho's random decision forests (1995), Breiman's bagging (1996) and random forests (2001).
  • 2000–2002: Friedman, Hastie and Tibshirani recast boosting as additive modelling; Friedman's gradient boosting machine (2001) and stochastic gradient boosting (2002).
  • 2014–2018: XGBoost dominates Kaggle; the paper appears in 2016. LightGBM (2017) and CatBoost (2018) follow.
  • 2022–2025: Grinsztajn et al. (2022) document that trees still beat deep learning on medium-sized tabular data; TabPFN (Hollmann et al., Nature, 2025), a transformer pre-trained on millions of synthetic datasets, reports beating tuned tree ensembles on datasets up to 10,000 samples.

First principles

Why greedy, and why it is fine. Optimal trees are intractable, but greedy growth is cheap and, crucially, ensembles forgive greedy mistakes. A forest averages over many greedy trees grown on perturbed data; boosting fixes a bad early split by later trees. The base learner does not need to be optimal, only diverse (forests) or slightly useful (boosting).

Why impurity has to be strictly concave. The obvious score, misclassification rate, is a bad splitting criterion. A node with 400 of each class: split A gives children (300, 100) and (100, 300); split B gives (200, 400) and (200, 0). Both have misclassification rate 0.25. Gini prefers B (\(\tfrac{6}{8}\cdot\tfrac49 + \tfrac28\cdot 0 = 0.333\) against \(0.375\)) because B creates a pure node, from which no more work is needed. Strictly concave impurities (Gini, entropy) always reward moving the children's class proportions apart; a piecewise-linear one can fail to register progress, and then growth stalls.

Why averaging must be paired with decorrelation. The variance formula above says correlation sets a floor that no number of trees removes. Every design choice in random forests (bootstrap rows, random features per split, fully grown trees) is a trade between individual-tree accuracy and between-tree correlation.

Why boosting must use weak learners and shrinkage. If the first tree were deep enough to fit the residuals perfectly, the second would have nothing to learn and the ensemble would be one overfit tree. Small trees (depth 3–8) and small steps \(\nu\) keep each increment a modest correction, so the ensemble walks slowly along the loss surface and early stopping can choose where to stop. Depth also sets the interaction order: a depth-\(d\) tree can express interactions among at most \(d\) features, so depth-1 stumps give an additive model with no interactions at all.

Why trees win on tables. Grinsztajn, Oyallon and Varoquaux (2022) traced the gap to three inductive biases. Tabular targets are often irregular functions of the features, and neural networks are biased towards smooth solutions; tables contain many uninformative columns, which trees ignore by never splitting on them; and columns carry individual meaning, whereas an MLP is rotation-invariant and so mixes them. Trees are axis-aligned, piecewise-constant and feature-selecting: exactly the right biases.

The maths

Impurities. For a node with \(n\) points and class proportions \(p_k = n_k/n\):

\[ \text{Gini} = \sum_k p_k(1-p_k) = 1 - \sum_k p_k^2, \qquad H = -\sum_k p_k \log_2 p_k . \]

Gini is the probability that two points drawn at random from the node have different labels. The information gain of a split is \(H(\text{parent}) - \sum_{c \in \{L,R\}} \frac{n_c}{n} H(c)\): the mutual information between the split indicator and the label (see information theory).

Regression split. A leaf's best constant under squared loss is the mean, leaving sum of squares \(\mathrm{SSE}(S) = \sum_{i\in S} y_i^2 - \frac{1}{|S|}\big(\sum_{i\in S} y_i\big)^2\). With prefix sums of \(y\) and \(y^2\) over sorted points, every threshold's \(\mathrm{SSE}(L) + \mathrm{SSE}(R)\) costs \(O(1)\), which is how the sweep in Build it is linear after sorting.

Derivation: variance of an average of correlated trees

Let \(T_1,\dots,T_B\) have common variance \(\sigma^2\) and pairwise correlation \(\rho\), so \(\operatorname{Cov}(T_a, T_b) = \rho\sigma^2\) for \(a \ne b\). Then

\[ \operatorname{Var}\Big(\frac1B\sum_b T_b\Big) = \frac{1}{B^2}\Big(\sum_b \operatorname{Var}T_b + \sum_{a\ne b}\operatorname{Cov}(T_a,T_b)\Big) = \frac{1}{B^2}\big(B\sigma^2 + B(B-1)\rho\sigma^2\big) = \rho\sigma^2 + \frac{1-\rho}{B}\sigma^2 . \]

Bias is unchanged by averaging (the expectation of a mean is the mean of expectations), so bagging can only lower mean squared error.

Derivation: AdaBoost is stagewise minimisation of exponential loss

Let \(F_{t-1}\) be the current ensemble and \(L = \sum_i e^{-y_i F(\mathbf{x}_i)}\). Adding \(\alpha h\) with \(h(\mathbf{x}) \in \{\pm 1\}\):

\[ \sum_i e^{-y_i F_{t-1}(\mathbf{x}_i)} e^{-\alpha y_i h(\mathbf{x}_i)} = \sum_i w_i e^{-\alpha y_i h(\mathbf{x}_i)}, \quad w_i = e^{-y_i F_{t-1}(\mathbf{x}_i)} . \]

Since \(y_i h(\mathbf{x}_i) = +1\) when correct and \(-1\) when wrong, this is \(e^{-\alpha}\sum_{\text{correct}} w_i + e^{\alpha}\sum_{\text{wrong}} w_i = W\big[(1-\varepsilon)e^{-\alpha} + \varepsilon e^{\alpha}\big]\) with \(W = \sum_i w_i\) and \(\varepsilon\) the weighted error. For any fixed \(\alpha > 0\) the best \(h\) minimises \(\varepsilon\): train the weak learner on weighted data. Setting the derivative in \(\alpha\) to zero, \(-(1-\varepsilon)e^{-\alpha} + \varepsilon e^{\alpha} = 0\), gives \(\alpha = \tfrac12 \ln\frac{1-\varepsilon}{\varepsilon}\). The next round's weights are \(w_i e^{-\alpha y_i h(\mathbf{x}_i)}\), exactly AdaBoost's update. The population minimiser of exponential loss is \(F^{*}(\mathbf{x}) = \tfrac12 \ln\frac{P(y=1\mid\mathbf{x})}{P(y=-1\mid\mathbf{x})}\), half the log-odds, which is why AdaBoost's scores can be turned into probabilities.

Gradient boosting (Friedman's Algorithm 1). Given loss \(L\), learning rate \(\nu\) and \(M\) rounds:

  1. \(F_0(\mathbf{x}) = \arg\min_c \sum_i L(y_i, c)\).
  2. For \(m = 1..M\): compute \(r_{im} = -\partial L(y_i, F_{m-1}(\mathbf{x}_i))/\partial F\); fit a regression tree to \(\{(\mathbf{x}_i, r_{im})\}\), giving regions \(R_{jm}\); set each leaf \(\gamma_{jm} = \arg\min_\gamma \sum_{\mathbf{x}_i \in R_{jm}} L(y_i, F_{m-1}(\mathbf{x}_i) + \gamma)\); update \(F_m = F_{m-1} + \nu \sum_j \gamma_{jm}\mathbb{1}[\mathbf{x}\in R_{jm}]\).

For log-loss with \(p_i = \sigma(F(\mathbf{x}_i))\): \(\partial L/\partial F = p_i - y_i\) and \(\partial^2 L/\partial F^2 = p_i(1-p_i)\), so the leaf line search is usually replaced by one Newton step, \(\gamma_j = \sum_{i \in R_j}(y_i - p_i) \big/ \sum_{i\in R_j} p_i(1-p_i)\).

Derivation: XGBoost's leaf weights and split gain

At round \(m\) add a tree \(f\) with \(T\) leaves and leaf values \(w_1..w_T\), and penalise complexity by \(\Omega(f) = \gamma T + \tfrac12\lambda\sum_j w_j^2\). Expand each loss to second order around the current prediction, with \(g_i = \partial_F L\) and \(h_i = \partial^2_F L\):

\[ \mathcal{L} \approx \sum_i \big[g_i f(\mathbf{x}_i) + \tfrac12 h_i f(\mathbf{x}_i)^2\big] + \gamma T + \tfrac12\lambda\sum_j w_j^2 + \text{const}. \]

Group points by leaf, \(G_j = \sum_{i\in j} g_i\), \(H_j = \sum_{i\in j} h_i\): \(\mathcal{L} = \sum_j \big[G_j w_j + \tfrac12 (H_j + \lambda) w_j^2\big] + \gamma T\). Each term is a 1-D quadratic, minimised at

\[ w_j^{*} = -\frac{G_j}{H_j + \lambda}, \qquad \mathcal{L}^{*} = -\frac12\sum_j \frac{G_j^2}{H_j+\lambda} + \gamma T . \]

Splitting a leaf into \(L\) and \(R\) therefore changes the objective by

\[ \text{Gain} = \frac12\left[\frac{G_L^2}{H_L+\lambda} + \frac{G_R^2}{H_R+\lambda} - \frac{(G_L+G_R)^2}{H_L+H_R+\lambda}\right] - \gamma . \]

A split is worth making only if Gain \(> 0\), so \(\gamma\) is a built-in pruning threshold, and \(\lambda\) shrinks leaf values towards zero (most strongly in leaves with little Hessian mass, i.e. few or confidently-predicted points). For squared loss \(g_i = F - y_i\) and \(h_i = 1\), so \(w^{*} = \sum (y_i - F)/(n_j + \lambda)\): a ridge-shrunk mean residual.

In practice

  • Start with a GBDT, not a neural network, on tabular data. LightGBM or XGBoost with early stopping on a validation fold is a strong baseline in minutes; CatBoost is the easiest when there are many high-cardinality categorical columns.
  • The knobs that matter: learning rate and number of trees (tune together, with early stopping deciding the count); tree size (max_depth 4–8 or num_leaves 15–255); row subsampling (0.5–0.9) and column subsampling (0.5–0.9); minimum samples or Hessian per leaf; \(\lambda\). Defaults are good; tuning typically buys a few per cent.
  • Random forests are the low-maintenance alternative: hard to overfit by adding trees, few knobs (max_features, min_samples_leaf), free OOB validation, embarrassingly parallel.
  • Leakage still bites. Trees will find a leaked column instantly and split on it at the root. Target-encoding categoricals without out-of-fold computation is the classic leak (CatBoost's ordered statistics exist for this reason). See validation and leakage.
  • Monotone constraints (supported by XGBoost, LightGBM and CatBoost) force predictions to be non-decreasing in a feature, which regulators and finance teams often require, for example credit risk that must not fall as debt rises.
  • Know the limits. Trees cannot extrapolate beyond the training range, need many splits for linear trends (add a linear model or a linear-trend feature), and are not the right tool for raw images, audio or text, where learned representations win. As of 2026, tabular foundation models such as TabPFN are a serious option for small datasets (up to roughly 10,000 rows in the published version); for large tables GBDTs remain the default.

Common misconceptions

“Random forests cannot overfit”

Adding trees to a forest does not overfit: Breiman proved the generalisation error converges as the number of trees grows. But each tree can still be overfit to noise, and on very noisy data limiting depth or raising min_samples_leaf helps. Boosting, by contrast, definitely overfits as rounds increase.

“Feature importance tells you what causes the outcome”

Importance measures how much the model uses a feature. Correlated features split importance between them arbitrarily, impurity importance favours high-cardinality columns, and none of it is causal. Use permutation importance on held-out data and treat it as a diagnostic.

“Boosting reduces bias, so it needs deep trees”

The opposite: boosting relies on shallow trees and many rounds. Depth sets the interaction order, not the capacity of the ensemble, which grows with the number of rounds.

Build it

A regression tree, a random forest and gradient boosting from scratch in NumPy (about 55 lines). The data: \(y = \sin(2\pi x_1) + 0.5\,x_2 + \varepsilon\) with \(\varepsilon \sim \mathcal{N}(0, 0.3^2)\), plus three pure-noise features.

import numpy as np
rng = np.random.default_rng(0)

def make_data(n):                      # y = sin(2πx0) + 0.5·x1 + noise; x2..x4 are pure noise
    X = rng.uniform(0, 1, (n, 5))
    return X, np.sin(2*np.pi*X[:, 0]) + 0.5*X[:, 1] + rng.normal(0, 0.3, n)

def build(X, y, depth, min_leaf=5, m=None):
    """Regression tree as nested tuples: (feature, threshold, left, right) or a leaf value."""
    if depth == 0 or len(y) < 2*min_leaf:
        return y.mean()
    feats = rng.choice(X.shape[1], m, replace=False) if m else range(X.shape[1])
    best = (np.inf, None, None)
    for j in feats:
        order = np.argsort(X[:, j]); xs, ys = X[order, j], y[order]
        csum, n = np.cumsum(ys), len(ys)
        csq = np.cumsum(ys**2)
        for i in range(min_leaf, n - min_leaf + 1):         # left = first i points
            if xs[i-1] == xs[i]: continue
            sse_l = csq[i-1] - csum[i-1]**2 / i
            sse_r = (csq[-1]-csq[i-1]) - (csum[-1]-csum[i-1])**2 / (n-i)
            if sse_l + sse_r < best[0]:
                best = (sse_l + sse_r, j, (xs[i-1] + xs[i]) / 2)
    if best[1] is None: return y.mean()
    _, j, t = best; mask = X[:, j] <= t
    return (j, t, build(X[mask], y[mask], depth-1, min_leaf, m),
                  build(X[~mask], y[~mask], depth-1, min_leaf, m))

def predict(node, X):
    if not isinstance(node, tuple): return np.full(len(X), node)
    j, t, l, r = node; mask = X[:, j] <= t
    out = np.empty(len(X)); out[mask] = predict(l, X[mask]); out[~mask] = predict(r, X[~mask])
    return out

Xtr, ytr = make_data(500); Xte, yte = make_data(2000)
mse = lambda p: np.mean((p - yte)**2)
print(f"noise floor (irreducible) MSE   = {0.3**2:.3f}")
print(f"predict the mean                = {mse(np.full(len(yte), ytr.mean())):.3f}")
print(f"stump (depth 1)                 = {mse(predict(build(Xtr, ytr, 1), Xte)):.3f}")
print(f"deep tree (depth 12, leaf>=1)   = {mse(predict(build(Xtr, ytr, 12, min_leaf=1), Xte)):.3f}")

# Random forest: bootstrap rows + m random features per split, average B deep trees
preds = []
for b in range(100):
    idx = rng.integers(0, len(ytr), len(ytr))
    preds.append(predict(build(Xtr[idx], ytr[idx], 12, min_leaf=1, m=2), Xte))
print(f"random forest (100 trees, m=2)  = {mse(np.mean(preds, axis=0)):.3f}")

# Gradient boosting, squared loss: each depth-3 tree fits the residuals (= negative gradient)
F, Fte, lr = np.full(len(ytr), ytr.mean()), np.full(len(yte), ytr.mean()), 0.1
for t in range(1, 301):
    tree = build(Xtr, ytr - F, 3)
    F += lr * predict(tree, Xtr); Fte += lr * predict(tree, Xte)
    if t in (1, 10, 50, 100, 300):
        print(f"boosting, {t:3d} trees: train MSE {np.mean((F-ytr)**2):.3f}  test MSE {mse(Fte):.3f}")

Output (about 3 seconds on a laptop):

noise floor (irreducible) MSE   = 0.090
predict the mean                = 0.612
stump (depth 1)                 = 0.209
deep tree (depth 12, leaf>=1)   = 0.186
random forest (100 trees, m=2)  = 0.109
boosting,   1 trees: train MSE 0.532  test MSE 0.517
boosting,  10 trees: train MSE 0.158  test MSE 0.171
boosting,  50 trees: train MSE 0.054  test MSE 0.106
boosting, 100 trees: train MSE 0.041  test MSE 0.109
boosting, 300 trees: train MSE 0.016  test MSE 0.122

Read it against the bias–variance story. The fully grown tree has near-zero training error and a test MSE of 0.186, twice the noise floor: pure variance. Averaging 100 decorrelated deep trees removes most of it (0.109). Boosting depth-3 trees starts with high bias (one shrunken tree: 0.517), reaches the best test error of the lot around 50 trees (0.106), and then keeps driving training error down while test error creeps back up (0.122 at 300 trees). That rising tail is why every GBDT library has early stopping on a validation set.

Things to try

  • Set m=None in the forest (plain bagging). Test MSE rises: with only two informative features out of five, unrestricted trees all split on \(x_1\) first and are highly correlated.
  • Boost with lr=1.0: the best test error arrives in a handful of trees and is worse. Then try lr=0.02 with 1,000 trees.
  • Replace squared loss with absolute loss (fit trees to np.sign(ytr - F), and set leaf values to the median residual), then add a few large outliers to ytr.
  • Add the XGBoost leaf value \(-G/(H+\lambda)\): for squared loss, divide the leaf's residual sum by count + lam instead of count, and watch what \(\lambda\) does to small leaves.
  • Compare with sklearn.ensemble.HistGradientBoostingRegressor(early_stopping=True) on the same data: it should match or beat the from-scratch numbers in a fraction of a second.

Check yourself

A node has 60 positives and 40 negatives. What are its Gini impurity and entropy?

Gini \(= 1 - 0.6^2 - 0.4^2 = 0.48\). Entropy \(= -0.6\log_2 0.6 - 0.4\log_2 0.4 \approx 0.442 + 0.529 = 0.971\) bits.

Why does a random forest choose a random subset of features at every split rather than once per tree?

Per-split sampling decorrelates trees far more: a single dominant feature would otherwise be chosen at the root of every tree that is allowed to see it, so many trees would still share their top structure. Randomising at each split forces alternative structures throughout every tree, lowering \(\rho\) in \(\rho\sigma^2 + (1-\rho)\sigma^2/B\).

Your gradient-boosted model's training loss keeps falling but validation loss bottomed out at round 340. What do you do and why?

Use the model at round ~340 (early stopping). Later rounds fit noise in the residuals: each tree is still a valid gradient step on the training loss, which is no longer a good proxy for test loss. If you want more rounds, lower the learning rate (more, smaller steps usually reach a slightly better minimum) and add subsampling or \(\lambda\).

For binary log-loss with F the log-odds, what does the first gradient-boosting tree fit if F0 is the base-rate log-odds and the base rate is 20%?

\(F_0 = \ln(0.2/0.8) = -1.386\), so every \(p_i = 0.2\). Pseudo-residuals are \(y_i - 0.2\): \(+0.8\) for positives and \(-0.2\) for negatives. The tree splits to separate rows with many positives from rows with few; Newton leaf values are \(\sum(y_i - 0.2)/\sum 0.16\).

Show that with λ = 0, the XGBoost gain for squared loss equals the reduction in sum of squared residuals (up to a factor).

With \(g_i = F - y_i = -r_i\) and \(h_i = 1\): \(G^2/H = (\sum r_i)^2/n\). Since \(\mathrm{SSE} = \sum r_i^2 - (\sum r_i)^2/n\) and \(\sum r_i^2\) is the same before and after the split, \(\mathrm{SSE}_{\text{parent}} - \mathrm{SSE}_L - \mathrm{SSE}_R = \frac{G_L^2}{n_L} + \frac{G_R^2}{n_R} - \frac{(G_L+G_R)^2}{n}\), which is twice the Gain with \(\gamma = 0\). So XGBoost generalises the CART regression criterion.

Why are trees invariant to monotone transformations of a feature but not to rotations of the feature space?

A split depends only on the ordering of values of one feature; a monotone map preserves the ordering, so the same partitions are available. A rotation mixes features: a boundary that was axis-aligned becomes diagonal and needs a staircase of many splits. This is the "trees are not rotation-invariant" bias that Grinsztajn et al. argue suits tabular data.

Hard: AdaBoost's training error often keeps falling to zero, and test error keeps falling even after that. Why might adding learners after zero training error still help?

Because the margins \(y_i\sum_t\alpha_t h_t(\mathbf{x}_i)/\sum_t\alpha_t\) keep growing even when all signs are already correct, and generalisation bounds for voting classifiers depend on the margin distribution, not just training error (Schapire, Freund, Bartlett and Lee, 1998). The exponential loss keeps pushing points further from the boundary, the same mechanism as an SVM's margin (see kernels and SVMs). On noisy labels, though, the exponential loss over-weights mislabelled points and AdaBoost overfits.

Go deeper

Papers

Videos and lectures

Articles and blog posts

Courses and books

Code

Where this leads