Module contents
Lesson 17 of 24Core 110 min

Gradient boosting: gradient descent in function space

Derive Friedman’s gradient boosting as functional gradient descent: at each stage fit a regression tree to pseudo-residuals (negative loss gradients evaluated on the data) and optimize each leaf value. Instantiate the algorithm for squared, absolute, Huber, quantile and logistic losses, and introduce practical regularizers: shrinkage, stochastic subsampling and early stopping.

After this lesson you can

  • Derive gradient boosting from gradient descent in function space.
  • Calculate pseudo-residuals and optimal leaf values for squared, absolute, Huber, quantile and logistic losses (binomial deviance).
  • Implement gradient boosting from scratch on a custom regression tree and reproduce GradientBoostingRegressor.
  • Explain the combined effect of learning rate, tree count and depth, and apply early stopping.
  • Justify stochastic subsampling as variance reduction and acceleration.

Before you start

Motivation: the tabular data algorithm

If you work with tabular data (credit risk, fraud detection, search ranking, demand forecasting, quantitative finance signals), the model that ends up in production will most likely be an ensemble of trees built by gradient boosting. This is not just an impression: in the XGBoost paper, Chen and Guestrin (2016) counted that, among 29 winning competition solutions published on Kaggle’s blog during 2015, 17 used XGBoost (8 as the sole model), versus 11 using deep networks. In a systematic study of 45 datasets, Grinsztajn, Oyallon and Varoquaux (2022) conclude that tree-based models remain state of the art on medium-sized tabular data (about 10,000 examples), even without counting their speed advantage.

XGBoost, LightGBM and CatBoost, covered in the following lessons, are engineering built on a 1999 idea by Jerome Friedman (published in 2001): perform gradient descent in function space. In the previous lesson you saw AdaBoost as forward stagewise additive modeling with exponential loss: each stage adds the term that reduces loss most without changing previous ones. That recipe is convenient only for particular losses. Friedman turned it into a generic algorithm: for any differentiable loss (and some nondifferentiable ones, such as absolute loss), calculate the loss gradient at the training points, fit a regression tree to its negative, and take a step.

This lesson derives the algorithm from scratch, instantiates it for five losses (squared, absolute, Huber, quantile and binomial deviance), studies the three regularizers that make it work in practice (learning rate, subsampling and early stopping), and finishes with our own implementation that reproduces scikit-learn’s GradientBoostingRegressor and GradientBoostingClassifier to the last decimal.

From gradient descent in ℝⁿ to function space

We want a function F:Rd→RF : \R^d \to \R that minimizes empirical risk

R^(F)=1n∑i=1nℓ(yi,F(xi)),\hat{R}(F) = \frac{1}{n}\sum_{i=1}^n \ell\big(y_i, F(\vb{x}_i)\big),

where ℓ\ell is a loss differentiable in its second argument (for example, ℓ(y,F)=12(y−F)2\ell(y, F) = \tfrac12 (y - F)^2). In a parametric model, F=FθF = F_\theta, gradient descent moves θ\theta. Here there are no parameters: the unknown is the entire function.

The first step is to realize that R^\hat{R} only looks at FF at nn points. Call F=(F(x1),…,F(xn))∈Rn\vb{F} = \big(F(\vb{x}_1), \dots, F(\vb{x}_n)\big) \in \R^n the prediction vector. Then R^(F)=1n∑iℓ(yi,Fi)\hat{R}(F) = \frac1n\sum_i \ell(y_i, F_i) is an ordinary function of nn variables, and its gradient has one component per example:

gi=∂ℓ(yi,F)∂F∣F=F(xi),i=1,…,ng_i = \frac{\partial \ell(y_i, F)}{\partial F}\bigg|_{F = F(\vb{x}_i)}, \qquad i = 1, \dots, n

(We omit the factor 1/n1/n, which only rescales the step.) Gradient descent in Rn\R^n would be F←F−η g\vb{F} \leftarrow \vb{F} - \eta\,\vb{g}. With squared loss, gi=Fi−yig_i = F_i - y_i, and a step with η=1\eta = 1 leads directly to Fi=yiF_i = y_i: it memorizes the data in one step and says nothing about F(x)F(\vb{x}) at a new point. Vector −g-\vb{g} is a direction in the space of values at the data points, not a function.

The solution is to restrict the direction to a class H\mathcal{H} of functions that can be evaluated at any x\vb{x} (small regression trees, for example), and find within that class the function most similar to −g-\vb{g} on the data:

h=arg min⁡h∈H∑i=1n(−gi−h(xi))2.h = \argmin_{h \in \mathcal{H}} \sum_{i=1}^n \big(-g_i - h(\vb{x}_i)\big)^2 .

Fitting hh by least squares to −gi-g_i projects the gradient onto the class. Then perform a line search along hh and update F←F+ρhF \leftarrow F + \rho h. The resulting function is defined over all Rd\R^d, because it is a sum of trees.

Why does least-squares projection give a descent direction? Use the data inner product, ⟨u,v⟩n=1n∑iu(xi)v(xi)\inner{u}{v}_n = \frac1n\sum_i u(\vb{x}_i)v(\vb{x}_i), and its norm ∥u∥n\norm{u}_n. A first-order Taylor expansion in each component gives

R^(F+εh)=R^(F)+ε ⟨g,h⟩n+o(ε),\hat{R}(F + \eps h) = \hat{R}(F) + \eps\,\inner{g}{h}_n + o(\eps),

so, if ⟨g,h⟩n<0\inner{g}{h}_n < 0, hh is a descent direction: a sufficiently small step in that direction reduces empirical risk. Mason and coauthors choose hh by directly maximizing −⟨g,h⟩n-\inner{g}{h}_n (with hh normalized); Friedman uses least squares. For trees, the two ideas are essentially equivalent, as we can prove.

Proof

With the partition fixed, VV is a subspace of Rn\R^n (through the values on the data), spanned by the mutually orthogonal leaf indicators. The least-squares fit is the orthogonal projection of rr onto VV, and in that basis it is computed leaf by leaf: minimizing ∑xi∈Rj(ri−cj)2\sum_{\vb{x}_i \in R_j}(r_i - c_j)^2 gives cj=rˉjc_j = \bar{r}_j. As an orthogonal projection, residual r−hr - h is orthogonal to VV and in particular to hh: ⟨r−h,h⟩n=0\inner{r - h}{h}_n = 0. Thus ⟨g,h⟩n=−⟨r,h⟩n=−⟨h,h⟩n−⟨r−h,h⟩n=−∥h∥n2\inner{g}{h}_n = -\inner{r}{h}_n = -\inner{h}{h}_n - \inner{r - h}{h}_n = -\norm{h}_n^2. And cos⁡∠(r,h)=⟨r,h⟩n/(∥r∥n∥h∥n)=∥h∥n/∥r∥n\cos\angle(r, h) = \inner{r}{h}_n / (\norm{r}_n\norm{h}_n) = \norm{h}_n / \norm{r}_n.

∎

The theorem holds for any partition, but the regression tree is not given one: it searches for it. Greedy search for the best split picks at each node the split that reduces the sum of squares most, which maximizes ∥h∥n2\norm{h}_n^2. The tree is therefore a greedy search for the direction in VV (with JJ leaves) most aligned with the negative gradient. The first interactive’s reading “fraction of ∥r∥2\norm{\vb{r}}^2 captured by hm+1h_{m+1}” is exactly that cos⁡2\cos^2.

Friedman’s algorithm

With the negative gradient as each tree’s target, the algorithm has four pieces. The first has its own name.

Two details distinguish this algorithm from naive gradient descent.

The tree only decides the partition. The least-squares tree’s predictions (means rˉj\bar{r}_j) are discarded: each leaf receives γjm\gamma_{jm} minimizing the actual loss. A tree with JJ leaves is a combination of JJ basis functions, indicators 1[x∈Rjm]\ind[\vb{x} \in R_{jm}], and instead of a single line search along hmh_m there are JJ searches, one per coefficient. Friedman calls this variant TreeBoost. With squared loss the two coincide; with absolute loss, as you will see, they differ greatly.

