Skip to content
LeetQuant
QR06 Machine Learning and Model Validation

QR06 · Machine Learning and Model Validation · Lesson 2 of 5

Trees, Forests and Boosting

How a decision tree chooses its splits, why bagging and random forests cut variance, how gradient boosting performs gradient descent in function space, which hyperparameters matter, and when tree ensembles suit financial data.

18 min

Objective

Tree ensembles are the default model for tabular data, and interviewers expect you to explain them from the split rule upwards. By the end you should be able to compute a split by hand, derive the variance of a bagged average, describe boosting as gradient descent on the loss, and say which knobs control overfitting.

One tree: greedy recursive splitting

A decision tree partitions feature space into rectangles and predicts a constant in each: the mean of yy for regression, the class proportions for classification. Finding the best tree is NP-hard, so trees are grown greedily: at each node, try every feature jj and every threshold ss, split the node's data into {xj≤s}\{x_j \le s\} and {xj>s}\{x_j > s\}, and keep the split that most reduces an impurity measure.

  • Regression: impurity is the sum of squared errors around the node mean, so the split maximises the drop SSEparent−(SSEL+SSER)\text{SSE}_{\text{parent}} - (\text{SSE}_L + \text{SSE}_R). This is "variance reduction".
  • Classification: with class proportions pkp_k in a node, the Gini impurity is G=1−∑kpk2G = 1 - \sum_k p_k^2 and the entropy is H=−∑kpklog⁡2pkH = -\sum_k p_k \log_2 p_k. A split's score is the size-weighted average impurity of the children:
Δ=I(parent)−nLn I(L)−nRn I(R).\Delta = I(\text{parent}) - \frac{n_L}{n}\, I(L) - \frac{n_R}{n}\, I(R) .

Growth stops at a maximum depth, a minimum number of samples per leaf, or when no split improves impurity by enough. A fully grown tree has one observation per leaf: zero training error, very high variance.

Properties worth stating in an interview: trees are invariant to monotone transformations of each feature (only the ordering matters), they handle interactions automatically (a split inside a split is an interaction), they need no scaling, and they extrapolate flat: beyond the training range the prediction is the constant of the outermost leaf.

Worked example

choosing a classification split

A node holds 10 days: 6 up days and 4 down days. Two candidate splits:

  • A: left has 4 days (4 up, 0 down), right has 6 days (2 up, 4 down).
  • B: left has 5 days (4 up, 1 down), right has 5 days (2 up, 3 down).

Which split does a Gini tree choose, and by how much does it reduce impurity?

Show solution

Parent: G=1−0.62−0.42=1−0.36−0.16=0.48G = 1 - 0.6^2 - 0.4^2 = 1 - 0.36 - 0.16 = 0.48.

Split A. The left child is pure, GL=0G_L = 0. The right child has proportions 13,23\tfrac13, \tfrac23, so GR=1−19−49=49G_R = 1 - \tfrac19 - \tfrac49 = \tfrac49. Weighted impurity: 610⋅49=415≈0.267\tfrac{6}{10}\cdot\tfrac49 = \tfrac{4}{15} \approx 0.267. Reduction 0.48−0.267=0.2130.48 - 0.267 = 0.213.

Split B. GL=1−0.64−0.04=0.32G_L = 1 - 0.64 - 0.04 = 0.32 and GR=1−0.16−0.36=0.48G_R = 1 - 0.16 - 0.36 = 0.48. Weighted impurity 0.5(0.32)+0.5(0.48)=0.400.5(0.32) + 0.5(0.48) = 0.40. Reduction 0.080.08.

The tree takes split A. Entropy agrees: the parent has H≈0.971H \approx 0.971 bits, split A leaves 0.6×0.918≈0.5510.6 \times 0.918 \approx 0.551 and split B leaves ≈0.846\approx 0.846. Gini and entropy rarely disagree on the chosen split; Gini is cheaper because it avoids logarithms.

Worked example

a regression split by variance reduction

Six observations sorted by a feature xx have targets y=(1,2,3,7,8,9)y = (1, 2, 3, 7, 8, 9). Where does a regression stump split, and what is the reduction in squared error?

Show solution

The root mean is 55, so SSEroot=16+9+4+4+9+16=58\text{SSE}_{\text{root}} = 16 + 9 + 4 + 4 + 9 + 16 = 58.

Only the five cut points between consecutive sorted xx values need checking. Splitting after the third point gives left {1,2,3}\{1,2,3\} with mean 2 and SSE 2, right {7,8,9}\{7,8,9\} with mean 8 and SSE 2, total 4. The other cuts give totals 38.8,21.25,21.25,38.838.8, 21.25, 21.25, 38.8.

