Notes
All notes

Deriving Gradient Boosting (ML #8)

Chapter 7’s forests reduced variance and left bias untouched, so they plateaued at whatever error a single tree makes. Boosting goes after that bias directly. Its idea is startlingly simple: fit a weak model, look at what you got wrong, fit another model to those specific errors, and repeat.

The algorithm is four lines. The interesting part is why it works at all, and the answer turns out to be that boosting is secretly Newton’s method wearing a different hat — which is a satisfying thing to derive rather than take on faith.

This chapter derives the stagewise additive model, shows that leaf values are exactly Newton steps, and explains why a small learning rate buys generalization.

The stagewise additive model

Both ensembles start from the same place: predict with a weighted sum of weak learners. Forests differ in how they build that sum — parallel, on resampled data — while boosting builds it sequentially, with each new learner correcting the current prediction:

\[ F_0(x) = \bar{y} = \text{constant}, \qquad F_m(x) = F_{m-1}(x) + f_m(x) \]

At stage \(m\) we choose \(f_m\) to minimize the loss of \(F_{m-1} + f_m\):

\[ f_m = \arg\min_{f}\; L\!\left(y_i - \left[F_{m-1}(x_i) + f(x_i)\right]\right)_{i=1}^{n} \]

Now the key move. For squared error, \(\frac12\sum_i (y_i - F_{m-1}(x_i) - f(x_i))^2\) has a unique decomposition. Write \(r_i = y_i - F_{m-1}(x_i)\), the residual of the current model on point \(i\). Then:

\[ \frac{1}{2}\sum_i \left(r_i - f(x_i)\right)^2 \]

which is minimized by the best least-squares fit to the residuals \(r_i\). So for squared error the stage-\(m\) learner is a regression model trained on the current residuals — no further machinery. Every boosting iteration is “fit a shallow tree to the mistakes.”

Notice what makes this work: the correction is targeted. Forest averaging applies every tree everywhere and hopes the errors cancel; boosting applies each new tree only where the previous ones fell short. That is why it can fix bias.

import numpy as np

def fit_boosting_squared(X, y, n_trees=100, lr=0.1, max_depth=2, seed=0):
    """Gradient boosting for squared error: each tree fits the current residuals."""
    rng = np.random.default_rng(seed)
    n = len(y)
    trees, F = [], np.full(n, y.mean())        # F_0 = the constant mean
    for _ in range(n_trees):
        r = y - F                              # residuals of the current model
        tree = RegressionTree(max_depth=max_depth)
        tree.fit(X, r)                         # fit to mistakes, not to y
        trees.append(tree)
        F += lr * tree.predict(X)              # shrunk additive update
    return trees, F

Note max_depth=2: each learner must be weak. The whole division of labor depends on it.

Leaf values are Newton steps

Now generalize past squared error, because this is where the connection to Chapter 4 appears. Take a general loss \(L(y, F)\) and expand it to second order around the current prediction \(F_{m-1}(x_i)\):

\[ L(y_i, F_{m-1} + f) \approx L(y_i, F_{m-1}) + g_i f + \frac{1}{2}h_i f^2 \]

with the per-point gradient and Hessian of the loss with respect to the prediction:

\[ g_i = \frac{\partial L}{\partial F}(y_i, F_{m-1}(x_i)), \qquad h_i = \frac{\partial^2 L}{\partial F^2}(y_i, F_{m-1}(x_i)) \]

The first term is constant in \(f\), so drop it. Now constrain \(f\) to be constant on a leaf — say value \(v\) on the points in leaf \(L\). The objective for that leaf becomes \(\sum_{i \in L} g_i v + \frac12 h_i v^2\). Differentiate with respect to \(v\) and set to zero:

\[ \frac{\partial}{\partial v}\left(\sum_{i\in L} g_i v + \tfrac12 h_i v^2\right) = \sum_{i \in L} g_i + v\sum_{i \in L} h_i = 0 \;\Longrightarrow\; v^*_L = -\frac{\sum_{i \in L} g_i}{\sum_{i \in L} h_i} \]

That is a Newton step. Compare Chapter 4’s \(\theta_{t+1} = \theta_t - H^{-1}\nabla_\theta L\): Newton updates parameters by a gradient divided by a curvature. Boosting’s leaf update is a gradient divided by a curvature — summed over the points in the leaf instead of solved as a system, because the leaf value is a single parameter. Boosting is Newton’s method applied one leaf at a time.

Check that squared error is the special case. For \(L = \frac12(y-F)^2\):

\[ g_i = F_{m-1}(x_i) - y_i = -r_i, \qquad h_i = 1 \]

Substituting gives \(v^*_L = -\frac{\sum(-r_i)}{n_L} = \frac{1}{n_L}\sum_{i\in L} r_i\) — the mean residual in the leaf, exactly the least-squares result above. The residual heuristic and the Newton formulation are two views of one derivation. This is the equation that makes gradient boosting “gradient” boosting: fit the negative gradient, not literally the residual.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.6cm, minimum height=0.75cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=gray!12] (l0) at (0,3.2) {$F_0 = \bar{y}$};
  \node[b, fill=blue!10] (l1) at (0,1.9) {$F_1 = F_0 + f_1$\\$f_1$ fits residuals};
  \node[b, fill=blue!10] (l2) at (0,0.6) {$F_2 = F_1 + f_2$\\$f_2$ fits residuals of $F_1$};
  \node[b, fill=orange!16] (l3) at (0,-0.7) {$F_3 = F_2 + f_3$};
  \node[b, fill=green!12] (out) at (4.6,-0.7) {$F_M$: bias driven down\\stage by stage};
  \draw[a] (l0) -- (l1); \draw[a] (l1) -- (l2); \draw[a] (l2) -- (l3);
  \draw[a] (l3) -- (out);
  \node[font=\rmfamily\scriptsize, text=black!60, align=left] at (-3.6,1.4) {each stage sees only\\the *current* errors;\\sequence is what makes\\correction possible};