The step is shrunk. Factor ν\nu (shrinkage) multiplies each tree’s contribution. With ν=1\nu = 1 the optimal step is taken; with ν=0.1\nu = 0.1, a tenth of it. It looks wasteful and is, alongside the number of trees, the decision with the greatest effect on model quality; we study it in its own section.

InteractiveGradient boosting in 1D
Data, FmF_m and the next step Fm+1=Fm+ν hm+1F_{m+1} = F_m + \nu\, h_{m+1}
Pseudo-residuals ri=yi−Fm(xi)r_i = y_i - F_m(x_i) and tree hm+1h_{m+1} fitted to them (4 leaves)
Mean squared error versus mm (log scale on 1+m1 + m)
σ² = 0.1225
  • training data
  • truth f(x)=sin⁡2πx+0.6xf(x) = \sin 2\pi x + 0.6x
  • FmF_m (and dashed Fm+1F_{m+1})
  • pseudo-residual rir_i
  • tree hm+1h_{m+1} (area: νhm+1\nu h_{m+1})
  • training MSE
  • validation MSE (circle: minimum)
Learning rate ν\nu
Tree depth
m = 0
Iteration mm0
Training MSE of FmF_m0.6424
Validation MSE of FmF_m0.4328
Validation minimum0.1477 at m = 16
Fraction of ∥r∥2\lVert \vb{r} \rVert^2 captured by hm+1h_{m+1}79.8 %
F0F_0 is the mean of yiy_i: the best constant for squared loss. Arrows show the pseudo-residuals seen by the first tree.
Explicit model: x∼Unif⁡[0,1]x \sim \Unif[0, 1], y=f(x)+0.35 εy = f(x) + 0.35\,\eps with f(x)=sin⁡2πx+0.6xf(x) = \sin 2\pi x + 0.6x and ε∼N(0,1)\eps \sim \Normal(0, 1); 50 training and 400 validation points generated with a fixed seed, squared loss. At step mm, red arrows are pseudo-residuals (here, residuals) of FmF_m; below, the tree hm+1h_{m+1} fitted to them and, shaded, the step νhm+1\nu h_{m+1} added; the dashed orange curve is Fm+1F_{m+1}. The third panel shows training and validation mean squared error against mm, with noise variance σ2=0.1225\sigma^2 = 0.1225 as the floor. Everything runs in your browser with the same algorithm as the cell below.

Play the animation with default values (ν=0.1\nu = 0.1, depth-2 trees, i.e., 4 leaves). Each tree is a crude step function, but the sum of many small steps draws a smooth curve following ff. Notice three things:

  • Residuals shrink and become noise. Initially arrows are long and coherent (a whole region above FmF_m, another below) and the tree captures a large fraction of ∥r∥2\norm{\vb{r}}^2. Near the end arrows are short, change sign from one point to the next, and the tree captures only a small percentage: no structure remains, only noise.
  • Training error always falls; validation error does not. It bottoms out and then rises slowly. We revisit this in early stopping.
  • Learning rate changes the path. With ν=1\nu = 1 and depth 2 the validation minimum occurs at the first iteration and is substantially greater than with ν=0.1\nu = 0.1 (0.200 versus 0.148, at m=16m = 16): from the second tree, each full step fits both the remaining signal and noise in its region at once, and validation worsens. With one-tenth steps each tree corrects little, and subsequent trees can undo the previous one’s overfit.

Specific losses

Changing the loss changes three things: the initial constant, pseudo-residuals, and optimal leaf value. The following five cover almost everything you will need. We write u=y−Fu = y - F for the residual; you saw regression losses and their gradients in lesson 1.

Loss ℓ(y,F)\ell(y, F)Pseudo-residual rir_iF0F_0Leaf value γj\gamma_j
Squared, 12u2\tfrac12 u^2uiu_imean of yymean of leaf’s uiu_i
Absolute, ∣u∣\abs{u}sign⁡(ui)\operatorname{sign}(u_i)median of yymedian of leaf’s uiu_i
Huber with threshold δ\deltauiu_i if ∣ui∣≤δ\abs{u_i} \le \delta; otherwise δsign⁡(ui)\delta\operatorname{sign}(u_i)median of yyone step from median (below)
Quantile (pinball) τ\tauτ\tau if ui≥0u_i \ge 0; τ−1\tau - 1 otherwiseτ\tau quantile of yyτ\tau quantile of leaf’s uiu_i
Binomial devianceyi−piy_i - p_ilog⁡yˉ1−yˉ\log\frac{\bar y}{1 - \bar y}∑ri/∑pi(1−pi)\sum r_i / \sum p_i(1 - p_i) (Newton)

Squared: the familiar residuals

With ℓ=12(y−F)2\ell = \tfrac12(y - F)^2, ∂ℓ/∂F=−(y−F)\partial\ell/\partial F = -(y - F) and the pseudo-residual is the residual. A leaf’s optimal value minimizes ∑i∈Rj(ui−γ)2\sum_{i \in R_j}(u_i - \gamma)^2, whose solution is the mean of uiu_i: exactly what the tree already sets. Thus step 2.3 does nothing and the algorithm reduces to “fit a tree to residuals, add it shrunk, repeat”. Friedman calls it LS_Boost. You will prove it in the first guided exercise.

Absolute: signs for the tree, medians for the leaves

With ℓ=∣y−F∣\ell = \abs{y - F}, the derivative with respect to FF is −sign⁡(y−F)-\operatorname{sign}(y - F) away from u=0u = 0; at u=0u = 0 the loss is nondifferentiable and any value in [−1,1][-1, 1] is a subgradient. We take sign⁡(0)=0\operatorname{sign}(0) = 0. The pseudo-residual is therefore a sign: the tree sees only whether each point lies above or below the model, never by how far. An outlier ten units above weighs as much as a point a tenth above. This is the source of robustness.

The leaf value, however, is computed from actual residuals: minimizing ∑i∈Rj∣ui−γ∣\sum_{i \in R_j}\abs{u_i - \gamma} gives the median of the leaf’s uiu_i. (If the leaf has an even number of points, any value between the two middle ones is optimal; scikit-learn takes the lower one.) The mean of signs, what the tree would predict, is a unitless number in [−1,1][-1, 1]: adding it to the model would be a scale error.

Huber: the best of both

Huber loss is quadratic for small residuals and linear for large ones:

