Boosting: AdaBoost and forward stagewise additive modeling
Answer Kearns and Valiant's question—can weak learners be combined into a strong one?—with AdaBoost, and reinterpret it with Friedman, Hastie and Tibshirani as stagewise additive modeling minimizing exponential loss. Prove the exponential training-error bound, discuss margin explanations for AdaBoost's unexpectedly limited overfitting and their limits under label noise.
After this lesson you can
- Implement discrete AdaBoost with decision stumps and reproduce sample-weight evolution.
- Prove the training-error bound Π_t 2√(ε_t(1 - ε_t)) ≤ exp(-2Σ_t γ_t²).
- Derive AdaBoost as stagewise additive modeling with exponential loss and obtain α_t = ½ log((1 - ε_t)/ε_t).
- Explain boosting margin theory and its limits.
- Diagnose AdaBoost sensitivity to label noise and relate it to exponential loss.
Before you start
Motivation: can an almost random rule be amplified?
In 1988 Michael Kearns and Leslie Valiant posed a seemingly academic learning-theory question. In PAC learning, an algorithm strongly learns a class if, with enough data, it achieves arbitrarily small error with arbitrarily high probability. It weakly learns if it guarantees only slightly better than a coin flip: error at most for fixed, perhaps tiny . Are the notions equivalent? Can any rule 51 % correct become one 99.9 % correct?
Robert Schapire answered yes in 1990 with a recursive construction: train one rule, another on a sample where the first fails half the time, a third where the two disagree, and majority-vote; repeat inside each piece. Yoav Freund soon found a much more efficient method, boost by majority (journal publication 1995), still requiring in advance. The version used today is Freund and Schapire (1997): AdaBoost, adaptive boosting, which need not know because it adapts to each rule’s error. The paper also derives it from online-learning multiplicative weights Hedge, earning its authors the 2003 Gödel Prize.
Surprisingly, it worked very well in practice. On letter (recognizing 26 letters from 16 features), Schapire, Freund, Bartlett and Lee (1998) report C4.5 tree test error 13.8 %, bagging 1000 trees lowering it to 6.6 %, and AdaBoost with the same tree reaching 3.1 %. They note what this lesson seeks to understand: training error is already 0 after five rounds, yet test error keeps falling from 8.4 % at round 5 to 3.1 % at 1000, when the vote combines over two million nodes.
Bagging and boosting combine many trees for opposite reasons. Bagging averages deep, low-bias high-variance trees trained in parallel on resamples, gaining because averaging weakly correlated predictors reduces variance. Boosting combines very simple high-bias rules trained sequentially: each fits examples earlier rules classify worst. This lesson builds AdaBoost, proves exponential training-error decay, reinterprets it with Friedman, Hastie and Tibshirani (2000) as loss optimization, discusses margin explanations for less overfitting than expected, and ends where it fails: noisy labels. The next lesson generalizes to any differentiable loss with gradient boosting.
Weak learners
Kearns and Valiant’s question can be posed on a particular sample, as AdaBoost uses it.
Two details matter more than they appear:
- “For any distribution.” A classifier with error under uniform weights is easy to find; positive advantage under every reweighting, including ones concentrating on hardest examples, is a strong assumption. AdaBoost uses it each round on a different distribution constructed so the previous learner is exactly at chance.
- Advantage belongs to class and data together. One-split trees (decision stumps) have comfortable advantage on a circular-boundary problem and almost none on XOR, : under the square’s uniform distribution any vertical or horizontal split leaves half of each class on either side. See the first figure.
Discrete AdaBoost
AdaBoost maintains distribution over examples, starts uniformly, and each round asks the weak learner for a classifier for the current distribution and changes it so that classifier stops being useful.
Since when is correct and when wrong, reweighting multiplies correct cases by and mistakes by : a mistake’s weight relative to a correct case grows by . Vote is positive exactly when , grows unbounded as and is zero when is no better than chance. If some had , would be negative and the vote would use , which is better than chance.
Proof
Before normalization, mistakes weigh and correct cases . They weigh equally, so after normalization each group weighs , and .
∎That is the whole idea: after each round choose a distribution under which the learner just added contributes nothing. The next must find something else. Watch it in action.
Three things the figure shows and the rest of the lesson explains:
- Training error falls rapidly, but rises. Early rounds find good splits with nearly uniform weights; later the distribution concentrates near the boundary and each stump barely beats chance. The next theorem’s bound quantifies it.
- For the circle, a sum of stumps approximates the boundary by a staircase. Vote sums step functions of and : a feature-additive model. This suffices for the circle, whose class is exactly with , but not XOR. Term explains a common circle phenomenon: a round’s best stump may not split and predicts the same class across the square (threshold outside data). It is the vote’s constant term, readjusted whenever a split unbalances class weights.
- With XOR and stumps training error falls, but true error does not. A finite sample always has a split with weighted error slightly below , so AdaBoost advances by memorization with tiny . Depth-2 trees make XOR easy; with initial data, at round 74 a tree separates all 80 points: , and AdaBoost stops.
The base learner: weighted stumps
A stump is if and otherwise, with a feature, a threshold and . To choose with weights use advantage , related to weighted error by , i.e. . Minimizing maximizes (the sign of fixes ).
Sort examples by and let sum over the first . A split after the -th predicts left and right, with advantage ; cases and are constant stumps. A cumulative sum gives all splits for a feature at once: after one initial sort (), each round costs . This is CART’s split sweep with weighted error instead of impurity.
The training-error bound
Proof
Step 1: unroll weights. Applying the reweighting rule times from ,
Since sums to 1, : the product of normalizers is exactly the vote’s mean exponential loss.
Step 2: 0–1 is below exponential. If , then and ; otherwise . Thus for every and, averaging,
Step 3: each value. Separating correct cases and errors gives , which with AdaBoost’s equals (as in the preceding proposition). With , .
Step 4: exponential. For all , ; with , . Multiplying over gives the last inequality.
∎Step 3 hides another interpretation of . Function is convex and its derivative vanishes at : AdaBoost’s minimizes , i.e. reduces that round’s bound most. AdaBoost greedily minimizes mean exponential loss of its vote. The next section turns this into a statistical viewpoint.
Three consequences:
- Weak implies strong on the sample. If , training error falls below and is exactly 0 once , i.e. after rounds. This constructively answers Kearns and Valiant. Small test error needs a separate generalization argument: margin theory below.
- The bound uses only advantages. It does not depend on the weak learner, dimension or : only sequence . Any weight-aware learner can be used.
- A bound is not a prediction. The product is usually far above actual error because is loose at large margins.
Check by implementing AdaBoost with stumps from scratch on the figure’s circle problem, with 300 training and 20 000 test points.
import numpy as np
def circulo(n, rng):
"""x uniforme en [-1, 1]^2; clase +1 dentro del círculo de área 2 (la mitad del cuadrado)."""
X = rng.uniform(-1, 1, size=(n, 2))
y = np.where((X ** 2).sum(axis=1) < 2 / np.pi, 1, -1)
return X, y
class Tocones:
"""Busca el tocón de mínimo error ponderado. Ordena una vez; cada búsqueda cuesta O(nd)."""
def __init__(self, X):
n, d = X.shape
self.orden = np.argsort(X, axis=0, kind="stable")
Xs = np.take_along_axis(X, self.orden, axis=0)
self.umbral = np.vstack([np.full(d, -np.inf), (Xs[1:] + Xs[:-1]) / 2, np.full(d, np.inf)])
self.valido = np.vstack([np.ones(d, bool), Xs[1:] > Xs[:-1], np.ones(d, bool)])
def ajustar(self, y, w):
"""Devuelve (j, u, s, r): h(x) = s si x_j > u y -s si no; r = sum_i w_i y_i h(x_i) es la ventaja."""
wy = (w * y)[self.orden] # n x d, en orden creciente de cada x_j
izq = np.vstack([np.zeros(wy.shape[1]), np.cumsum(wy, axis=0)])
r = izq[-1] - 2 * izq # ventaja de s = +1 para cada corte
r[~self.valido] = 0.0
k, j = np.unravel_index(np.argmax(np.abs(r)), r.shape)
s = 1.0 if r[k, j] >= 0 else -1.0
return j, self.umbral[k, j], s, abs(r[k, j])
def tocon(X, j, u, s):
return np.where(X[:, j] > u, s, -s)
def adaboost(X, y, T, X_test=None, y_test=None):
n = len(y)
buscador = Tocones(X)
D = np.full(n, 1 / n)
F = np.zeros(n)
F_test = None if X_test is None else np.zeros(len(y_test))
reg = {k: [] for k in ("eps", "alfa", "tocon", "err_ent", "err_test", "cota", "medio_tras")}
cota = 1.0
for t in range(T):
j, u, s, r = buscador.ajustar(y, D)
h = tocon(X, j, u, s)
eps = D[h != y].sum() # error ponderado = (1 - r) / 2
alfa = 0.5 * np.log((1 - eps) / eps)
D = D * np.exp(-alfa * y * h)
Z = D.sum() # normalizador Z_t
D = D / Z
F += alfa * h
cota *= Z
reg["eps"].append(eps); reg["alfa"].append(alfa); reg["tocon"].append((j, u, s))
reg["err_ent"].append(np.mean(np.sign(F) != y)); reg["cota"].append(cota)
reg["medio_tras"].append(D[h != y].sum()) # error de h_t con los pesos nuevos
if F_test is not None:
F_test += alfa * tocon(X_test, j, u, s)
reg["err_test"].append(np.mean(np.sign(F_test) != y_test))
reg = {k: np.array(v) if k != "tocon" else v for k, v in reg.items()}
reg["F"] = F
return reg
rng = np.random.default_rng(0)
X, y = circulo(300, rng)
X_te, y_te = circulo(20000, rng)
reg = adaboost(X, y, 400, X_te, y_te)
gam = 0.5 - reg["eps"]
cota_exp = np.exp(-2 * np.cumsum(gam ** 2))
print(" t ε_t α_t err.ent. ∏ Z_t exp(-2Σγ²) err.test")
for t in (1, 2, 3, 5, 10, 20, 50, 100, 200, 400):
i = t - 1
print(f"{t:3d} {reg['eps'][i]:.3f} {reg['alfa'][i]:.3f} {reg['err_ent'][i]:.3f} {reg['cota'][i]:.3f} {cota_exp[i]:.3f} {reg['err_test'][i]:.4f}")
cero = int(np.argmax(reg["err_ent"] == 0)) + 1
print("primera ronda con error de entrenamiento 0:", cero)
print("¿cota respetada en todas las rondas?", bool(np.all(reg["err_ent"] <= reg["cota"] + 1e-12)),
" ¿∏Z_t = ∏ 2√(ε(1-ε))?", np.allclose(reg["cota"], np.cumprod(2 * np.sqrt(reg["eps"] * (1 - reg["eps"])))))
print("error de h_t con los pesos D_{t+1}: mín", reg["medio_tras"].min().round(12), " máx", reg["medio_tras"].max().round(12))
print("ε_t medio en las rondas 1-10:", reg["eps"][:10].mean().round(3), " en las rondas 301-400:", reg["eps"][300:].mean().round(3))The table confirms the theorem and its looseness. Training error reaches 0 at round 67, yet the bound at round 100 is . The inequality holds for all 400 rounds, matches and each error under next weights is exactly , as stated. The bound slows because of : its mean falls from in the first ten rounds to in rounds 301–400. As weights concentrate on hard points, best-stump advantage shrinks.
Notice test error too: from with one stump to at rounds 100 and 200, and at round 400. On this noiseless problem continuing after zero training error neither helps nor hurts appreciably. The margin section has a case where it helps; the noise section one where it hurts badly.
Statistical view: forward stagewise additive modeling
The proof says AdaBoost reduces . Friedman, Hastie and Tibshirani (2000) reversed the argument: AdaBoost is a method fitting an additive model by minimizing that loss.
Fitting all terms simultaneously (backfitting or joint optimization) is expensive and often unnecessary. Stagewise fitting solves a one-basis-function problem per step, often in closed form.
The equivalence has a fundamental consequence: AdaBoost estimates something. Exponential loss is a classification loss expressed in margin , a convex differentiable upper bound on 0–1, and its population minimizer, as seen in the functional elicited by each loss lesson, is
Half the log-odds (you will prove it in an exercise). Therefore is the Bayes rule and, at least in population, . Scaled logistic loss has the same minimizer and, up to an additive constant, matches exponential to second order at (both equal ): they resemble each other near the boundary and separate on badly misclassified examples with very negative margins, where exponential grows like and logistic only like . This difference returns with noise.
Coordinate descent over a learner dictionary
Another view connects to the next lesson. If possible learners are finite (with points there are at most distinct stumps on the sample), , every vote is and exponential loss is a convex function of :
with and the weighted error of under current weights. Choosing the minimum weighted-error learner chooses the coordinate with most negative partial derivative, and setting performs exact line search in that coordinate. AdaBoost is coordinate descent with Gauss–Southwell’s rule (largest gradient coordinate) over a huge dictionary where only used coordinates are materialized. Next lesson’s gradient boosting replaces exponential with any loss and best-coordinate search with least-squares gradient fitting.
This view also explains separable data by some class vote: then , the infimum is unattained, and grows without bound. Training error reaches 0 and loss keeps falling as margins grow: thereafter ’s direction, not size, matters. Rosset, Zhu and Hastie (2004) proved infinitesimal-step boosting approximately follows the -regularized exponential path, converging to the maximum--margin separator: implicit max-margin bias like gradient descent in logistic regression.
Stagewise fitting does not need closed formulas. Choose direction by gradient and perform line search numerically; with exponential loss it should reproduce AdaBoost.
PERDIDAS = {
# l(m), l'(m), l''(m) como funciones del margen m = y F(x)
"exponencial": (lambda m: np.exp(-m), lambda m: -np.exp(-m), lambda m: np.exp(-m)),
"logística": (lambda m: np.logaddexp(0, -2 * m),
lambda m: -2 / (1 + np.exp(np.clip(2 * m, -700, 700))),
lambda m: 1 / np.cosh(np.clip(m, -350, 350)) ** 2),
}
def paso_optimo(dl, d2l, m, yh, iters=50):
"""Minimiza phi(b) = sum_i l(m_i + b y_i h_i) por Newton (phi es convexa)."""
b = 0.0
for _ in range(iters):
g = np.sum(dl(m + b * yh) * yh)
H = np.sum(d2l(m + b * yh)) # (y h)^2 = 1
paso = g / H
b -= paso
if abs(paso) < 1e-12:
break
return b
def por_etapas(X, y, perdida, T, X_te=None, y_te=None, ruido=None):
l, dl, d2l = PERDIDAS[perdida]
B = Tocones(X); F = np.zeros(len(y)); F_te = np.zeros(0 if X_te is None else len(X_te))
betas, err_te, cuota = [], [], []
for t in range(T):
m = y * F
w = -dl(m); w = w / w.sum() # dirección: el gradiente en cada punto
j, u, s, r = B.ajustar(y, w) # tocón más alineado con -gradiente
h = tocon(X, j, u, s)
b = paso_optimo(dl, d2l, m, y * h) # búsqueda lineal numérica
F += b * h; betas.append(b)
if X_te is not None:
F_te += b * tocon(X_te, j, u, s); err_te.append(np.mean(np.sign(F_te) != y_te))
if ruido is not None:
cuota.append(w[ruido].sum())
return np.array(betas), np.array(err_te), np.array(cuota)
betas, _, _ = por_etapas(X, y, "exponencial", 100)
print("exponencial: máx |β_t - α_t| en 100 rondas =", np.abs(betas - reg["alfa"][:100]).max())With exponential loss Newton’s 100 steps match AdaBoost’s up to floating-point rounding, and stumps match because weights are AdaBoost’s. With logistic, weights become , bounded by 2, and the step lacks a closed form. Below we use this code to compare losses with noise.
Margins: why test error can keep falling
Return to letter: after 5 rounds training error is 0 and the much more complex 1000-tree vote generalizes better. Schapire, Freund, Bartlett and Lee (1998) explain that training error poorly measures what AdaBoost continues improving. Examine its confidence on each example.
Normalization is essential: grows unbounded with rounds even if vote direction does not change. Schapire and coauthors’ main result, proved in the margin generalization bound, says that if base learners come from a VC-dimension- class, with probability at least over a sample of size , for every vote and every ,
where is the fraction of training examples with normalized margin at most . Notably absent is round count . Complexity is measured by , that of one base learner, and its term is paid with . If adding rounds lowers the small-margin fraction, the bound improves even with millions of vote nodes.
Why should margins grow? AdaBoost pushes them using the same argument as its training-error bound:
With this is the training-error bound; you will prove the general result in a guided exercise. As long as the weak learner retains advantage, AdaBoost does not settle for correct classification: it keeps pushing the smallest margins rightward. The figure shows a clear case.
The figure uses nested spheres from Hastie, Tibshirani and Friedman in The Elements of Statistical Learning: ten independent Gaussian features, with class indicating whether the point lies outside the sphere holding half the mass. The boundary is smooth, no noise, so Bayes error is 0. The next cell repeats with 500 training and 5000 test examples, depth-2 trees chosen by weighted Gini (as DecisionTreeClassifier(max_depth=2) would), and measures margins.
CHI2_10 = 9.341817765591966 # mediana de una chi-cuadrado con 10 grados de libertad
def esferas(n, rng):
"""ESL, ecuación (10.2): x ~ N(0, I_10), clase +1 si ||x||^2 > mediana de chi2_10."""
X = rng.normal(size=(n, 10))
return X, np.where((X ** 2).sum(axis=1) > CHI2_10, 1, -1)
def mejor_corte(B, wp, wm):
"""Corte de mínimo Gini ponderado sobre el orden global de B (pesos nulos fuera del nodo)."""
P = np.vstack([np.zeros(B.orden.shape[1]), np.cumsum(wp[B.orden], axis=0)])
M = np.vstack([np.zeros(B.orden.shape[1]), np.cumsum(wm[B.orden], axis=0)])
tp, tm = P[-1], M[-1]
L = P + M; R = (tp - P) + (tm - M)
with np.errstate(divide="ignore", invalid="ignore"):
g = np.where(L > 0, (P ** 2 + M ** 2) / L, 0) + np.where(R > 0, ((tp - P) ** 2 + (tm - M) ** 2) / R, 0)
g[~B.valido | (L <= 0) | (R <= 0)] = -np.inf # el corte debe dejar peso a los dos lados
k, j = np.unravel_index(np.argmax(g), g.shape)
return j, B.umbral[k, j], g[k, j]
def arbol2(B, X, y, w):
"""Árbol de profundidad 2 con Gini ponderado; hojas = clase de más peso (±1)."""
wp, wm = w * (y > 0), w * (y < 0)
j, u, _ = mejor_corte(B, wp, wm)
der = X[:, j] > u
hijos = []
for lado in (~der, der):
jj, uu, gg = mejor_corte(B, wp * lado, wm * lado)
if not np.isfinite(gg): # nodo sin cortes posibles: hoja
s = 1.0 if wp[lado].sum() >= wm[lado].sum() else -1.0
hijos.append((0, np.inf, s, s))
continue
d2 = X[:, jj] > uu
hojas = [1.0 if wp[m].sum() >= wm[m].sum() else -1.0 for m in (lado & ~d2, lado & d2)]
hijos.append((jj, uu, hojas[0], hojas[1]))
return j, u, hijos
def arbol2_predict(a, X):
j, u, hijos = a
der = X[:, j] > u
out = np.empty(len(X))
for lado, (jj, uu, si, sd) in zip((~der, der), hijos):
out[lado] = np.where(X[lado, jj] > uu, sd, si)
return out
def adaboost_arboles(X, y, T, X_te):
B = Tocones(X); n = len(y); D = np.full(n, 1 / n)
H = np.empty((T, n)); H_te = np.empty((T, len(X_te))); A = np.empty(T)
for t in range(T):
a = arbol2(B, X, y, D)
h = arbol2_predict(a, X); eps = D[h != y].sum()
A[t] = 0.5 * np.log((1 - eps) / eps)
D = D * np.exp(-A[t] * y * h); D /= D.sum()
H[t] = h; H_te[t] = arbol2_predict(a, X_te)
return A, H, H_te
rng4 = np.random.default_rng(0)
X4, y4 = esferas(500, rng4); X4_te, y4_te = esferas(5000, rng4)
A, H, H_te = adaboost_arboles(X4, y4, 1000, X4_te)
F_ac = np.cumsum(A[:, None] * H, axis=0); Ft_ac = np.cumsum(A[:, None] * H_te, axis=0)
err_ent = np.mean(np.sign(F_ac) != y4, axis=1); err_te = np.mean(np.sign(Ft_ac) != y4_te, axis=1)
margen = y4 * F_ac / np.cumsum(A)[:, None] # márgenes normalizados; fila t = tras t+1 rondas
T0 = int(np.argmax(err_ent == 0)) + 1
print("primera ronda con error de entrenamiento 0:", T0)
print(" T err.ent. err.test margen mín. P(ρ ≤ 0.05) P(ρ ≤ 0.1) mediana")
for T in (5, 50, T0, 200, 500, 1000):
m = margen[T - 1]
print(f"{T:4d} {err_ent[T-1]:.3f} {err_te[T-1]:.4f} {m.min():+.3f} {np.mean(m <= 0.05):.3f} {np.mean(m <= 0.1):.3f} {np.median(m):.3f}")Training error reaches 0 at round 125, with test error . Thereafter training says nothing, yet test improves: at round 200, at 500 and at 1000. Margins do change. The minimum rises from to and fraction with drops from to . But the last columns show fraction with rises from to and median falls from to . AdaBoost does not shift the entire distribution right: it raises small margins at the expense of large ones, narrowing around a common value. This fits an algorithm pushing the left tail hardest, and makes choice of in the bound important.
Limits of the explanation
The margin explanation prompted one of learning theory’s most instructive debates.
- Breiman and arc-gv. If larger margins improve the bound, directly maximizing the minimum margin should generalize better. Breiman (1999) designed arc-gv, obtaining larger minimum margins than AdaBoost in experiments but worse test errors. He interpreted this as a refutation.
- Reyzin and Schapire. Reyzin and Schapire (2006) reproduced the experiment and found arc-gv used more complex base trees: the bound’s complexity term, depending on learner class, differed. Their conclusion: maximizing margins is desirable, but not at the expense of base-learner complexity.
- AdaBoost does not maximize minimum margin. With separable data one might expect convergence to the maximum-minimum-margin vote. Rudin, Daubechies and Schapire (2004) showed not always: its dynamics can cycle below it. Vanishing-step boosting (Rosset et al. above) and designed variants such as arc-gv do attain it.
- The bound is not quantitative. The authors warn it is too loose to predict test error; it explains curve shape, not level. Even the training-margin theorem without complexity term is loose: in the figure after 500 rounds it is at , where actual fraction is , and exceeds 1 between and , when is already around .
The current picture is nuanced: the margin distribution, not just its minimum, relates to generalization, and base-learner complexity matters as much as margins. A complementary statistical explanation is that AdaBoost minimizes a convex loss stagewise with small late steps ( implies ), acting as implicit regularization. Neither guarantees it never overfits, as the next section shows.
Label noise
Reweighting has a dark side. A mislabeled example (fraud marked legitimate, a wrongly annotated image) lies on the wrong side of any reasonable boundary. AdaBoost misclassifies it round after round, each time multiplying its weight by : after errors its relative weight against an always-correct example grows by . In loss terms its contribution grows exponentially with the vote’s confidence in its true class. The algorithm eventually spends rounds explaining a few impossible points, twisting the boundary around them.
Dietterich (2000) documented this with C4.5: without noise boosting was best of three methods; with substantial classification noise bagging was much better. Is exponential loss to blame? The obvious answer is logistic loss with bounded gradient. The next figure tests that answer.
With the figure shows three things. AdaBoost reaches best error early then worsens: enough rounds with noise cause overfitting. Noisy points command much more pull than their fraction and appear as the largest points deep in the other class’s region. Counterintuitively, unclipped LogitBoost behaves much like AdaBoost. Only the clipped version resists. Measure over several seeds, first changing only loss in the prior stagewise procedure.
print("ruido pérdida err.test t=10 t=30 t=100 t=300 mínimo (ronda) peso en ruidosos t=300")
for rho in (0.1, 0.2):
res = {"exponencial": [], "logística": []}
for semilla in range(3):
g = np.random.default_rng(100 + semilla)
Xr, yr = circulo(300, g); Xr_te, yr_te = circulo(10000, g)
ruido = g.random(300) < rho # se invierten estas etiquetas de entrenamiento
yr_ruido = np.where(ruido, -yr, yr)
for p in res: # el test se mide con las etiquetas limpias
res[p].append(por_etapas(Xr, yr_ruido, p, 300, Xr_te, yr_te, ruido)[1:])
for p in res:
e = np.mean([r[0] for r in res[p]], axis=0); c = np.mean([r[1] for r in res[p]], axis=0)
print(f"{rho:.1f} {p:12s} {e[9]:.3f} {e[29]:.3f} {e[99]:.3f} {e[299]:.3f} {e.min():.3f} ({e.argmin() + 1:3d}) {c[299]:.2f}")With and exponential loss, mean true error across three seeds falls to minimum at round 56 then rises to at 300; noisy points, 20 % of the sample, receive 39 % of weight. Logistic is almost identical: minimum , at round 300, and 39 % of weight. Changing loss within the same scheme does not protect.
The reason is relative weights. A noisy point deep in the other class’s region has margin with , and clean neighbors roughly margin . Under exponential loss its weight relative to a neighbor is . Under scaled logistic weights are : the noisy point weighs nearly 2 and the neighbor nearly , again ratio . The logistic gradient bound equalizes misclassified points among themselves; relative to correctly classified points, both losses concentrate weight similarly because both penalize large positive margins exponentially.
LogitBoost and the clipping that saves it
Besides the statistical interpretation, Friedman, Hastie and Tibshirani proposed a logistic-loss algorithm using Newton steps instead of line search: LogitBoost. Each round, with and , compute working response and weights
fit a regression function (here a stump with real-valued leaves) to by weighted least squares and update . This is a Newton step on log-likelihood, like logistic-regression IRLS, restricted to stumps. Since , each point’s pull in fitting is proportional to its logistic gradient and bounded by 1.
The decisive detail is an implementation note. For a point with near 0 or 1, explodes, and the authors recommended bounding by for numerical stability (summarized by Li (2010), who studies instability). Clipping changes the pull of a hopeless point with and : from to . Pull of points the model confidently misclassifies switches off, precisely what convex loss cannot do.
def tocon_regresion(B, z, w):
"""Tocón de regresión por mínimos cuadrados ponderados: hojas = medias ponderadas de z."""
W = np.vstack([np.zeros(B.orden.shape[1]), np.cumsum(w[B.orden], axis=0)])
S = np.vstack([np.zeros(B.orden.shape[1]), np.cumsum((w * z)[B.orden], axis=0)])
Wt, St = W[-1], S[-1]
with np.errstate(divide="ignore", invalid="ignore"):
g = S ** 2 / W + (St - S) ** 2 / (Wt - W)
g[~B.valido | (W <= 0) | (Wt - W <= 0)] = -np.inf
k, j = np.unravel_index(np.argmax(g), g.shape)
return j, B.umbral[k, j], S[k, j] / W[k, j], (St[j] - S[k, j]) / (Wt[j] - W[k, j])
def logitboost(X, y, T, X_te, y_te, ruido, zmax=np.inf):
"""Friedman, Hastie y Tibshirani (2000), algoritmo 3, con tocones de regresión."""
B = Tocones(X); F = np.zeros(len(y)); F_te = np.zeros(len(X_te)); y01 = (y + 1) / 2
err, cuota = [], []
for t in range(T):
p = 1 / (1 + np.exp(-2 * F))
w = np.maximum(p * (1 - p), 1e-15)
z = np.clip((y01 - p) / w, -zmax, zmax) # respuesta de trabajo, truncada en ±zmax
j, u, ci, cd = tocon_regresion(B, z, w)
F += 0.5 * np.where(X[:, j] > u, cd, ci)
F_te += 0.5 * np.where(X_te[:, j] > u, cd, ci)
tiron = np.abs(w * z) # lo que cada punto empuja al ajuste
err.append(np.mean(np.sign(F_te) != y_te)); cuota.append(tiron[ruido].sum() / tiron.sum())
return np.array(err), np.array(cuota)
print("ruido método err.test t=10 t=30 t=100 t=300 mínimo (ronda) tirón de ruidosos t=30")
for rho in (0.1, 0.2):
res = {}
for semilla in range(3):
g = np.random.default_rng(100 + semilla)
Xr, yr = circulo(300, g); Xr_te, yr_te = circulo(10000, g)
ruido = g.random(300) < rho
yr_ruido = np.where(ruido, -yr, yr)
res.setdefault("AdaBoost", []).append(por_etapas(Xr, yr_ruido, "exponencial", 300, Xr_te, yr_te, ruido)[1:])
for zm in (np.inf, 4, 2):
res.setdefault(f"LogitBoost zmax={zm:g}", []).append(logitboost(Xr, yr_ruido, 300, Xr_te, yr_te, ruido, zm))
for k in res:
e = np.mean([r[0] for r in res[k]], axis=0); c = np.mean([r[1] for r in res[k]], axis=0)
print(f"{rho:.1f} {k:20s} {e[9]:.3f} {e[29]:.3f} {e[99]:.3f} {e[299]:.3f} {e.min():.3f} ({e.argmin() + 1:3d}) {c[29]:.2f}")
# los pesos de AdaBoost como detector de etiquetas erróneas (ρ = 0.2, primera semilla)
g = np.random.default_rng(100)
Xr, yr = circulo(300, g); _ = circulo(10000, g)
ruido = g.random(300) < 0.2
yr_ruido = np.where(ruido, -yr, yr)
F100 = adaboost(Xr, yr_ruido, 100)["F"]
mayores = np.argsort(-np.exp(-yr_ruido * F100))[:30] # los 30 ejemplos de más peso tras 100 rondas
print(f"\netiquetas invertidas: {ruido.mean():.0%} de la muestra, {ruido[mayores].mean():.0%} de los 30 ejemplos de más peso")The numbers separate explanations. With , unclipped LogitBoost ends at after 300 rounds, worse than AdaBoost (), and by round 30 its noisy points, 10 % of the sample, exert 37 % of pull (AdaBoost 25 %). Clipping at reduces noisy pull to 21 % and final error to , minimum . With the pattern repeats: unclipped, with . Robustness comes not from logistic loss but clipping making pull of worst-misclassified points tend to zero, like the gradient of bounded nonconvex loss. Even that version is not immune: with error rises from minimum to .
Convex loss being insufficient is no accident. Long and Servedio (2010) proved random classification noise defeats any convex-potential booster: they built distributions easy to learn without noise where, with arbitrarily small random noise, every such algorithm ends with a classifier no better than chance. Effective remedies differ:
- Stop early. Every curve’s minimum arrives in tens of rounds; choose by validation, boosting early stopping, the simplest remedy used by all libraries. Bartlett and Traskin (2007) proved AdaBoost consistent when stopped after rounds, for any .
- Bound influence. Nonconvex losses whose gradient vanishes for very negative margins, such as Freund’s (2001) BrownBoost, or soft-margin SVM-style soft margins such as AdaBoost by Rätsch, Onoda and Müller (2001).
- Shrink steps. Multiply each by factor and subsample, the two regularizers of next lesson’s gradient boosting.
Variants: Real AdaBoost and SAMME
Real AdaBoost. Discrete AdaBoost discards information: a stump whose right leaf is 90 % positive and one at 55 % vote equally, , distinguished only by per learner. Schapire and Singer (1999) allowed real-valued learners , sign as prediction and magnitude as confidence. The training-error proof repeats unchanged through step 2: for any real and , training error is at most with . So each round choose minimizing . For a stump with leaves and , if is class weight in the left leaf and leaf value is ,
Each leaf votes half its weighted log-odds and the split minimizes , Schapire and Singer’s criterion. The leaf rule is Friedman, Hastie and Tibshirani’s Real AdaBoost, derived as stagewise exponential modeling with real learners: minimizer of is , the statistical-section formula applied to the weighted distribution, and in a leaf is estimated by . You will implement it in the code exercise.
SAMME. With classes, condition is too demanding: with , 40 % accuracy beats chance (10 %) but AdaBoost would reject it. Zhu, Zou, Rosset and Hastie (2009) proposed SAMME (stagewise additive modeling using a multi-class exponential loss), changing one line:
The vote is positive if and only if , i.e. beats random guessing among classes. With , is twice AdaBoost’s and reweighting multiplies only errors by , giving the same normalized distribution: a common factor does not change the vote. The authors prove SAMME is stagewise modeling with multiclass exponential loss whose population minimizer again gives the Bayes rule.
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.ensemble import AdaBoostClassifier
from sklearn.tree import DecisionTreeClassifier
def sectores(n, rng, K):
"""K clases: el sector angular de 360°/K en el que cae x (x uniforme en [-1, 1]^2)."""
X = rng.uniform(-1, 1, size=(n, 2))
ang = np.mod(np.arctan2(X[:, 1], X[:, 0]), 2 * np.pi)
return X, np.minimum((ang // (2 * np.pi / K)).astype(int), K - 1)
class ToconesK(Tocones):
def ajustar(self, y, w, K):
"""Tocón multiclase: cada lado predice su clase de más peso. Devuelve (j, u, clase_izq, clase_der, error)."""
Y = np.eye(K)[y] * w[:, None] # n x K, pesos por clase
acum = np.vstack([np.zeros((1, self.orden.shape[1], K)), np.cumsum(Y[self.orden], axis=0)])
total = acum[-1]
acierto = acum.max(axis=2) + (total[None] - acum).max(axis=2) # peso bien clasificado de cada corte
acierto[~self.valido] = -1
k, j = np.unravel_index(np.argmax(acierto), acierto.shape)
return j, self.umbral[k, j], int(acum[k, j].argmax()), int((total[j] - acum[k, j]).argmax()), 1 - acierto[k, j]
def samme(X, y, K, T):
n = len(y); buscador = ToconesK(X); w = np.full(n, 1 / n); modelo = []
for t in range(T):
j, u, ci, cd, err = buscador.ajustar(y, w, K)
h = np.where(X[:, j] > u, cd, ci)
alfa = np.log((1 - err) / err) + np.log(K - 1) # SAMME: basta err < 1 - 1/K
w = w * np.exp(alfa * (h != y)); w /= w.sum()
modelo.append((alfa, j, u, ci, cd, err))
return modelo
def samme_predict(modelo, X, K):
votos = np.zeros((len(X), K))
for alfa, j, u, ci, cd, _ in modelo:
votos[np.arange(len(X)), np.where(X[:, j] > u, cd, ci)] += alfa
return votos.argmax(axis=1)
rng3 = np.random.default_rng(1)
K = 3
X3, y3 = sectores(300, rng3, K); X3_te, y3_te = sectores(20000, rng3, K)
mod = samme(X3, y3, K, 100)
errs = np.array([m[5] for m in mod])
print(f"error ponderado de los tocones: primero {errs[0]:.3f}, máximo {errs.max():.3f} (umbral 1 - 1/K = {1 - 1/K:.3f})")
for T in (1, 10, 100):
print(f"T = {T:3d}: error de test {np.mean(samme_predict(mod[:T], X3_te, K) != y3_te):.4f}")
class ToconK(ClassifierMixin, BaseEstimator):
"""El mismo tocón multiclase, con la interfaz de un estimador de scikit-learn."""
def fit(self, X, y, sample_weight=None):
self.classes_ = np.unique(y)
w = sample_weight / sample_weight.sum()
self.j_, self.u_, self.ci_, self.cd_, _ = ToconesK(X).ajustar(np.searchsorted(self.classes_, y), w, len(self.classes_))
return self
def predict(self, X):
return self.classes_[np.where(X[:, self.j_] > self.u_, self.cd_, self.ci_)]
sk3 = AdaBoostClassifier(ToconK(), n_estimators=60).fit(X3, y3)
print("pesos de AdaBoostClassifier frente a los nuestros, máx. diferencia:",
np.abs(sk3.estimator_weights_ - np.array([m[0] for m in mod[:60]])).max())With three sectors of , first-stump weighted error is and none of 100 exceeds , far from threshold ; test error falls from with one stump to with 10 and with 100. Wrapping our stump in scikit-learn’s interface, AdaBoostClassifier reproduces our within , floating-point rounding: it implements SAMME exactly.
scikit-learn AdaBoostClassifier
The professional version is sklearn.ensemble.AdaBoostClassifier. Its few parameters: estimator (base learner; default DecisionTreeClassifier(max_depth=1), a stump), n_estimators (round count , default 50), and learning_rate (factor multiplying each ; with it is noise-section shrinkage). Current versions implement only SAMME; real variant SAMME.R was removed in version 1.6. Check on the circle that with two classes it is our AdaBoost.
class ToconPonderado(ClassifierMixin, BaseEstimator):
"""El tocón de mínimo error ponderado de la primera celda, con la interfaz de scikit-learn."""
def fit(self, X, y, sample_weight=None):
self.classes_ = np.unique(y)
w = np.full(len(y), 1 / len(y)) if sample_weight is None else sample_weight / sample_weight.sum()
self.j_, self.u_, self.s_, _ = Tocones(X).ajustar(np.where(y == self.classes_[1], 1, -1), w)
return self
def predict(self, X):
return np.where(tocon(X, self.j_, self.u_, self.s_) > 0, self.classes_[1], self.classes_[0])
T = 60
sk = AdaBoostClassifier(ToconPonderado(), n_estimators=T).fit(X, y)
print("pesos de scikit-learn / 2 frente a nuestros α_t: máx. diferencia",
np.abs(sk.estimator_weights_ / 2 - reg["alfa"][:T]).max())
f_T = sum(a * tocon(X, *tc) for a, tc in zip(reg["alfa"][:T], reg["tocon"][:T]))
print("decision_function de scikit-learn = 2 f(x) / Σα:", np.allclose(sk.decision_function(X), 2 * f_T / reg["alfa"][:T].sum()))
gini = AdaBoostClassifier(DecisionTreeClassifier(max_depth=1), n_estimators=T).fit(X, y)
e0 = gini.estimators_[0].tree_
print(f"primer tocón: el nuestro corta x{reg['tocon'][0][0] + 1} en {reg['tocon'][0][1]:.3f}; el de Gini, x{e0.feature[0] + 1} en {e0.threshold[0]:.3f}")
for nombre, m in [("tocón por error ponderado", sk), ("tocón por Gini ponderado", gini)]:
print(f"{nombre:26s} error de test tras {T} rondas: {np.mean(m.predict(X_te) != y_te):.4f}")Three details. First, estimator_weights_ stores (SAMME with ), matching twice our to . Second, decision_function returns not but : twice normalized margin, in . Third, the default stump minimizes weighted Gini, not weighted error, so chooses different splits (the first splits at rather than ) and the entire sequence changes; after 60 rounds test error is versus our . AdaBoost only requires learner advantage; obtaining it is the learner’s job.
Choose n_estimators and learning_rate with cross-validated hyperparameter search and staged_predict, giving predictions after each round without retraining. In practice AdaBoost has ceded ground to next lesson’s gradient boosting and second-order implementations, incorporating shrinkage, subsampling, regularization and arbitrary losses.
Typical mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. What pointwise inequality replaces ?
Step 1 of 3. What is the conditional expectation?
real_adaboost_fit(X, y, T, suave=1e-6) with y in . In each round with weights : choose feature and threshold (midpoint between consecutive distinct values) minimizing ; put in each leaf; and reweight . Return (tocones, Z), where tocones[t] = (j, u, c_izq, c_der) ( if ) and Z[t] is normalizer . Tests check criterion, leaves, normalizers, and that training error never exceeds in any round.import numpy as np
def real_adaboost_fit(X, y, T, suave=1e-6):
"""Real AdaBoost con tocones. Devuelve (tocones, Z): tocones[t] = (j, u, c_izq, c_der),
con h_t(x) = c_der si x[j] > u y c_izq si no; Z[t] = suma de D_t(i) exp(-y_i h_t(x_i))."""
n, d = X.shape
D = np.full(n, 1 / n)
tocones, Z = [], []
for t in range(T):
# tu código: elige (j, u) que minimiza 2 * sum_hojas sqrt(W+ W-),
# pon en cada hoja 0.5 * log((W+ + suave) / (W- + suave)) y repondera
pass
return tocones, ZSummary
- A weak learner has advantage over chance for any data weighting. AdaBoost uses and , leaving at error exactly .
- Training error is bounded by : weak implies strong on the sample.
- AdaBoost is stagewise additive modeling with exponential loss and, equivalently, coordinate descent with exact line search over the learner dictionary. In population it estimates , but its vote is not a calibrated probability.
- Test error can keep falling after training error reaches 0 because AdaBoost raises small margins; the margin bound does not depend on but is qualitative, and maximizing the minimum margin alone is insufficient (arc-gv).
- With noisy labels AdaBoost concentrates weight on impossible examples and overfits. Another convex loss alone does not fix it; early stopping, shrinking steps or suppressing hopeless-point influence, as LogitBoost clipping does, can.
- Real AdaBoost uses real-valued learners and selects each by minimizing ; SAMME extends AdaBoost to classes by adding to the vote, and is what
AdaBoostClassifierimplements.