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 that minimizes empirical risk
where is a loss differentiable in its second argument (for example, ). In a parametric model, , gradient descent moves . Here there are no parameters: the unknown is the entire function.
The first step is to realize that only looks at at points. Call the prediction vector. Then is an ordinary function of variables, and its gradient has one component per example:
(We omit the factor , which only rescales the step.) Gradient descent in would be . With squared loss, , and a step with leads directly to : it memorizes the data in one step and says nothing about at a new point. Vector 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 of functions that can be evaluated at any (small regression trees, for example), and find within that class the function most similar to on the data:
Fitting by least squares to projects the gradient onto the class. Then perform a line search along and update . The resulting function is defined over all , because it is a sum of trees.
Why does least-squares projection give a descent direction? Use the data inner product, , and its norm . A first-order Taylor expansion in each component gives
so, if , is a descent direction: a sufficiently small step in that direction reduces empirical risk. Mason and coauthors choose by directly maximizing (with normalized); Friedman uses least squares. For trees, the two ideas are essentially equivalent, as we can prove.
Proof
With the partition fixed, is a subspace of (through the values on the data), spanned by the mutually orthogonal leaf indicators. The least-squares fit is the orthogonal projection of onto , and in that basis it is computed leaf by leaf: minimizing gives . As an orthogonal projection, residual is orthogonal to and in particular to : . Thus . And .
∎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 . The tree is therefore a greedy search for the direction in (with leaves) most aligned with the negative gradient. The first interactive’s reading “fraction of captured by ” is exactly that .
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 ) are discarded: each leaf receives minimizing the actual loss. A tree with leaves is a combination of basis functions, indicators , and instead of a single line search along there are 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 (shrinkage) multiplies each tree’s contribution. With the optimal step is taken; with , 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.
Play the animation with default values (, 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 . Notice three things:
- Residuals shrink and become noise. Initially arrows are long and coherent (a whole region above , another below) and the tree captures a large fraction of . 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 and depth 2 the validation minimum occurs at the first iteration and is substantially greater than with (0.200 versus 0.148, at ): 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 for the residual; you saw regression losses and their gradients in lesson 1.
| Loss | Pseudo-residual | Leaf value | |
|---|---|---|---|
| Squared, | mean of | mean of leaf’s | |
| Absolute, | median of | median of leaf’s | |
| Huber with threshold | if ; otherwise | median of | one step from median (below) |
| Quantile (pinball) | if ; otherwise | quantile of | quantile of leaf’s |
| Binomial deviance | (Newton) |
Squared: the familiar residuals
With , and the pseudo-residual is the residual. A leaf’s optimal value minimizes , whose solution is the mean of : 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 , the derivative with respect to is away from ; at the loss is nondifferentiable and any value in is a subgradient. We take . 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 gives the median of the leaf’s . (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 : 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:
Pseudo-residuals are residuals clipped to . Which ? Friedman proposes recomputing it at every stage as the quantile of , so sets the fraction of points treated as “normal”; in his 2002 study he uses , 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 of the leaf’s residuals:
where 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 has as its population minimizer the quantile of given . Its negative gradient takes only two values, if the point is above the model and if below. With , each point above pushes upward with force and each below pushes downward with force : equilibrium occurs when 90% of points lie below. The optimal leaf value is the quantile of leaf residuals. It is the standard tool for prediction intervals and probabilistic quantile forecasting.
Start with L2 at : outliers produce pseudo-residuals of two to four units, the tree isolates their regions and rises toward them in steps. Switch to L1 without changing : the lower panel becomes a row of signs , mean signs in each leaf (aqua) stay in and the added value (amber) is the residual median, in units of . hugs (mean offset versus with L2).
Huber has a trap visible in the interactive. With , threshold is the 0.9 quantile of absolute residuals, but 11% of points (9 of 80) here are contaminated: the threshold falls among outliers. At it is , four or five times the normal noise deviation, and an outlier clipped at still pushes as hard as four or five normal residuals; lies halfway (). Lower to : falls to , all 9 contaminated points are clipped and returns to (). As a practical rule must exceed the expected outlier fraction: sets the procedure’s breakdown point. Finally, with quantile loss, raise and watch “points below ”: after enough iterations it approaches .
Continue with Huber and and take beyond 40: narrow peaks appear over some outliers. Once normal points are well fitted, their pseudo-residuals are nearly zero and an outlier’s 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 , 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 plus constant . With 12% contamination and mean jump , the conditional mean is above ; 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 , the model returns log-odds and probability . The loss is the negative Bernoulli log-likelihood:
Differentiating, , so the pseudo-residual is : what the probability lacks to reach the label. is the best constant, , i.e., the log-odds of prevalence.
The optimal leaf value, , has no closed form. Since the second derivative is , one Newton step from gives
You will derive this in the second guided exercise. Friedman writes the same algorithm (L2_TreeBoost) with and equal to half the log-odds, and obtains ; with 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:
| 1.0 | 0.5 | 0.25 | 0.125 | 0.06 | 0.03 | |
|---|---|---|---|---|---|---|
| Optimal | 15 | 43 | 77 | 146 | 326 | 855 |
| relative error | 0.48 | 0.40 | 0.34 | 0.32 | 0.32 | 0.32 |
Two regularities stand out. First, and compensate: whenever is halved, optimal increases by a factor between 1.8 and 2.9, and overall, from to (8.3 times smaller), goes from 77 to 855 (11 times greater). Second, small wins, with diminishing returns below . Friedman’s practical recommendation follows: set as large as computation allows and tune so the validation minimum is near that .
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 is direct: each step of size changes one coefficient by , so after steps the coefficient norm is at most , with equality for monotone paths. The product acts as the lasso’s budget in its constrained form, : moving slowly traces a family of progressively less regularized models and allows stopping at the right point. With 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- tree is a function depending on at most variables along each path from root to leaf. Thus a model of depth-1 trees (stumps) is additive, : 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, , with 10 uniform variables (the last 5 have no effect) and noise . There is only one interaction, between and 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 is very noisy (a median of two points, a Newton step with nearly zero ), and limiting it is cheap regularization.
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 , depths 1, 2, 3 and 5, and subsampling 1 or 0.5. Above, validation mean squared error for each , colored relative to the panel's best value (stronger means closer to the minimum); circles mark each row's and dashed lines join points with constant . 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 following constant and from then on, with small , stays on a long plateau; with or the row never intensifies. The reading “first within 2% of minimum” quantifies this better than exact , because the minimum is very flat and its exact position varies: for and , that is 107, 244, 423, 1230 and 1818, and is 21, 24, 21, 25 and 18: dividing by 20 multiplies the number of trees needed by 17. Rows and 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 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 , 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 : simply evaluate partial predictions
The fact that training error does not rise is a fact, not merely an observation, at least for losses where is the exact minimizer. If is convex in and minimizes leaf loss, then for , by convexity,
where the final inequality uses as a candidate. Summing over leaves gives . This holds for squared, absolute and pinball losses. For Huber and deviance, 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 : 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 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 , with a typical 11% improvement in absolute error (22% on squared scale) versus no subsampling, and even or improved substantially, with 5× and 3× speedups. With 5,000 examples the best fraction was closer to 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 , 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 predictors of variance and correlation , the average has variance , and lowering more than compensates for raising when is large. Using without replacement resembles drawing bootstrap samples, which contain on average % 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 validation error falls clearly (2.51 to 2.03 in the best row; test error at , 2.61 to 2.14). With 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.
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 : 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): , which is times the reduction in sum of squares and thus chooses the same splits.
Now the other losses. For absolute and quantile we use the “inverted_cdf” quantile (the smallest value with ), scikit-learn’s convention for leaf values; with an even number of points, the “median” is the lower of the two central values.
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 above , less than the population : this sample has only 13 contaminated out of 200 (6.5%, not 12%), and , so L2 estimates the mean of this sample well. L1 hugs (), leaving 48.5% of points below. Huber stays at . Quantile with shifts , close to the population quantile (), with 76.5% of points below.
Finally, classification. We compare with decision_function of GradientBoostingClassifier, which returns as log-odds.
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 (the constant’s, nearly because prevalence is ) to , 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 on test for every from one training run.
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 test deviance bottoms out at iteration 9 (0.4970) and by iteration 200 has risen to 0.8274; with the minimum is better (0.4863, at 78) and subsequent deterioration much slower. But look at classification error: with 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 , while deviance also depends on its magnitude. When overfitting, the model inflates (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.
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.
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 when the test minimum is at 68, paying for it (0.4997). The reason is structural: oob_scores_[m] is the loss of on points not used by tree , but each point entered approximately half the previous trees, so has already seen them and their loss does not reflect overfitting. To choose , 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, , with and without subsampling) so you can verify the interactive displays what the code produces.
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 : without subsampling, and test MSE 2.661; with half the rows in each tree, 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
Step 1 of 3. What is pseudo-residual ?
Step 1 of 3. What is ?
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)Summary
- Empirical loss only sees at the points; its gradient is a vector in that does not generalize. The least-squares tree projects it onto piecewise-constant functions, and that projection is a descent direction: .
- Each loss contributes three pieces: , pseudo-residuals and leaf value. Squared: residuals and means. Absolute: signs and medians. Huber: residuals clipped at the quantile and one step from the median. Quantile: or and the leaf’s quantile. Binomial deviance: and a Newton step .
- and compensate (what matters is approximately ), and small 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 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.