The stump splits after the third point, predicts 2 on the left and 8 on the right, and reduces SSE from 58 to 4, a drop of 54. With nn points and pp features, an efficient implementation sorts once per feature and sweeps the cut points with running sums, costing O(p nlog⁡n)O(p\, n \log n) per node.

Bagging and random forests: averaging away variance

A deep tree has low bias and huge variance: change a few training points and the top split, and therefore the whole tree, can change. Bagging (bootstrap aggregating) fits BB trees on bootstrap resamples and averages them.

If each tree's prediction at a point has variance σ2\sigma^2 and any two trees have correlation ρ\rho, the average has variance

Var⁡(1B∑b=1Bf^b(x))=ρ σ2+1−ρB σ2.\operatorname{Var}\Big(\frac1B \sum_{b=1}^{B} \hat f_b(x)\Big) = \rho\,\sigma^2 + \frac{1-\rho}{B}\,\sigma^2 .

The second term vanishes as BB grows; the first does not. Bagged trees are highly correlated because they all see roughly the same data and all pick the same strong feature for the top split. A random forest attacks ρ\rho directly: at every split it considers only a random subset of max_features features (a common default is p\sqrt p for classification). Weaker individual trees, but far less correlated, so the average is better.

Two side benefits of bootstrapping: each tree leaves out about (1−1/n)n→e−1≈36.8%(1 - 1/n)^n \to e^{-1} \approx 36.8\% of the observations, which gives a free out-of-bag error estimate; and adding trees never overfits in the sense that test error does not rise with BB, it only plateaus. (The out-of-bag estimate assumes independent observations, so it is optimistic on overlapping financial labels; see the time-series cross-validation lesson.)

Gradient boosting: gradient descent in function space

Boosting builds the model sequentially: each new small tree corrects the current ensemble's errors. Write the model as FM(x)=F0(x)+ν∑m=1Mhm(x)F_M(x) = F_0(x) + \nu \sum_{m=1}^{M} h_m(x) and pick a differentiable loss L(y,F)L(y, F). At step mm:

  1. Compute the pseudo-residuals ri=−∂L(yi,F)∂F∣F=Fm−1(xi)r_i = -\dfrac{\partial L(y_i, F)}{\partial F}\Big|_{F = F_{m-1}(x_i)}, the negative gradient of the loss at each training point.
  2. Fit a small regression tree hmh_m to (xi,ri)(x_i, r_i).
  3. Update Fm=Fm−1+ν hmF_m = F_{m-1} + \nu\, h_m with learning rate (shrinkage) ν∈(0,1]\nu \in (0, 1].

For squared loss L=12(y−F)2L = \tfrac12 (y - F)^2 the negative gradient is y−Fy - F, the ordinary residual, so boosting literally fits trees to residuals. For log loss in classification it is y−py - p; for absolute loss it is sign⁡(y−F)\operatorname{sign}(y - F), which makes the procedure robust to outliers. The tree is a step in the direction of steepest descent, restricted to functions a small tree can represent.

Bagging and boosting attack different terms: a forest averages low-bias, high-variance trees to cut variance; boosting adds high-bias stumps or shallow trees one at a time to cut bias. Boosting therefore can overfit as MM grows, so the number of rounds is chosen by validation (early stopping).

Worked example

two rounds of boosting by hand

Use the six points y=(1,2,3,7,8,9)y = (1, 2, 3, 7, 8, 9) from the stump example, squared loss, stumps as weak learners and learning rate ν=0.5\nu = 0.5. Start from F0=yˉF_0 = \bar y. What is the training SSE after one and after two rounds?

Show solution

F0=5F_0 = 5, residuals (−4,−3,−2,2,3,4)(-4, -3, -2, 2, 3, 4), SSE 58.

Round 1. The best stump on the residuals splits after the third point (as before) and predicts the group means −3-3 and +3+3. Update: F1=5+0.5(∓3)F_1 = 5 + 0.5(\mp 3), i.e. 3.53.5 on the left and 6.56.5 on the right. New residuals (−2.5,−1.5,−0.5,0.5,1.5,2.5)(-2.5, -1.5, -0.5, 0.5, 1.5, 2.5), SSE =2(6.25+2.25+0.25)=17.5= 2(6.25 + 2.25 + 0.25) = 17.5.

Round 2. The best stump is the same split, now with means ∓1.5\mp 1.5, so each side moves halfway again to 2.752.75 and 7.257.25. SSE =4+6×0.752=7.375= 4 + 6 \times 0.75^2 = 7.375.

The SSE decomposes as the within-group part (4, which a stump cannot remove) plus 6×(remaining group offset)26 \times (\text{remaining group offset})^2, and the offset halves each round: 3,1.5,0.75,…3, 1.5, 0.75, \dots A smaller ν\nu approaches the same fit more slowly; the slow approach is what regularises, because later trees get to correct earlier ones instead of committing fully to each.