ℓδ(u)={12u2,∣u∣≤δ,δ(∣u∣−δ2),∣u∣>δ,ri={ui,∣ui∣≤δ,δsign⁡(ui),∣ui∣>δ.\ell_\delta(u) = \begin{cases} \tfrac12 u^2, & \abs{u} \le \delta, \\ \delta\big(\abs{u} - \tfrac{\delta}{2}\big), & \abs{u} > \delta, \end{cases} \qquad r_i = \begin{cases} u_i, & \abs{u_i} \le \delta, \\ \delta\operatorname{sign}(u_i), & \abs{u_i} > \delta. \end{cases}

Pseudo-residuals are residuals clipped to [−δ,δ][-\delta, \delta]. Which δ\delta? Friedman proposes recomputing it at every stage as the α\alpha quantile of ∣yi−Fm−1(xi)∣\abs{y_i - F_{m-1}(\vb{x}_i)}, so α\alpha sets the fraction of points treated as “normal”; in his 2002 study he uses α=0.9\alpha = 0.9, also scikit-learn’s default. The optimal leaf value has no closed form (it is a Huber M-estimator), and Friedman approximates it with one step of Huber’s iterative procedure starting at the median u~j\tilde{u}_j of the leaf’s residuals:

γj=u~j+1Nj∑i∈Rjsign⁡(ui−u~j) min⁡(δ,∣ui−u~j∣),\gamma_j = \tilde{u}_j + \frac{1}{N_j}\sum_{i \in R_j} \operatorname{sign}(u_i - \tilde{u}_j)\,\min\big(\delta, \abs{u_i - \tilde{u}_j}\big),

where NjN_j is the number of points in the leaf. It is the median corrected by the mean of clipped deviations. You will implement it in the coding exercise.

Quantile: a fit leaving a fraction τ below

Pinball loss ρτ(u)=u (τ−1[u<0])\rho_\tau(u) = u\,(\tau - \ind[u < 0]) has as its population minimizer the τ\tau quantile of yy given x\vb{x}. Its negative gradient takes only two values, τ\tau if the point is above the model and τ−1\tau - 1 if below. With τ=0.9\tau = 0.9, each point above pushes upward with force 0.90.9 and each below pushes downward with force 0.10.1: equilibrium occurs when 90% of points lie below. The optimal leaf value is the τ\tau quantile of leaf residuals. It is the standard tool for prediction intervals and probabilistic quantile forecasting.

InteractiveWhat the tree sees with each loss
Data (hollow: contaminated), FmF_m with L2 loss
What tree m+1m + 1 receives: pseudo-residuals rir_i (red) versus residuals yi−Fm(xi)y_i - F_m(x_i) (gray)
  • data point (hollow: contaminated)
  • truth ff
  • population target f+cf + c
  • FmF_m
  • residual yi−Fm(xi)y_i - F_m(x_i)
  • pseudo-residual rir_i
  • mean rir_i in leaf (tree)
  • optimal leaf value γ\gamma
Loss
40
Mean training loss0.3031
Points below FmF_m58 of 80 (73 %)
Mean shift Fm−f‾\overline{F_m - f}0.266
Population shift cc0.390
With L2 the pseudo-residual is the entire residual: outliers contribute arrows of 3 or 4 units and the tree chases them. FmF_m targets the conditional mean, shifted upward by contamination.
Explicit model: 80 points with x∼Unif⁡[0,1]x \sim \Unif[0, 1] and y=f(x)+0.25 εy = f(x) + 0.25\,\eps, each contaminated with probability 0.120.12 by adding 2.5+1.5 U2.5 + 1.5\,U with U∼Unif⁡[0,1]U \sim \Unif[0, 1] (hollow; in this fixed-seed sample, 9 of 80). Gradient boosting with ν=0.1\nu = 0.1 and depth-2 trees; with Huber you can choose quantile α\alpha setting δm\delta_m. Above, FmF_m against truth ff and the loss's population target, f+cf + c, with cc calculated exactly for this noise (mean, median or τ\tau quantile of the mixture). Below, what the next tree receives: pseudo-residuals (red) against raw residuals (gray), the chosen partition and, in each leaf, mean pseudo-residual (tree prediction) against optimal value γ\gamma actually added.

Start with L2 at m=40m = 40: outliers produce pseudo-residuals of two to four units, the tree isolates their regions and FmF_m rises toward them in steps. Switch to L1 without changing mm: the lower panel becomes a row of signs ±1\pm 1, mean signs in each leaf (aqua) stay in [−1,1][-1, 1] and the added value (amber) is the residual median, in units of yy. FmF_m hugs ff (mean offset −0.02-0.02 versus +0.27+0.27 with L2).

Huber has a trap visible in the interactive. With α=0.9\alpha = 0.9, threshold δm\delta_m is the 0.9 quantile of absolute residuals, but 11% of points (9 of 80) here are contaminated: the threshold falls among outliers. At m=40m = 40 it is δm=1.14\delta_m = 1.14, four or five times the normal noise deviation, and an outlier clipped at 1.141.14 still pushes as hard as four or five normal residuals; FmF_m lies halfway (+0.12+0.12). Lower α\alpha to 0.850.85: δm\delta_m falls to 0.490.49, all 9 contaminated points are clipped and FmF_m returns to ff (+0.01+0.01). As a practical rule 1−α1 - \alpha must exceed the expected outlier fraction: α\alpha sets the procedure’s breakdown point. Finally, with quantile loss, raise τ\tau and watch “points below FmF_m”: after enough iterations it approaches τ\tau.

Continue with Huber and α=0.85\alpha = 0.85 and take mm beyond 40: narrow peaks appear over some outliers. Once normal points are well fitted, their pseudo-residuals are nearly zero and an outlier’s +δm+\delta_m stands out; the tree isolates it in a leaf of one or two points, whose value starts at the median of its residuals, the outlier’s entire residual. This does not happen with L1: an outlier’s pseudo-residual is +1+1, the same as any normal point above, and it does not stand out. Loss robustness does not replace min_samples_leaf or early stopping.

What does each loss estimate? Each targets a different functional of the conditional distribution, here f(x)f(x) plus constant cc. With 12% contamination and mean jump 2.5+1.5/2=3.252.5 + 1.5/2 = 3.25, the conditional mean is 0.12⋅3.25=0.390.12 \cdot 3.25 = 0.39 above ff; the conditional median barely moves. There is no “correct” loss: if you care about the mean (e.g., to add predictions), L2 does its job and outliers are part of the mean.

Binomial deviance: a Newton step in each leaf

In binary classification with y∈{0,1}y \in \{0, 1\}, the model returns log-odds FF and probability p=σ(F)=1/(1+e−F)p = \sigmoid(F) = 1/(1 + e^{-F}). The loss is the negative Bernoulli log-likelihood:

ℓ(y,F)=−[ylog⁡p+(1−y)log⁡(1−p)]=log⁡(1+eF)−yF.\ell(y, F) = -\big[y\log p + (1 - y)\log(1 - p)\big] = \log(1 + e^{F}) - yF.

Differentiating, ∂ℓ/∂F=σ(F)−y=p−y\partial\ell/\partial F = \sigmoid(F) - y = p - y, so the pseudo-residual is ri=yi−pir_i = y_i - p_i: what the probability lacks to reach the label. F0F_0 is the best constant, σ(F0)=yˉ\sigmoid(F_0) = \bar y, i.e., the log-odds of prevalence.

The optimal leaf value, arg min⁡γ∑i∈Rjℓ(yi,Fi+γ)\argmin_\gamma \sum_{i \in R_j}\ell(y_i, F_i + \gamma), has no closed form. Since the second derivative is ∂2ℓ/∂F2=p(1−p)\partial^2\ell/\partial F^2 = p(1 - p), one Newton step from γ=0\gamma = 0 gives

γj=∑i∈Rj(yi−pi)∑i∈Rjpi(1−pi).\gamma_j = \frac{\sum_{i \in R_j} (y_i - p_i)}{\sum_{i \in R_j} p_i(1 - p_i)}.

You will derive this in the second guided exercise. Friedman writes the same algorithm (L2_TreeBoost) with y∈{−1,1}y \in \{-1, 1\} and FF equal to half the log-odds, and obtains γj=∑y~i/∑∣y~i∣(2−∣y~i∣)\gamma_j = \sum\tilde{y}_i / \sum\abs{\tilde{y}_i}(2 - \abs{\tilde{y}_i}); with y~i=2(yi−pi)\tilde{y}_i = 2(y_i - p_i) it is the same update on another scale. This Newton step is the seed of second-order boosting: XGBoost uses the gradient and Hessian also to choose splits, not just for leaf values, as you will see in Newton boosting.

Regularization: learning rate, number of trees and depth

Unregularized gradient boosting overfits: every new tree reduces training loss, and training loss can be driven nearly to zero. There are three main levers.

Shrinkage: small steps

Friedman measured this in his paper. In the preliminary 1999 version (table 1), with 5,000 simulated examples and 11-leaf trees, the number of iterations giving best validation error and that error (absolute error relative to the best constant) for least-squares boosting were:

ν\nu1.00.50.250.1250.060.03
Optimal MM154377146326855
relative error0.480.400.340.320.320.32

Two regularities stand out. First, ν\nu and MM compensate: whenever ν\nu is halved, optimal MM increases by a factor between 1.8 and 2.9, and overall, from ν=0.25\nu = 0.25 to ν=0.03\nu = 0.03 (8.3 times smaller), MM goes from 77 to 855 (11 times greater). Second, small ν\nu wins, with diminishing returns below 0.1250.125. Friedman’s practical recommendation follows: set MM as large as computation allows and tune ν\nu so the validation minimum is near that MM.

Why do small steps win? An explanation that can be made precise comes from linear regression. If base learners are the variables themselves and steps infinitesimal, squared-loss boosting (incremental forward stagewise) follows a coefficient path that, under conditions such as monotone coefficients, matches the lasso regularization path (Efron, Hastie, Johnstone and Tibshirani, 2004). The connection to νM\nu M is direct: each step of size ν\nu changes one coefficient by ν\nu, so after MM steps the coefficient ℓ1\ell_1 norm is at most νM\nu M, with equality for monotone paths. The product νM\nu M acts as the lasso’s tt budget in its constrained form, ∥w∥1≤t\norm{\vb{w}}_1 \le t: moving slowly traces a family of progressively less regularized models and allows stopping at the right point. With ν=1\nu = 1 each step skips a large stretch of that path and, above all, each tree fits both signal and noise in its region at once.

Depth is interaction order

A depth-dd tree is a function depending on at most dd variables along each path from root to leaf. Thus a model of depth-1 trees (stumps) is additive, F(x)=∑kgk(xk)F(\vb{x}) = \sum_k g_k(x_k): it sums single-variable functions and cannot represent interactions. At depth 2 products of indicators of two variables appear, and generally depth bounds the interaction order the model can capture. The classic recommendation is small trees: in Friedman’s 2002 study with 500 examples, the optimal size averaged over 100 target functions was 6 leaves.

The third interactive uses scikit-learn’s Friedman 1 problem, y=10sin⁡(πx1x2)+20(x3−0.5)2+10x4+5x5+εy = 10\sin(\pi x_1 x_2) + 20(x_3 - 0.5)^2 + 10x_4 + 5x_5 + \eps, with 10 uniform variables (the last 5 have no effect) and noise N(0,1)\Normal(0, 1). There is only one interaction, between x1x_1 and x2x_2 inside the sine. Stumps cannot see it and pay for it: their best validation error is 3.125 versus 2.51 at depth 2 or 3. More depth does not help either: at depth 5 without subsampling, the best is 3.07, because 32-leaf trees on 500 points fit noise at every step.

Besides depth, min_samples_leaf prevents leaves with too few points: with few data per leaf, value γj\gamma_j is very noisy (a median of two points, a Newton step with nearly zero ∑p(1−p)\sum p(1 - p)), and limiting it is cheap regularization.

InteractiveLearning rate, trees and depth
Validation MSE over grid (ν,M)(\nu, M); depth 3, subsampling 1. Circles: M⋆M^\star for each row; lines: νM\nu M constant
νM=10νM=30νM=100νM=30010.50.20.10.050.020.01ν1101001000M (árboles)
ECM de validación respecto al mínimo del panel (2.510):mínimo+5 %+10 %+25 %+50 %≥ ×2
Curves for row ν=0.1\nu = 0.1: error versus MM
ruido σ² = 1
  • training (500)
  • validation (2000); circle: M⋆M^\star
  • test (2000)
  • chosen MM
Tree depth
Row subsampling
0.1
469
Validation MSE at (ν,M)(\nu, M)2.656
M⋆M^\star (validation minimum) and νM⋆\nu M^\star460 and 46
First MM within 2% of minimum, and νM\nu M244 and 24
Validation MSE at M⋆M^\star2.654
Test MSE at M⋆M^\star (honest)2.661
Test minimum (chosen by inspecting test)2.660 at M = 717
You are within 2% of this row’s validation minimum. Note νM=47\nu M = 47 and compare it with other good rows.
Actual output of GradientBoostingRegressor (scikit-learn 1.8.0 in Pyodide, the same environment that runs the cells) on Friedman 1 with 500 training, 2,000 validation and 2,000 test points, squared loss and up to 3,000 trees, for ν∈{1,0.5,0.2,0.1,0.05,0.02,0.01}\nu \in \{1, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01\}, depths 1, 2, 3 and 5, and subsampling 1 or 0.5. Above, validation mean squared error for each (ν,M)(\nu, M), colored relative to the panel's best value (stronger means closer to the minimum); circles mark each row's M⋆M^\star and dashed lines join points with constant νM\nu M. Below are the selected row's curves on a log scale. Code is in the implementation section and a cell recomputes one row.

At depth 3 without subsampling, the intense region starts at a diagonal boundary: each row reaches good models at MM following constant νM≈\nu M \approx and from then on, with small ν\nu, stays on a long plateau; with ν=0.5\nu = 0.5 or 11 the row never intensifies. The reading “first MM within 2% of minimum” quantifies this better than exact M⋆M^\star, because the minimum is very flat and its exact position varies: for ν=0.2,0.1,0.05,0.02\nu = 0.2, 0.1, 0.05, 0.02 and 0.010.01, that MM is 107, 244, 423, 1230 and 1818, and νM\nu M is 21, 24, 21, 25 and 18: dividing ν\nu by 20 multiplies the number of trees needed by 17. Rows ν=1\nu = 1 and 0.50.5 never reach the band: their best validation errors are 6.80 and 4.09 versus 2.51 for the best row. With stumps the band lies at νM≈25\nu M \approx 25 to 28 and at depth 5 around 10: the more powerful each tree, the less total travel is needed.

Early stopping

In the curve below, training error falls continuously while validation error bottoms out and, for large ν\nu, rises. The number of trees is the most frequently tuned hyperparameter and the cheapest to tune, because one training run gives a model at any MM: simply evaluate partial predictions F1,F2,…F_1, F_2, \dots

The fact that training error does not rise is a fact, not merely an observation, at least for losses where γj\gamma_j is the exact minimizer. If ℓ\ell is convex in FF and γj\gamma_j minimizes leaf loss, then for ν∈[0,1]\nu \in [0, 1], by convexity,

∑i∈Rjℓ(yi,Fi+νγj)≤(1−ν)∑i∈Rjℓ(yi,Fi)+ν∑i∈Rjℓ(yi,Fi+γj)≤∑i∈Rjℓ(yi,Fi),\sum_{i \in R_j}\ell(y_i, F_i + \nu\gamma_j) \le (1 - \nu)\sum_{i \in R_j}\ell(y_i, F_i) + \nu\sum_{i \in R_j}\ell(y_i, F_i + \gamma_j) \le \sum_{i \in R_j}\ell(y_i, F_i),

where the final inequality uses γ=0\gamma = 0 as a candidate. Summing over leaves gives R^(Fm)≤R^(Fm−1)\hat{R}(F_m) \le \hat{R}(F_{m-1}). This holds for squared, absolute and pinball losses. For Huber and deviance, γj\gamma_j is an approximation (one Huber or Newton step) and monotonicity is not guaranteed in general, though in practice it almost always holds (we check it in the deviance cell below). Training error therefore cannot choose MM: it always asks for more trees. An error the algorithm has not seen is needed, as in any training, validation and test split.

Stochastic gradient boosting

In 2002 Friedman added a one-line modification with large effects: in each iteration, fit the tree (and calculate its leaf values) on a random subsample of the data.

The effects described by Friedman (2002), with his numbers:

  • Computation. Each tree is fitted on a fraction ff of the data, so cost per iteration falls by approximately that factor.
  • Accuracy. Across 100 simulated target functions with 500 examples and Gaussian noise, the best average fraction was f≈0.4f \approx 0.4, with a typical 11% improvement in absolute error (22% on squared scale) versus no subsampling, and even f=0.2f = 0.2 or 0.30.3 improved substantially, with 5× and 3× speedups. With 5,000 examples the best fraction was closer to 0.60.6 and the improvement smaller (1–11%, median 5%). In classification subsampling helped on average, but less universally than in regression.
  • Robustness to large trees. Subsampling moderates overfitting by high-capacity trees: with 500 examples and f=0.5f = 0.5, deterioration (median relative error) when going from 6 to 41 leaves was one-third that of the deterministic algorithm.

Why does it work? Friedman attributes it to variance reduction, using the same argument as bagging. Each tree is estimated with less data, so its variance rises; but trees from different iterations are estimated from different subsamples and less correlated, and the final model, a sum of many trees, averages out that variability. Recall the variance of an average of correlated predictors: with BB predictors of variance σ2\sigma^2 and correlation ρ\rho, the average has variance ρσ2+(1−ρ)σ2/B\rho\sigma^2 + (1 - \rho)\sigma^2/B, and lowering ρ\rho more than compensates for raising σ2\sigma^2 when BB is large. Using f=1/2f = 1/2 without replacement resembles drawing bootstrap samples, which contain on average 1−1/e≈631 - 1/e \approx 63% distinct points; Friedman describes the result as a hybrid of boosting and bagging.

In the interactive, switch to subsampling 0.5 at depth 3. With ν≤0.1\nu \le 0.1 validation error falls clearly (2.51 to 2.03 in the best row; test error at M⋆M^\star, 2.61 to 2.14). With ν=1\nu = 1 it worsens greatly: a tree estimated with half the data and added at full size is pure noise. And at depth 5, where the deterministic algorithm overfits (best validation 3.07, worse than depth 3), subsampling recovers much of it (2.31): Friedman’s robustness to capacity.

Implementation from scratch

The plan: a least-squares CART regression tree (a compact version of the one you built for the decision tree), a generic GBM receiving a loss object with three methods, init, negative_gradient and update_leaf, and five losses. To compare with scikit-learn to the last decimal we must imitate three conventions: trees process inputs as float32, each split threshold is the midpoint between consecutive values, and the first split wins ties.

[ ]The tree and boosting from scratchBrowser
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor

EPS = np.finfo(float).eps

class RegressionTree:
    """Árbol de regresión CART por mínimos cuadrados (versión compacta del de la lección 14)."""

    def __init__(self, max_depth=3, min_samples_leaf=1):
        self.max_depth, self.min_samples_leaf = max_depth, min_samples_leaf

    def fit(self, X, r):
        self.feature, self.threshold, self.left, self.right, self.value = [], [], [], [], []
        self._grow(X, r, np.arange(len(r)), 0)
        for name in ("feature", "threshold", "left", "right", "value"):
            setattr(self, name, np.array(getattr(self, name), dtype=float if name in ("threshold", "value") else int))
        return self

    def _grow(self, X, r, idx, depth):
        node = len(self.value)
        self.feature.append(-1); self.threshold.append(0.0)
        self.left.append(-1); self.right.append(-1); self.value.append(r[idx].mean())
        n, msl = len(idx), self.min_samples_leaf
        impureza = np.mean(r[idx] ** 2) - np.mean(r[idx]) ** 2
        if depth >= self.max_depth or n < max(2, 2 * msl) or impureza <= EPS:
            return node
        split = self._best_split(X, r, idx)
        if split is None:
            return node
        j, thr = split
        izq = X[idx, j] <= thr
        self.feature[node], self.threshold[node] = j, thr
        self.left[node] = self._grow(X, r, idx[izq], depth + 1)
        self.right[node] = self._grow(X, r, idx[~izq], depth + 1)
        return node

    def _best_split(self, X, r, idx):
        n, msl = len(idx), self.min_samples_leaf
        nl = np.arange(1, n, dtype=float)
        nr = n - nl
        best_gain, best = -np.inf, None
        for j in range(X.shape[1]):
            orden = idx[np.argsort(X[idx, j], kind="stable")]
            xs, rs = X[orden, j], r[orden]
            Sl = np.cumsum(rs)[:-1]
            Sr = rs.sum() - Sl
            # (n_R S_L - n_L S_R)^2 / (n_L n_R) = n_L n_R (media_L - media_R)^2: ordena igual que la caída del SSE
            gain = (nr * Sl - nl * Sr) ** 2 / (nl * nr)
            ok = (xs[1:] > xs[:-1] + 1e-7) & (nl >= msl) & (nr >= msl)
            if not ok.any():
                continue
            gain = np.where(ok, gain, -np.inf)
            k = int(np.argmax(gain))                      # primer máximo en caso de empate
            if gain[k] > best_gain:
                best_gain, best = gain[k], (j, xs[k] / 2 + xs[k + 1] / 2)
        return best

    def apply(self, X):
        """Índice de la hoja de cada fila."""
        node = np.zeros(len(X), dtype=int)
        for _ in range(self.max_depth):
            dentro = self.feature[node] >= 0
            if not dentro.any():
                break
            nd = node[dentro]
            izq = X[dentro, self.feature[nd]] <= self.threshold[nd]
            node[dentro] = np.where(izq, self.left[nd], self.right[nd])
        return node

    def predict(self, X):
        return self.value[self.apply(X)]


class GBM:
    """Gradient boosting de Friedman para cualquier pérdida con init, negative_gradient y update_leaf."""

    def __init__(self, loss, n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_leaf=1):
        self.loss, self.M, self.nu = loss, n_estimators, learning_rate
        self.max_depth, self.min_samples_leaf = max_depth, min_samples_leaf

    def fit(self, X, y):
        self.F0 = self.loss.init(y)                                   # paso 1: la mejor constante
        F = np.full(len(y), self.F0, dtype=float)
        self.trees = []
        for m in range(self.M):
            r = self.loss.negative_gradient(y, F)                     # paso 2.1: pseudo-residuos
            tree = RegressionTree(self.max_depth, self.min_samples_leaf).fit(X, r)   # 2.2: árbol por mínimos cuadrados
            hoja = tree.apply(X)
            for t in np.unique(hoja):                                 # 2.3: valor óptimo de cada hoja
                s = hoja == t
                tree.value[t] = self.loss.update_leaf(y[s], F[s], r[s])
            F += self.nu * tree.value[hoja]                           # 2.4: paso con shrinkage
            self.trees.append(tree)
        return self

    def decision_function(self, X):
        return self.F0 + self.nu * sum(t.predict(X) for t in self.trees)

    predict = decision_function


class SquaredLoss:
    def init(self, y):
        return y.mean()

    def negative_gradient(self, y, F):
        return y - F

    def update_leaf(self, y, F, r):
        return r.mean()


# Datos: x ~ U[0, 1], y = f(x) + 0.25 eps, y un 12 % de puntos contaminados con +2.5 + 1.5 U (la ley del interactivo).
# Las x se redondean a float32, la precisión con la que trabajan los árboles de scikit-learn.
f = lambda x: np.sin(2 * np.pi * x) + 0.6 * x
rng = np.random.default_rng(0)

def contaminated(n):
    x = rng.uniform(0, 1, n).astype(np.float32).astype(float)
    y = f(x) + 0.25 * rng.standard_normal(n)
    out = rng.uniform(size=n) < 0.12
    y[out] += 2.5 + 1.5 * rng.uniform(size=out.sum())
    return x.reshape(-1, 1), y, out

X, y, out = contaminated(200)
Xg = np.linspace(0, 1, 501, dtype=np.float32).astype(float).reshape(-1, 1)

mio = GBM(SquaredLoss(), n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_leaf=5).fit(X, y)
sk = GradientBoostingRegressor(loss="squared_error", n_estimators=100, learning_rate=0.1,
                               max_depth=3, min_samples_leaf=5, random_state=0).fit(X, y)
print(f"outliers: {out.sum()} de {len(y)}")
print(f"F0 = {mio.F0:.4f}   (scikit-learn: {sk.init_.constant_.ravel()[0]:.4f})")
print(f"máx |F_mio - F_sklearn| en 501 puntos: {np.max(np.abs(mio.predict(Xg) - sk.predict(Xg))):.1e}")

The maximum difference is on the order of 10−1510^{-15}: all 100 trees are identical, split by split, and all that remains is rounding from summing in a different order. The gain _best_split uses is scikit-learn’s (its friedman_mse criterion): (nRSL−nLSR)2/(nLnR)=nLnR(rˉL−rˉR)2(n_R S_L - n_L S_R)^2/(n_L n_R) = n_L n_R(\bar r_L - \bar r_R)^2, which is nn times the reduction in sum of squares nLnRn(rˉL−rˉR)2\frac{n_L n_R}{n}(\bar r_L - \bar r_R)^2 and thus chooses the same splits.

Now the other losses. For absolute and quantile we use the “inverted_cdf” quantile (the smallest value vv with F^n(v)≥τ\hat F_n(v) \ge \tau), scikit-learn’s convention for leaf values; with an even number of points, the “median” is the lower of the two central values.

[ ]Four regression losses versus scikit-learnBrowser
from scipy.optimize import brentq
from scipy.stats import norm
import matplotlib.pyplot as plt

def q_low(v, q):
    """Cuantil «inverted_cdf»: el menor valor con F_n >= q (la mediana inferior si q = 0.5)."""
    return np.quantile(v, q, method="inverted_cdf")

class AbsoluteLoss:
    def init(self, y):
        return np.median(y)

    def negative_gradient(self, y, F):
        return np.sign(y - F)

    def update_leaf(self, y, F, r):
        return q_low(y - F, 0.5)           # la mediana de los residuos, no la media de los signos

class QuantileLoss:
    def __init__(self, tau):
        self.tau = tau

    def init(self, y):
        return np.percentile(y, 100 * self.tau)

    def negative_gradient(self, y, F):
        return np.where(y >= F, self.tau, self.tau - 1.0)

    def update_leaf(self, y, F, r):
        return q_low(y - F, self.tau)

class HuberLossRef:
    """Versión de referencia; en el ejercicio de código la escribes tú."""
    def __init__(self, alpha=0.9):
        self.alpha = alpha

    def init(self, y):
        return np.median(y)

    def negative_gradient(self, y, F):
        d = y - F
        self.delta = q_low(np.abs(d), self.alpha)
        return np.where(np.abs(d) <= self.delta, d, self.delta * np.sign(d))

    def update_leaf(self, y, F, r):
        d = y - F
        med = q_low(d, 0.5)
        return med + np.mean(np.sign(d - med) * np.minimum(self.delta, np.abs(d - med)))

# objetivo poblacional de cada pérdida para este ruido: f(x) + c
u = (np.arange(4000) + 0.5) / 4000
cdf = lambda c: 0.88 * norm.cdf(c / 0.25) + 0.12 * norm.cdf((c - 2.5 - 1.5 * u) / 0.25).mean()
c_q = lambda tau: brentq(lambda c: cdf(c) - tau, -3, 6)
objetivo = {"L2": 0.12 * 3.25, "L1": c_q(0.5), "Huber": np.nan, "cuantil 0.75": c_q(0.75)}

casos = [("L2", SquaredLoss(), dict(loss="squared_error")),
         ("L1", AbsoluteLoss(), dict(loss="absolute_error")),
         ("Huber", HuberLossRef(0.9), dict(loss="huber", alpha=0.9)),
         ("cuantil 0.75", QuantileLoss(0.75), dict(loss="quantile", alpha=0.75))]
fg = f(Xg.ravel())
print(f"{'pérdida':13s} {'máx dif. con sklearn':>21s} {'media de F - f':>15s} {'c poblacional':>14s} {'por debajo':>11s}")
ajustes = {}
for nombre, loss, kw in casos:
    mio = GBM(loss, 100, 0.1, 3, min_samples_leaf=5).fit(X, y)
    sk = GradientBoostingRegressor(n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_leaf=5,
                                   random_state=0, **kw).fit(X, y)
    Fg = mio.predict(Xg)
    ajustes[nombre] = Fg
    debajo = np.mean(y < mio.predict(X))
    print(f"{nombre:13s} {np.max(np.abs(Fg - sk.predict(Xg))):21.1e} {np.mean(Fg - fg):15.3f} "
          f"{objetivo[nombre]:14.3f} {debajo:11.1%}")

plt.figure(figsize=(7, 3.6))
plt.scatter(X[~out, 0], y[~out], s=10, color="C0", label="datos")
plt.scatter(X[out, 0], y[out], s=18, facecolors="none", edgecolors="C0", label="contaminados")
plt.plot(Xg[:, 0], fg, "k--", lw=1, label="f")
for nombre, Fg in ajustes.items():
    plt.plot(Xg[:, 0], Fg, lw=1.6, label=nombre)
plt.legend(ncol=3, fontsize=8); plt.ylim(-1.6, 4.6); plt.show()

All four match scikit-learn up to rounding. The other columns say what each estimates. L2 shifts 0.2110.211 above ff, less than the population 0.3900.390: this sample has only 13 contaminated out of 200 (6.5%, not 12%), and 0.065⋅3.25≈0.210.065 \cdot 3.25 \approx 0.21, so L2 estimates the mean of this sample well. L1 hugs ff (−0.006-0.006), leaving 48.5% of points below. Huber stays at 0.0370.037. Quantile with τ=0.75\tau = 0.75 shifts 0.2530.253, close to the population quantile (0.2620.262), with 76.5% of points below.

Finally, classification. We compare with decision_function of GradientBoostingClassifier, which returns FF as log-odds.

[ ]Binomial deviance versus GradientBoostingClassifierBrowser
from sklearn.ensemble import GradientBoostingClassifier

class BinomialDeviance:
    """Deviance binomial con F en log-odds: l(y, F) = log(1 + e^F) - y F, con y en {0, 1}."""
    def init(self, y):
        p = y.mean()
        return np.log(p / (1 - p))

    def negative_gradient(self, y, F):
        return y - 1 / (1 + np.exp(-F))

    def update_leaf(self, y, F, r):
        p = y - r                                   # r = y - p
        den = np.sum(p * (1 - p))
        return 0.0 if abs(den) < 1e-150 else r.sum() / den      # un paso de Newton

def deviance(y, F):
    return np.mean(np.logaddexp(0, F) - y * F)

xc = rng.uniform(0, 1, 400).astype(np.float32).astype(float).reshape(-1, 1)
pc = 1 / (1 + np.exp(-3 * np.sin(2 * np.pi * xc[:, 0])))
yc = (rng.uniform(size=400) < pc).astype(float)

mio = GBM(BinomialDeviance(), 100, 0.1, 3, min_samples_leaf=5).fit(xc, yc)
sk = GradientBoostingClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, min_samples_leaf=5,
                                random_state=0).fit(xc, yc)
print(f"F0 = {mio.F0:.4f} = log-odds de la prevalencia {yc.mean():.3f}")
print(f"máx |F_mio - decision_function| en 501 puntos: {np.max(np.abs(mio.predict(Xg) - sk.decision_function(Xg))):.1e}")

# la pérdida de entrenamiento a lo largo de las iteraciones
F = np.full(len(yc), mio.F0)
dev = [deviance(yc, F)]
for t in mio.trees:
    F = F + mio.nu * t.predict(xc)
    dev.append(deviance(yc, F))
dev = np.array(dev)
print(f"deviance de entrenamiento: {dev[0]:.4f} -> {dev[10]:.4f} (m=10) -> {dev[-1]:.4f} (m=100); "
      f"¿monótona? {bool(np.all(np.diff(dev) <= 1e-12))}")
pg = 1 / (1 + np.exp(-3 * np.sin(2 * np.pi * Xg[:, 0])))
print(f"error medio |p_hat - p| en la rejilla: {np.mean(np.abs(1 / (1 + np.exp(-mio.predict(Xg))) - pg)):.3f}")

Again identical. Training deviance falls monotonically from 0.69230.6923 (the constant’s, nearly log⁡2\log 2 because prevalence is 0.520.52) to 0.31330.3133, although the Newton step does not guarantee monotonicity in general.

The library version

scikit-learn has two families. GradientBoostingRegressor and GradientBoostingClassifier are Friedman’s algorithm as-is (what you just reproduced), with subsample, validation_fraction and n_iter_no_change. HistGradientBoostingRegressor and HistGradientBoostingClassifier discretize each variable into at most 255 bins before training and search splits over histograms, like LightGBM; they are much faster with lots of data and you will study them in LightGBM and CatBoost.

To see overfitting we need noise to overfit: a make_classification problem where 15% of labels have been replaced with random labels (flip_y). staged_decision_function obtains FmF_m on test for every mm from one training run.

[ ]Error versus iterations with staged_decision_functionBrowser
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_classification
from sklearn.ensemble import GradientBoostingClassifier

# Clasificación con un 15 % de etiquetas al azar (flip_y): hay ruido que sobreajustar.
X, y = make_classification(n_samples=3800, n_features=10, n_informative=5, n_redundant=2,
                           flip_y=0.15, class_sep=0.8, random_state=1)
Xtr, ytr, Xte, yte = X[:800], y[:800], X[800:], y[800:]

def curvas_test(modelo, X, y):
    """Deviance (log-loss) y error de test tras cada iteración, a partir de F_m en log-odds."""
    dev, err = [], []
    for F in modelo.staged_decision_function(X):
        F = F.ravel()
        dev.append(np.mean(np.logaddexp(0, F) - y * F))
        err.append(np.mean((F > 0) != y))
    return np.array(dev), np.array(err)

curvas = {}
for nu in (0.5, 0.1):
    gb = GradientBoostingClassifier(n_estimators=200, learning_rate=nu, max_depth=3, random_state=0).fit(Xtr, ytr)
    dev, err = curvas_test(gb, Xte, yte)
    curvas[nu] = (dev, err)
    print(f"nu = {nu}: deviance de test mínima {dev.min():.4f} en m = {dev.argmin() + 1}, en m = 200 {dev[-1]:.4f};"
          f"  error mínimo {err.min():.3f} en m = {err.argmin() + 1}, en m = 200 {err[-1]:.3f}")

fig, ax = plt.subplots(1, 2, figsize=(8, 3))
for nu, (dev, err) in curvas.items():
    ax[0].plot(np.arange(1, 201), dev, label=f"ν = {nu}")
    ax[1].plot(np.arange(1, 201), err, label=f"ν = {nu}")
ax[0].set_title("deviance de test"); ax[1].set_title("error de clasificación de test")
for a in ax:
    a.set_xlabel("m"); a.legend()
plt.tight_layout(); plt.show()

With ν=0.5\nu = 0.5 test deviance bottoms out at iteration 9 (0.4970) and by iteration 200 has risen to 0.8274; with ν=0.1\nu = 0.1 the minimum is better (0.4863, at 78) and subsequent deterioration much slower. But look at classification error: with ν=0.5\nu = 0.5 its minimum comes at iteration 164, long after the deviance minimum. Friedman noted this phenomenon in 2001: classification error depends only on the sign of FF, while deviance also depends on its magnitude. When overfitting, the model inflates ∣F∣\abs{F} (becomes overconfident) without spoiling the sign. If you will use probabilities (for calibration, costs or ranking), monitor deviance, not accuracy.

Now automatic early stopping. Both families set aside a fraction of training data as validation (validation_fraction, stratified in classification) and stop when validation loss has not improved for n_iter_no_change iterations. In HistGradientBoosting*, early_stopping='auto' enables it only with more than 10,000 examples; here we force it.

[ ]Early stopping: validation_fraction and n_iter_no_changeBrowser
from sklearn.ensemble import HistGradientBoostingClassifier

def deviance(modelo, X, y):
    F = modelo.decision_function(X).ravel()
    return np.mean(np.logaddexp(0, F) - y * F)

for paciencia in (10, 50):
    gb_es = GradientBoostingClassifier(n_estimators=1000, learning_rate=0.1, max_depth=3, validation_fraction=0.2,
                                       n_iter_no_change=paciencia, random_state=0).fit(Xtr, ytr)
    print(f"GradientBoostingClassifier, paciencia {paciencia}: para en {gb_es.n_estimators_} árboles; "
          f"deviance de test {deviance(gb_es, Xte, yte):.4f}")
hgb = HistGradientBoostingClassifier(max_iter=1000, learning_rate=0.1, early_stopping=True,
                                     validation_fraction=0.2, n_iter_no_change=10, random_state=0).fit(Xtr, ytr)
print(f"HistGradientBoostingClassifier: para en {hgb.n_iter_} iteraciones; deviance de test {deviance(hgb, Xte, yte):.4f}")
dev01 = curvas[0.1][0]
print(f"mínimo mirando el test (no se puede hacer en la práctica): {dev01.min():.4f} en m = {dev01.argmin() + 1}")

With patience 10, GradientBoostingClassifier stops at 64 trees and achieves test deviance 0.4889, within 0.003 of the unattainable minimum 0.4863 (which requires looking at test and also trains with all 800 points, not 640). Patience 50 allows 121 trees and improves nothing (0.4902): near the minimum the curve is nearly flat, and validation with only 160 points is too noisy to distinguish within that plateau. Patience trades computation against stopping too early; it is not fine regularization. HistGradientBoostingClassifier stops at 51 iterations with slightly worse deviance (0.5033): its default trees have up to 31 leaves, each iteration advances further and, with 640 points, overfits sooner.

Finally, subsampling. With subsample < 1, scikit-learn also computes loss on points excluded from each subsample (oob_scores_), which looks like free validation.

[ ]Subsampling: three seeds and the out-of-bag estimateBrowser
mins = []
for seed in range(3):
    gs = GradientBoostingClassifier(n_estimators=200, learning_rate=0.1, max_depth=3, subsample=0.5,
                                    random_state=seed).fit(Xtr, ytr)
    dev_s, _ = curvas_test(gs, Xte, yte)
    mins.append(dev_s.min())
    if seed == 0:
        m_oob = int(np.argmin(gs.oob_scores_)) + 1
        print(f"semilla 0: mínimo de test en m = {dev_s.argmin() + 1}; el OOB elige m = {m_oob}, "
              f"con deviance de test {dev_s[m_oob - 1]:.4f}")
print(f"subsample = 0.5: deviance de test mínima por semilla {np.round(mins, 4)}, media {np.mean(mins):.4f}")
print(f"subsample = 1:   deviance de test mínima {dev01.min():.4f}")

On this problem subsampling improves minimum deviance in all three seeds (mean 0.4717 versus 0.4863), consistent with Friedman’s small-sample findings. The out-of-bag estimate instead chooses M=198M = 198 when the test minimum is at 68, paying for it (0.4997). The reason is structural: oob_scores_[m] is the loss of FmF_m on points not used by tree mm, but each point entered approximately half the previous trees, so FmF_m has already seen them and their loss does not reflect overfitting. To choose MM, use a real validation set.

The grid data

The third interactive comes from this code, run outside the lesson with the same Pyodide as the cells (it takes about four minutes, too long for a cell):

import json
import numpy as np
from sklearn.datasets import make_friedman1
from sklearn.ensemble import GradientBoostingRegressor

X, y = make_friedman1(n_samples=4500, noise=1.0, random_state=0)
Xtr, ytr, Xva, yva, Xte, yte = X[:500], y[:500], X[500:2500], y[500:2500], X[2500:], y[2500:]
NUS, DEPTHS, SUBS, MMAX = [1.0, 0.5, 0.2, 0.1, 0.05, 0.02, 0.01], [1, 2, 3, 5], [1.0, 0.5], 3000
grid = np.unique(np.round(np.geomspace(1, MMAX, 70)).astype(int))     # M guardados, en escala logarítmica

def staged_mse(model, X, y):
    return np.array([np.mean((y - p) ** 2) for p in model.staged_predict(X)])

runs = []
for sub in SUBS:
    for d in DEPTHS:
        for nu in NUS:
            gb = GradientBoostingRegressor(n_estimators=MMAX, learning_rate=nu, max_depth=d,
                                           subsample=sub, random_state=0).fit(Xtr, ytr)
            tr, va, te = staged_mse(gb, Xtr, ytr), staged_mse(gb, Xva, yva), staged_mse(gb, Xte, yte)
            k, kt = int(np.argmin(va)), int(np.argmin(te))
            k2 = int(np.argmax(va <= 1.02 * va[k]))            # primer M a menos del 2 % del mínimo
            runs.append({"sub": sub, "depth": d, "nu": nu, "train": tr[grid - 1].round(4).tolist(),
                         "val": va[grid - 1].round(4).tolist(), "test": te[grid - 1].round(4).tolist(),
                         "bestM": k + 1, "bestVal": round(float(va[k]), 4), "testAtBest": round(float(te[k]), 4),
                         "bestTestM": kt + 1, "M2": k2 + 1, "bestTest": round(float(te[kt]), 4)})
json.dump({"nus": NUS, "depths": DEPTHS, "subsamples": SUBS, "M": grid.tolist(), "runs": runs},
          open("grid.json", "w", encoding="utf-8"))

The following cell recomputes one row (depth 3, ν=0.1\nu = 0.1, with and without subsampling) so you can verify the interactive displays what the code produces.

[ ]One grid row, recomputedBrowser
from sklearn.datasets import make_friedman1
from sklearn.ensemble import GradientBoostingRegressor

Xf, yf = make_friedman1(n_samples=4500, noise=1.0, random_state=0)
Xa, ya, Xv, yv, Xt, yt = Xf[:500], yf[:500], Xf[500:2500], yf[500:2500], Xf[2500:], yf[2500:]
for sub in (1.0, 0.5):
    g = GradientBoostingRegressor(n_estimators=600, learning_rate=0.1, max_depth=3, subsample=sub,
                                  random_state=0).fit(Xa, ya)
    va = np.array([np.mean((yv - p) ** 2) for p in g.staged_predict(Xv)])
    te = np.array([np.mean((yt - p) ** 2) for p in g.staged_predict(Xt)])
    k = int(va.argmin())
    print(f"subsample = {sub}: M* = {k + 1}, ECM de validación {va[k]:.3f}, ECM de test en M* {te[k]:.3f}")

These are the interactive’s readings for depth 3 and ν=0.1\nu = 0.1: without subsampling, M⋆=460M^\star = 460 and test MSE 2.661; with half the rows in each tree, M⋆=547M^\star = 547 and 2.371, 11% lower.

Common mistakes

The other four common mistakes have already appeared where relevant: using the mean as an L1 leaf value, combining a high rate with many trees, choosing the number of trees using test, and forgetting initialization.

Exercises

ProofSquared loss: residuals and means
Prove: For loss ℓ(y,F)=12(y−F)2\ell(y, F) = \tfrac12(y - F)^2, pseudo-residuals are ordinary residuals yi−Fm−1(xi)y_i - F_{m-1}(\vb{x}_i) and each leaf's optimal value is its residual mean.
0
Fix stage mm and a leaf RjR_j with NjN_j points. Write Fi=Fm−1(xi)F_i = F_{m-1}(\vb{x}_i) and ui=yi−Fiu_i = y_i - F_i.

Step 1 of 3. What is pseudo-residual rimr_{im}?

ProofBinomial deviance: pseudo-residuals and Newton step
Prove: For binomial deviance ℓ(y,F)=log⁡(1+eF)−yF\ell(y, F) = \log(1 + e^F) - yF with y∈{0,1}y \in \{0, 1\} and FF in log-odds, pseudo-residuals are ri=yi−pir_i = y_i - p_i with pi=σ(Fi)p_i = \sigmoid(F_i), and a Newton step from γ=0\gamma = 0 for leaf value RjR_j is γj=∑i∈Rjri/∑i∈Rjpi(1−pi)\gamma_j = \sum_{i \in R_j} r_i / \sum_{i \in R_j} p_i(1 - p_i).
0
Write σ(F)=1/(1+e−F)\sigma(F) = 1/(1 + e^{-F}) and Lj(γ)=∑i∈Rjℓ(yi,Fi+γ)L_j(\gamma) = \sum_{i \in R_j}\ell(y_i, F_i + \gamma).

Step 1 of 3. What is ∂ℓ/∂F\partial\ell/\partial F?

NumericAn L1 leaf value
Gradient boosting with absolute loss. Residuals yi−Fm−1(xi)y_i - F_{m-1}(\vb{x}_i) of the five points in a leaf are (−3,−1,0,2,10)(-3, -1, 0, 2, 10). What is the leaf's optimal value γ\gamma (before multiplying by ν\nu)?
NumericA leaf value with quantile loss
With pinball loss τ=0.75\tau = 0.75, residuals of seven points in a leaf are (−2,−1,0.5,1,3,4,8)(-2, -1, 0.5, 1, 3, 4, 8). What is the optimal leaf value γ\gamma?
NumericA Newton step in a leaf
Classification with binomial deviance. A leaf contains four points with labels (1,1,0,1)(1, 1, 0, 1) and the current model gives F=0F = 0 (probability 0.50.5) to all four. What value γ\gamma does Friedman's Newton step assign to the leaf?
CodeHuber loss for GBM
Implement the class HuberLoss(alpha) with the three methods used by the lesson's GBM. init(y) returns the median of y (np.median). negative_gradient(y, F) computes residuals d = y - F, stores in self.delta the alpha quantile of |d| using scikit-learn's convention (np.quantile(..., method='inverted_cdf')) and returns residuals clipped to [-delta, delta]. update_leaf(y, F, r) receives points in a leaf and returns Friedman's approximation to the optimal value: the lower median med of the leaf's y - F residuals (0.5 quantile using inverted_cdf) plus the mean of sign(d - med) * min(delta, |d - med|), using delta from the last call to negative_gradient. Tests compare boosting built with your class and scikit-learn trees against GradientBoostingRegressor(loss='huber').
import numpy as np

class HuberLoss:
  def __init__(self, alpha=0.9):
      self.alpha = alpha
      self.delta = None

  def init(self, y):
      return np.mean(y)

  def negative_gradient(self, y, F):
      # tu código: residuos, delta (cuantil alpha de |residuos|), residuos recortados
      return y - F

  def update_leaf(self, y, F, r):
      # tu código: mediana inferior de los residuos más la media de las desviaciones recortadas
      return np.mean(r)
Shift+Enter to run
QuizOne-tenth the rate
You have well-tuned gradient boosting with ν=0.1\nu = 0.1 and M=300M = 300 trees chosen by early stopping. You switch to ν=0.01\nu = 0.01. What do you do with the number of trees to obtain a comparable model?
QuizWhat the tree sees with L1
Gradient boosting with absolute loss. A point in a leaf has residual changing from +2+2 to +200+200 due to a recording error. What changes in that iteration?
QuizWhich number do you report?
You train boosting with 2,000 trees and look at the error curve on your test set: the minimum is at M=640M = 640, with error 0.231. On validation, the minimum is at M=590M = 590. What do you do?
QuizDoes it always fall?
Which statement about training loss R^(Fm)\hat{R}(F_m) of gradient boosting with trees is correct?

Summary

Key idea
Gradient boosting is gradient descent in function space: at each stage a regression tree is fitted to pseudo-residuals (the negative loss gradient on the data), each leaf’s value is set using the actual loss, and the tree is added shrunk by ν\nu.
  • Empirical loss only sees FF at the nn points; its gradient is a vector in Rn\R^n that does not generalize. The least-squares tree projects it onto piecewise-constant functions, and that projection is a descent direction: ⟨g,h⟩n=−∥h∥n2\inner{g}{h}_n = -\norm{h}_n^2.
  • Each loss contributes three pieces: F0F_0, pseudo-residuals and leaf value. Squared: residuals and means. Absolute: signs and medians. Huber: residuals clipped at the α\alpha quantile and one step from the median. Quantile: τ\tau or τ−1\tau - 1 and the leaf’s τ\tau quantile. Binomial deviance: y−py - p and a Newton step ∑r/∑p(1−p)\sum r / \sum p(1 - p).
  • ν\nu and MM compensate (what matters is approximately νM\nu M), and small ν\nu with enough trees gives better models, with diminishing returns. Depth sets interaction order: stumps give an additive model.
  • Subsampling without replacement each iteration reduces cost by a factor ff and, especially with few data and large trees, error, by decorrelating trees.
  • Tree count is chosen by early stopping on validation: training error always asks for more trees and test cannot be touched.