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 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 and every threshold , split the node's data into and , 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 . This is "variance reduction".
- Classification: with class proportions in a node, the Gini impurity is and the entropy is . A split's score is the size-weighted average impurity of the children:
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 solutionHide solution
Parent: .
Split A. The left child is pure, . The right child has proportions , so . Weighted impurity: . Reduction .
Split B. and . Weighted impurity . Reduction .
The tree takes split A. Entropy agrees: the parent has bits, split A leaves and split B leaves . 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 have targets . Where does a regression stump split, and what is the reduction in squared error?
Show solutionHide solution
The root mean is , so .
Only the five cut points between consecutive sorted values need checking. Splitting after the third point gives left with mean 2 and SSE 2, right with mean 8 and SSE 2, total 4. The other cuts give totals .
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 points and features, an efficient implementation sorts once per feature and sweeps the cut points with running sums, costing 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 trees on bootstrap resamples and averages them.
If each tree's prediction at a point has variance and any two trees have correlation , the average has variance
The second term vanishes as 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 directly: at every split it considers only a random subset of max_features features (a common default is for classification). Weaker individual trees, but far less correlated, so the average is better.
Two side benefits of bootstrapping: each tree leaves out about 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 , 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 and pick a differentiable loss . At step :
- Compute the pseudo-residuals , the negative gradient of the loss at each training point.
- Fit a small regression tree to .
- Update with learning rate (shrinkage) .
For squared loss the negative gradient is , the ordinary residual, so boosting literally fits trees to residuals. For log loss in classification it is ; for absolute loss it is , 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 grows, so the number of rounds is chosen by validation (early stopping).
Worked example
two rounds of boosting by hand
Use the six points from the stump example, squared loss, stumps as weak learners and learning rate . Start from . What is the training SSE after one and after two rounds?
Show solutionHide solution
, residuals , SSE 58.
Round 1. The best stump on the residuals splits after the third point (as before) and predicts the group means and . Update: , i.e. on the left and on the right. New residuals , SSE .
Round 2. The best stump is the same split, now with means , so each side moves halfway again to and . SSE .
The SSE decomposes as the within-group part (4, which a stump cannot remove) plus , and the offset halves each round: A smaller 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
| Model | Knob | Effect |
|---|---|---|
| Tree | max_depth, min_samples_leaf | Main complexity controls. Large leaves are the best defence against noise. |
| Forest | max_features | Lower decorrelates trees (smaller ), raises each tree's bias. |
| Forest | n_estimators | More is never worse, only slower. |
| Boosting | learning rate and rounds | Trade off against each other: halve , roughly double . Pick by early stopping. |
| Boosting | tree depth | Depth allows interactions of order up to . Depth 2 to 6 is typical. |
| Boosting | subsample | Fit each tree on a random fraction of rows (stochastic gradient boosting); reduces variance. |
| Boosting | L1/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 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 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 and pairwise correlation . 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 trees leaves variance ; random forests win by lowering , not by raising .
- 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 , and never trust training fit.
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).