\end{tikzpicture}

The learning rate is the variance control

Two knobs control the fit: tree count \(M\) and shrinkage \(\eta\). The update is \(\eta f_m\), and \(\eta\) is not cosmetic. Small \(\eta\) means each stage is a small correction, which buys two things:

This is the classic bias–variance trade in a single scalar. Empirically, 100 trees at \(\eta = 0.1\) routinely beats 20 trees at \(\eta = 0.5\) at similar training error, because the smaller-step version has lower variance out-of-sample. There is no universal “right” value, but \(\eta \in [0.01, 0.1]\) with many more trees is the robust default region — the interaction with tree count is exactly what makes boosting easy to under-tune in both directions.

for lr, trees in [(0.5, 20), (0.2, 50), (0.1, 200), (0.02, 500)]:
    _, F = fit_boosting_squared(X, y, n_trees=trees, lr=lr)
    print(f"lr={lr:.2f} trees={trees:3d} train MSE={np.mean((y - F)**2):.5f}")

Why boosting can beat forests

Bagging / Random Forest Gradient Boosting
Build parallel, on bootstrap samples sequential, each on current residuals
Targets variance bias
Base learner deep, high variance shallow (depth 2–4), low variance
Trees are… diverse by resampling diverse by fitting different errors
Many trees help? yes, up to \(\rho\)-limited saturation yes, more reliably
Tuning pressure low high (\(\eta\), depth, \(M\) interact)
Overfits via deep trees, few samples/node too much \(\eta\) or depth, too little data

The practical dividing line: random forests are “just works” defaults with almost nothing to tune, while boosting wins competitions because it can be tuned hard. If you have the validation budget and the data volume to tune \(\eta\) and depth jointly, boosting usually edges forests out. If you want a model this afternoon, take the forest.

Stochastic gradient boosting

XGBoost and LightGBM add one ingredient that matters more than it sounds: feature subsampling and row subsampling at every stage. Each weak learner sees a random subset of rows and a random subset of features, which injects noise into the boosting process.

Why does adding noise help? It prevents the model from chasing the same small quirks at every stage — each learner can only correct what it happens to see, so no single tree can fit noise precisely and completely. The noise averages out across stages exactly as it does across forest members. It is the same variance-reduction mechanism as bagging, grafted onto a sequential method, and it is why subsample < 1.0 is usually a free win.

The failure mode that surprises people

Boosting overfits quietly. Because each stage reduces training loss a little, training error keeps dropping smoothly while test error bottoms out and climbs — and the crossing is often smooth enough to miss without a validation curve. A shallow tree with \(\eta\) near 0.1 needs hundreds of trees before it visibly bends; by then you’ve trained for an hour.

Guard against it explicitly: always plot validation error against stage count and pick the stopping point there (early stopping is the standard implementation), never by looking at training loss. And keep the trees shallow — a boosting stage that can split freely can fit noise exactly, which defeats the entire division of labor.

Pitfalls

QQuestionSelf-check

Show that for squared error the gradient boosting leaf update \(v^*_L = -\frac{\sum_{i\in L} g_i}{\sum_{i \in L} h_i}\) reduces to the mean residual in that leaf. Why can averaging many trees fail to reduce bias while boosting does reduce it? Your boosting model has 2000 trees, \(\eta = 0.5\), training MSE 0.001 and test MSE 0.31. Diagnose it and give three specific changes with their effect on bias and variance.

ASolution

For \(L = \frac12(y-F)^2\), differentiating the loss with respect to the prediction gives \(g_i = \partial L/\partial F = F - y = -r_i\) and \(h_i = \partial^2 L/\partial F^2 = 1\), so \(v^*_L = -\frac{\sum(-r_i)}{\sum 1} = \frac{1}{n_L}\sum_{i \in L} r_i\) — the mean residual, exactly the least-squares solution to minimizing \(\frac12\sum(r_i - v)^2\) in that leaf. Averaging fails on bias because \(\mathbb{E}[\frac1M\sum f_m] = \mathbb{E}[f_1]\): the mean of identically-biased predictors is identically biased, so the errors cannot cancel systematically; boosting reduces bias because each stage is fit to the current errors and is added with the opposite sign of the bias it targets, so successive stages remove the bias the previous ones left. On the diagnosis: with training MSE at 0.001 the model has essentially memorized the training noise. First, reduce \(\eta\) from 0.5 to ~0.05 and add trees to compensate — this lowers variance by making the ensemble behave like averaging, at the cost of a slower, slightly higher-bias fit; in practice a small learning rate plus many trees beats a large one plus few at equal training error. Second, cut tree depth from whatever it is to 2–4 — a weak learner cannot chase noise, which raises bias slightly and cuts variance sharply. Third, enable row and feature subsampling per stage (stochastic gradient boosting), which adds variance to each member so it averages out and stops any single tree fitting noise exactly. Then select the stopping point on a validation curve — the model is past it long before tree 2000.

Next: Deriving Support Vector Machines (ML #9) — the Lagrangian dual, why only support vectors survive, and the kernel trick that follows from the algebra.