The hyperparameters that matter

ModelKnobEffect
Treemax_depth, min_samples_leafMain complexity controls. Large leaves are the best defence against noise.
Forestmax_featuresLower decorrelates trees (smaller ρ\rho), raises each tree's bias.
Forestn_estimatorsMore is never worse, only slower.
Boostinglearning rate ν\nu and rounds MMTrade off against each other: halve ν\nu, roughly double MM. Pick MM by early stopping.
Boostingtree depthDepth dd allows interactions of order up to dd. Depth 2 to 6 is typical.
BoostingsubsampleFit each tree on a random fraction of rows (stochastic gradient boosting); reduces variance.
BoostingL1/L2 penalty on leaf values (XGBoost, LightGBM)Shrinks leaf predictions; helps with noisy targets.

When trees fit financial data

Trees suit tabular, heterogeneous features with non-linearities and interactions: fundamentals, ratios, flags, regime indicators. They are robust to outliers in features and need no scaling, which matters when features have fat tails.

They struggle with what makes finance hard. With a signal-to-noise ratio where the best achievable R2R^2 is 1–3%, deep trees memorise noise; leaves must be large and boosting must be heavily shrunk. Trees cannot extrapolate, so a feature drifting outside its historical range gets a stale constant. They split on raw levels, so non-stationary features (price levels, unnormalised volumes) should be converted to returns, ranks or z-scores first. And the bootstrap and out-of-bag machinery assume independent rows, which overlapping labels violate.

Seeing it on noisy data

The script below plants a weak non-linear signal (best achievable test R2R^2 about 3%) in unit-variance noise and compares a deep tree, a shallow tree, a forest with large leaves and a heavily shrunk boosting model.

import numpy as np
from sklearn.tree import DecisionTreeRegressor
from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor

rng = np.random.default_rng(0)
n = 6000
X = rng.normal(size=(n, 5))
f = 0.2 * np.tanh(2 * X[:, 0]) + 0.1 * X[:, 1] * X[:, 2]   # weak non-linear signal
y = f + rng.normal(size=n)                                  # noise swamps it
Xtr, Xte, ytr, yte = X[:4000], X[4000:], y[:4000], y[4000:]

models = {
    "deep tree": DecisionTreeRegressor(random_state=0),
    "depth-3 tree": DecisionTreeRegressor(max_depth=3, random_state=0),
    "random forest": RandomForestRegressor(n_estimators=300, min_samples_leaf=50,
                                           max_features=2, random_state=0),
    "boosting": GradientBoostingRegressor(n_estimators=200, learning_rate=0.02,
                                          max_depth=2, subsample=0.5, random_state=0),
}
for name, m in models.items():
    m.fit(Xtr, ytr)
    print(f"{name:14s} train R^2 {m.score(Xtr, ytr):+.3f}  test R^2 {m.score(Xte, yte):+.3f}")
print(f"best possible  test R^2 {1 - np.mean((yte - f[4000:])**2) / np.var(yte):+.3f}")

Output:

deep tree      train R^2 +1.000  test R^2 -1.049
depth-3 tree   train R^2 +0.028  test R^2 +0.004
random forest  train R^2 +0.083  test R^2 +0.020
boosting       train R^2 +0.048  test R^2 +0.015
best possible  test R^2 +0.030

The deep tree fits the training set perfectly and is twice as bad as predicting the mean out of sample. The regularised ensembles recover about half to two thirds of the available signal, which is a realistic outcome in finance.

Knowledge check

Each tree in an ensemble has prediction variance σ2=1\sigma^2 = 1 and pairwise correlation ρ=0.6\rho = 0.6. Roughly what is the variance of the average of 1,000 trees?

Knowledge check

In gradient boosting with log loss for a binary label, what does each new tree fit?

Knowledge check

A boosted model's validation loss bottoms out at 300 rounds with learning rate 0.1 and rises afterwards. Which change is most likely to improve validation loss?

Key takeaways

  • A tree splits greedily to maximise impurity reduction: SSE for regression, Gini or entropy for classification.
  • Averaging BB trees leaves variance ρσ2+(1−ρ)σ2/B\rho\sigma^2 + (1-\rho)\sigma^2/B; random forests win by lowering ρ\rho, not by raising BB.
  • Gradient boosting fits each tree to the negative gradient of the loss; for squared loss that is the residual. It cuts bias and can overfit, so use shrinkage and early stopping.
  • Trees are scale-free and capture interactions, but they cannot extrapolate and memorise noise unless leaves are large.
  • In low signal-to-noise problems, expect regularised ensembles to capture only part of a small R2R^2, and never trust training fit.

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).