Module contents
Lesson 16 of 24Core 95 min

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 1/2−γ1/2 - \gamma for fixed, perhaps tiny γ>0\gamma > 0. 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 γ\gamma in advance. The version used today is Freund and Schapire (1997): AdaBoost, adaptive boosting, which need not know γ\gamma 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 0.40.4 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, y=sign⁡(x1x2)y = \operatorname{sign}(x_1 x_2): 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 DtD_t 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 yiht(xi)=+1y_i h_t(\vb{x}_i) = +1 when hth_t is correct and −1-1 when wrong, reweighting multiplies correct cases by e−αte^{-\alpha_t} and mistakes by eαte^{\alpha_t}: a mistake’s weight relative to a correct case grows by e2αt=(1−εt)/εte^{2\alpha_t} = (1 - \varepsilon_t)/\varepsilon_t. Vote αt\alpha_t is positive exactly when εt<1/2\varepsilon_t < 1/2, grows unbounded as εt→0\varepsilon_t \to 0 and is zero when hth_t is no better than chance. If some hth_t had εt>1/2\varepsilon_t > 1/2, αt\alpha_t would be negative and the vote would use −ht-h_t, which is better than chance.

Proof

Before normalization, mistakes weigh εteαt=εt(1−εt)/εt=εt(1−εt)\varepsilon_t e^{\alpha_t} = \varepsilon_t\sqrt{(1-\varepsilon_t)/\varepsilon_t} = \sqrt{\varepsilon_t(1-\varepsilon_t)} and correct cases (1−εt)e−αt=εt(1−εt)(1 - \varepsilon_t)e^{-\alpha_t} = \sqrt{\varepsilon_t(1-\varepsilon_t)}. They weigh equally, so after normalization each group weighs 1/21/2, and Zt=2εt(1−εt)Z_t = 2\sqrt{\varepsilon_t(1-\varepsilon_t)}.

∎

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.

InteractiveAdaBoost round by round
Weights D1D_{1} and h1h_{1} split; background: vote of 0 learners
ronda 1 · ajustar
  • class +1
  • class −1
  • hth_t split (ringed: its errors)
  • true boundary
Errors, bounds and εt\varepsilon_t versus round
azar
  • training error
  • true error
  • ∏2ε(1−ε)\prod 2\sqrt{\varepsilon(1-\varepsilon)}
  • e−2∑γ2e^{-2\sum\gamma^2}
  • εt\varepsilon_t
Problem
Base learner
round 1, fit
Round tt1 of 100
Weighted error εt\varepsilon_t0.288
Edge γt=1/2−εt\gamma_t = 1/2 - \varepsilon_t0.212
Vote αt\alpha_t0.454
Training error of the vote−
Bound ∏t2εt(1−εt)\prod_t 2\sqrt{\varepsilon_t(1-\varepsilon_t)}1
True error of the vote−
Round 1: all points weigh 1/801/80. The learner fits with those weights and misses the ringed points, totaling ε1=0.288\varepsilon_1 = 0.288. Advance one step to reweight.
80 points in [−1,1]2[-1, 1]^2, class +1+1 (orange) inside the dashed circle. Each point’s area is its weight. Each round has two steps: in ‘ajustar’ (fit) see learner hth_t’s split and circled errors; in ‘reponderar’ (reweight), errors grow to half the total weight. Background is accumulated vote, stronger for larger ∣f∣/∑α\abs{f}/\sum\alpha. At right training error falls below the dashed bound while εt\varepsilon_t rises toward 1/21/2. Try XOR with stumps then depth-2 trees: in the latter case wait for a perfect tree.

Three things the figure shows and the rest of the lesson explains:

  1. Training error falls rapidly, but εt\varepsilon_t 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.
  2. For the circle, a sum of stumps approximates the boundary by a staircase. Vote ff sums step functions of x1x_1 and x2x_2: a feature-additive model. This suffices for the circle, whose class is exactly sign⁡(g1(x1)+g2(x2))\operatorname{sign}\big(g_1(x_1) + g_2(x_2)\big) with gj(xj)=r2/2−xj2g_j(x_j) = r^2/2 - x_j^2, but not XOR. Term r2r^2 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.
  3. With XOR and stumps training error falls, but true error does not. A finite sample always has a split with weighted error slightly below 1/21/2, so AdaBoost advances by memorization with tiny γt\gamma_t. Depth-2 trees make XOR easy; with initial data, at round 74 a tree separates all 80 points: εt=0\varepsilon_t = 0, αt=∞\alpha_t = \infty and AdaBoost stops.

The base learner: weighted stumps

A stump is h(x)=sh(\vb{x}) = s if xj>ux_j > u and −s-s otherwise, with jj a feature, uu a threshold and s∈{−1,+1}s \in \{-1, +1\}. To choose with weights use advantage r(h)=∑iD(i) yih(xi)r(h) = \sum_i D(i)\, y_i h(\vb{x}_i), related to weighted error by r=(1−ε)−ε=1−2εr = (1 - \varepsilon) - \varepsilon = 1 - 2\varepsilon, i.e. γ=r/2\gamma = r/2. Minimizing ε\varepsilon maximizes ∣r∣\abs{r} (the sign of rr fixes ss).

Sort examples by xjx_j and let ckc_k sum D(i) yiD(i)\,y_i over the first kk. A split after the kk-th predicts −1-1 left and +1+1 right, with advantage (total−ck)−ck=total−2ck(\text{total} - c_k) - c_k = \text{total} - 2c_k; cases k=0k = 0 and k=nk = n are constant stumps. A cumulative sum gives all splits for a feature at once: after one initial sort (O(dnlog⁡n)\bigO(dn\log n)), each round costs O(dn)\bigO(dn). 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 TT times from D1(i)=1/nD_1(i) = 1/n,

DT+1(i)=1n e−α1yih1(xi)⋯e−αTyihT(xi)Z1⋯ZT=e−yif(xi)n∏tZt.D_{T+1}(i) = \frac{1}{n}\,\frac{e^{-\alpha_1 y_i h_1(\vb{x}_i)}\cdots e^{-\alpha_T y_i h_T(\vb{x}_i)}}{Z_1\cdots Z_T} = \frac{e^{-y_i f(\vb{x}_i)}}{n\prod_t Z_t}.

Since DT+1D_{T+1} sums to 1, 1n∑ie−yif(xi)=∏tZt\frac1n\sum_i e^{-y_i f(\vb{x}_i)} = \prod_t Z_t: the product of normalizers is exactly the vote’s mean exponential loss.

Step 2: 0–1 is below exponential. If H(xi)≠yiH(\vb{x}_i) \neq y_i, then yif(xi)≤0y_i f(\vb{x}_i) \le 0 and e−yif(xi)≥1e^{-y_i f(\vb{x}_i)} \ge 1; otherwise e−yif(xi)>0e^{-y_i f(\vb{x}_i)} > 0. Thus 1[H(xi)≠yi]≤e−yif(xi)\ind[H(\vb{x}_i) \neq y_i] \le e^{-y_i f(\vb{x}_i)} for every ii and, averaging,

1n∑i1[H(xi)≠yi]≤1n∑ie−yif(xi)=∏tZt.\frac1n\sum_i \ind[H(\vb{x}_i) \neq y_i] \le \frac1n\sum_i e^{-y_i f(\vb{x}_i)} = \prod_t Z_t .

Step 3: each ZtZ_t value. Separating correct cases and errors gives Zt=(1−εt)e−αt+εteαtZ_t = (1 - \varepsilon_t)e^{-\alpha_t} + \varepsilon_t e^{\alpha_t}, which with AdaBoost’s αt\alpha_t equals 2εt(1−εt)2\sqrt{\varepsilon_t(1-\varepsilon_t)} (as in the preceding proposition). With εt=12−γt\varepsilon_t = \tfrac12 - \gamma_t, 4εt(1−εt)=(1−2γt)(1+2γt)=1−4γt24\varepsilon_t(1-\varepsilon_t) = (1 - 2\gamma_t)(1 + 2\gamma_t) = 1 - 4\gamma_t^2.

Step 4: exponential. For all x∈Rx \in \R, 1+x≤ex1 + x \le e^x; with x=−4γt2x = -4\gamma_t^2, 1−4γt2≤e−4γt2=e−2γt2\sqrt{1 - 4\gamma_t^2} \le \sqrt{e^{-4\gamma_t^2}} = e^{-2\gamma_t^2}. Multiplying over tt gives the last inequality.

∎

Step 3 hides another interpretation of αt\alpha_t. Function Zt(α)=(1−εt)e−α+εteαZ_t(\alpha) = (1 - \varepsilon_t)e^{-\alpha} + \varepsilon_t e^{\alpha} is convex and its derivative −(1−εt)e−α+εteα-(1-\varepsilon_t)e^{-\alpha} + \varepsilon_t e^{\alpha} vanishes at e2α=(1−εt)/εte^{2\alpha} = (1-\varepsilon_t)/\varepsilon_t: AdaBoost’s αt\alpha_t minimizes ZtZ_t, 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 γt≥γ\gamma_t \ge \gamma, training error falls below 1/n1/n and is exactly 0 once e−2γ2T<1/ne^{-2\gamma^2 T} < 1/n, i.e. after T>log⁡n2γ2T > \frac{\log n}{2\gamma^2} 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 hth_t: only sequence γt\gamma_t. Any weight-aware learner can be used.
  • A bound is not a prediction. The product is usually far above actual error because 1[m≤0]≤e−m\ind[m \le 0] \le e^{-m} 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.

[ ]AdaBoost from scratch with stumpsBrowser
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 0.1300.130. The inequality holds for all 400 rounds, ∏Zt\prod Z_t matches ∏2εt(1−εt)\prod 2\sqrt{\varepsilon_t(1-\varepsilon_t)} and each hth_t error under next weights is exactly 0.50.5, as stated. The bound slows because of εt\varepsilon_t: its mean falls from 0.3550.355 in the first ten rounds to 0.4490.449 in rounds 301–400. As weights concentrate on hard points, best-stump advantage shrinks.

Notice test error too: from 40.0 %40.0\,\% with one stump to 3.79 %3.79\,\% at rounds 100 and 200, and 4.11 %4.11\,\% 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 1n∑ie−yif(xi)\frac1n\sum_i e^{-y_i f(\vb{x}_i)}. 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.

∑ie−yiFm(xi)=∑iwi e−βyib(xi)\sum_i e^{-y_i F_m(\mathbf{x}_i)} = \sum_i w_i\, e^{-\beta y_i b(\mathbf{x}_i)}
With Fm=Fm−1+βbF_m = F_{m-1} + \beta b and wi=e−yiFm−1(xi)w_i = e^{-y_i F_{m-1}(\mathbf{x}_i)}: already-fitted terms enter only as fixed example weights, independent of β\beta and bb.
1/6

The equivalence has a fundamental consequence: AdaBoost estimates something. Exponential loss e−yFe^{-yF} is a classification loss expressed in margin yFyF, a convex differentiable upper bound on 0–1, and its population minimizer, as seen in the functional elicited by each loss lesson, is

F∗(x)=arg min⁡FE[e−YF∣x]=12log⁡p(x)1−p(x),p(x)=P(Y=1∣x),F^*(\vb{x}) = \argmin_F \E\big[e^{-YF} \given \vb{x}\big] = \frac12 \log\frac{p(\vb{x})}{1 - p(\vb{x})}, \qquad p(\vb{x}) = \Pr(Y = 1 \given \vb{x}),

Half the log-odds (you will prove it in an exercise). Therefore sign⁡F∗\operatorname{sign} F^* is the Bayes rule and, at least in population, p(x)=1/(1+e−2F∗(x))p(\vb{x}) = 1/(1 + e^{-2F^*(\vb{x})}). Scaled logistic loss log⁡(1+e−2yF)\log(1 + e^{-2yF}) has the same minimizer and, up to an additive constant, matches exponential to second order at yF=0yF = 0 (both equal c−yF+(yF)2/2+…c - yF + (yF)^2/2 + \dots): they resemble each other near the boundary and separate on badly misclassified examples with very negative margins, where exponential grows like e∣yF∣e^{\abs{yF}} and logistic only like 2∣yF∣2\abs{yF}. This difference returns with noise.

Coordinate descent over a learner dictionary

Another view connects to the next lesson. If possible learners are finite (with nn points there are at most 2d(n+1)2d(n+1) distinct stumps on the sample), h(1),…,h(K)h^{(1)}, \dots, h^{(K)}, every vote is f=∑kλkh(k)f = \sum_k \lambda_k h^{(k)} and exponential loss is a convex function of λ∈RK\vb{\lambda} \in \R^K:

L(λ)=1n∑i=1nexp⁡(−yi∑kλkh(k)(xi)),∂L∂λk=−1n∑ie−yif(xi) yih(k)(xi)=−c (1−2εk),L(\vb{\lambda}) = \frac1n\sum_{i=1}^n \exp\Big(-y_i \sum_k \lambda_k h^{(k)}(\vb{x}_i)\Big), \qquad \pd{L}{\lambda_k} = -\frac1n\sum_i e^{-y_i f(\vb{x}_i)}\, y_i h^{(k)}(\vb{x}_i) = -c\,\big(1 - 2\varepsilon_k\big),

with c=1n∑ie−yif(xi)>0c = \frac1n\sum_i e^{-y_i f(\vb{x}_i)} > 0 and εk\varepsilon_k the weighted error of h(k)h^{(k)} under current weights. Choosing the minimum weighted-error learner chooses the coordinate with most negative partial derivative, and setting αt\alpha_t 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 inf⁡L=0\inf L = 0, the infimum is unattained, and ∥λ∥1=∑tαt\norm{\vb{\lambda}}_1 = \sum_t \alpha_t grows without bound. Training error reaches 0 and loss keeps falling as margins yif(xi)y_i f(\vb{x}_i) grow: thereafter λ\vb{\lambda}’s direction, not size, matters. Rosset, Zhu and Hastie (2004) proved infinitesimal-step boosting approximately follows the ℓ1\ell_1-regularized exponential path, converging to the maximum-ℓ1\ell_1-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.

[ ]Generic stagewise modelingBrowser
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 αt\alpha_t up to floating-point rounding, and stumps match because weights −ℓ′(mi)=e−mi-\ell'(m_i) = e^{-m_i} are AdaBoost’s. With logistic, weights become 2/(1+e2mi)2/(1 + e^{2m_i}), 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: yif(xi)y_i f(\vb{x}_i) 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-dd class, with probability at least 1−δ1 - \delta over a sample of size nn, for every vote ff and every θ>0\theta > 0,

Ptest[yf(x)≤0]  ≤  P^[ρ≤θ]+O ⁣(1n(dlog⁡2(n/d)θ2+log⁡1δ)1/2),\Pr_{\text{test}}\big[y f(\vb{x}) \le 0\big] \;\le\; \hat{P}\big[\rho \le \theta\big] + \bigO\!\left(\frac{1}{\sqrt n}\left(\frac{d \log^2(n/d)}{\theta^2} + \log\frac1\delta\right)^{1/2}\right),

where P^[ρ≤θ]\hat{P}[\rho \le \theta] is the fraction of training examples with normalized margin at most θ\theta. Notably absent is round count TT. Complexity is measured by dd, that of one base learner, and its term is paid with 1/θ21/\theta^2. 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 θ=0\theta = 0 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.

InteractiveThe margin distribution
Cumulative distribution of normalized margins ρi=yif(xi)/∑tαt\rho_i = y_i f(\mathbf{x}_i)/\sum_t\alpha_t for 500 training examples
9.8 %mal clasificados
  • 5 rounds
  • 50 rounds
  • 500 rounds
  • 1000 rounds
Training and test error versus number of rounds (log axis)
entrenamiento = 0 (t = 128)test 14.1 %
  • training error
  • test error
Highlight
0.050
Margin axis
Training error0.0 %
Test error14.50 %
Minimum margin0.032
P^(ρ≤θ)\hat P(\rho \le \theta)9.8 %
Bound ∏t2εt1−θ(1−εt)1+θ\prod_t 2\sqrt{\varepsilon_t^{1-\theta}(1-\varepsilon_t)^{1+\theta}}36.33 %
First round with zero training error128
After 500 rounds training error has been zero since round 128, but the vote keeps changing: minimum margin is 0.032 and only 9.8 % of examples have ρ≤0.050\rho \le 0.050. Test error is 14.5 % (at round 128 it was 16.8 %).
ESL nested spheres (equation 10.2): x∼N(0,I10)\vb{x} \sim \Normal(\vb{0}, \mat{I}_{10}), class +1+1 if ∥x∥2\norm{\vb{x}}^2 exceeds the median of χ102\chi^2_{10}. AdaBoost with depth-2 trees on 500 examples, 1000 rounds. Above, normalized-margin cumulative distributions after 5, 50, 500 and 1000 rounds; below, errors versus rounds. Highlight 500 and 1000: training error is already 0, but the left tail keeps moving right and test error keeps falling. Move θ\theta and compare fraction of margins ≤θ\le \theta with the theorem’s bound: at what θ\theta does it stop being informative?

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.

[ ]Margins after zero training errorBrowser
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 15.46 %15.46\,\%. Thereafter training says nothing, yet test improves: 14.62 %14.62\,\% at round 200, 13.86 %13.86\,\% at 500 and 13.70 %13.70\,\% at 1000. Margins do change. The minimum rises from +0.001+0.001 to +0.042+0.042 and fraction with ρ≤0.05\rho \le 0.05 drops from 0.1840.184 to 0.1160.116. But the last columns show fraction with ρ≤0.1\rho \le 0.1 rises from 0.5860.586 to 0.7880.788 and median falls from 0.0890.089 to 0.0680.068. 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 θ\theta 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 0.360.36 at θ=0.05\theta = 0.05, where actual fraction is 0.0980.098, and exceeds 1 between θ=0.05\theta = 0.05 and θ=0.08\theta = 0.08, when εt\varepsilon_t is already around 0.460.46.

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 (εt→1/2\varepsilon_t \to 1/2 implies αt→0\alpha_t \to 0), 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 eαte^{\alpha_t}: after kk errors its relative weight against an always-correct example grows by e2∑αe^{2\sum\alpha}. In loss terms its contribution e−yif(xi)e^{-y_i f(\vb{x}_i)} 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.

InteractiveAdaBoost versus noise
AdaBoost (exponencial): pull of each point after 100 rounds
  • label +1
  • label −1
  • ring: flipped label
True error versus rounds (log axis)
Fraction of total pull exerted by noisy points
if all pulled equally
  • AdaBoost (exponencial)
  • LogitBoost sin truncar (logística)
  • LogitBoost con |z| ≤ 2
20 %
Method (point panel)
After
Flipped labels59 of 300
True error after 100 rounds20.6 %
Minimum (round)14.1 % (35)
Total pull of noisy points36.8 %
Fraction noisy (uniform pull)19.7 %
With 59 flipped labels (20 %), AdaBoost drops to 14.1 % at round 35 and rises to 21.7 % by round 300. Unclipped LogitBoost with logistic loss ends at 20.9 %: changing convex loss is not enough. Clipping ∣z∣≤2|z| \le 2 dampens the pull of hopeless points and ends at 13.6 %.
300 circle-problem points; labels are flipped for fraction ρ\rho (rings). Curves show true error against clean labels for AdaBoost (exponential loss), LogitBoost (logistic loss) and LogitBoost with working response clipped at ∣z∣≤2\abs{z} \le 2, all with stumps; dots mark curve minima. Below: fraction of total pull exerted by noisy points; dotted line shows equal pull. In the point panel each area is its pull in the selected round. Raise ρ\rho and compare curves after 100 and 300 rounds.

With ρ=20 %\rho = 20\,\% 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.

[ ]Exponential versus logistic loss with noiseBrowser
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 ρ=0.2\rho = 0.2 and exponential loss, mean true error across three seeds falls to minimum 0.1110.111 at round 56 then rises to 0.1590.159 at 300; noisy points, 20 % of the sample, receive 39 % of weight. Logistic is almost identical: minimum 0.1070.107, 0.1530.153 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 m=−am = -a with a>0a > 0, and clean neighbors roughly margin +a+a. Under exponential loss its weight relative to a neighbor is ea/e−a=e2ae^{a}/e^{-a} = e^{2a}. Under scaled logistic weights are −ℓ′(m)=2/(1+e2m)-\ell'(m) = 2/(1 + e^{2m}): the noisy point weighs nearly 2 and the neighbor nearly 2e−2a2e^{-2a}, again ratio e2ae^{2a}. 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 pi=1/(1+e−2F(xi))p_i = 1/(1 + e^{-2F(\vb{x}_i)}) and yi∗=(yi+1)/2∈{0,1}y_i^* = (y_i + 1)/2 \in \{0, 1\}, compute working response and weights

zi=yi∗−pipi(1−pi),wi=pi(1−pi),z_i = \frac{y_i^* - p_i}{p_i(1 - p_i)}, \qquad w_i = p_i(1 - p_i),

fit a regression function (here a stump with real-valued leaves) to ziz_i by weighted least squares and update F←F+12hF \leftarrow F + \frac12 h. This is a Newton step on log-likelihood, like logistic-regression IRLS, restricted to stumps. Since wizi=yi∗−piw_i z_i = y_i^* - p_i, 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 pip_i near 0 or 1, ziz_i explodes, and the authors recommended bounding ∣zi∣≤zmax⁡\abs{z_i} \le z_{\max} by zmax⁡∈[2,4]z_{\max} \in [2, 4] for numerical stability (summarized by Li (2010), who studies instability). Clipping changes the pull of a hopeless point with yi∗=1y_i^* = 1 and pi→0p_i \to 0: from 1−pi≈11 - p_i \approx 1 to wizmax⁡=pi(1−pi)zmax⁡→0w_i z_{\max} = p_i(1 - p_i)z_{\max} \to 0. Pull of points the model confidently misclassifies switches off, precisely what convex loss cannot do.

[ ]LogitBoost with and without response clippingBrowser
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 ρ=0.1\rho = 0.1, unclipped LogitBoost ends at 0.1250.125 after 300 rounds, worse than AdaBoost (0.1150.115), and by round 30 its noisy points, 10 % of the sample, exert 37 % of pull (AdaBoost 25 %). Clipping at zmax⁡=2z_{\max} = 2 reduces noisy pull to 21 % and final error to 0.0770.077, minimum 0.0650.065. With ρ=0.2\rho = 0.2 the pattern repeats: 0.1630.163 unclipped, 0.1080.108 with zmax⁡=2z_{\max} = 2. 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 ρ=0.2\rho = 0.2 error rises from minimum 0.0750.075 to 0.1080.108.

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 TT by validation, boosting early stopping, the simplest remedy used by all libraries. Bartlett and Traskin (2007) proved AdaBoost consistent when stopped after n1−ϵn^{1-\epsilon} rounds, for any ϵ∈(0,1)\epsilon \in (0, 1).
  • 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 AdaBoostReg_\text{Reg} by Rätsch, Onoda and Müller (2001).
  • Shrink steps. Multiply each αt\alpha_t by factor ν<1\nu < 1 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, +1+1, distinguished only by αt\alpha_t per learner. Schapire and Singer (1999) allowed real-valued learners ht:Rd→Rh_t : \R^d \to \R, sign as prediction and magnitude as confidence. The training-error proof repeats unchanged through step 2: for any real hth_t and Dt+1(i)∝Dt(i)e−yiht(xi)D_{t+1}(i) \propto D_t(i)e^{-y_i h_t(\vb{x}_i)}, training error is at most ∏tZt\prod_t Z_t with Zt=∑iDt(i)e−yiht(xi)Z_t = \sum_i D_t(i) e^{-y_i h_t(\vb{x}_i)}. So each round choose hth_t minimizing ZtZ_t. For a stump with leaves LL and RR, if W±LW_\pm^{L} is class ±1\pm 1 weight in the left leaf and leaf value is cc,

Z=∑hojas(W+e−c+W−ec),c∗=12log⁡W+W−,Z∗=2∑hojasW+W−.Z = \sum_{\text{hojas}} \big(W_+ e^{-c} + W_- e^{c}\big), \qquad c^* = \frac12\log\frac{W_+}{W_-}, \qquad Z^* = 2\sum_{\text{hojas}} \sqrt{W_+ W_-}.

Each leaf votes half its weighted log-odds and the split minimizes 2∑W+W−2\sum\sqrt{W_+W_-}, 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 Ew[e−Yh∣x]\E_w[e^{-Yh} \given \vb{x}] is 12log⁡pw(x)1−pw(x)\frac12\log\frac{p_w(\vb{x})}{1 - p_w(\vb{x})}, the statistical-section formula applied to the weighted distribution, and in a leaf pwp_w is estimated by W+/(W++W−)W_+/(W_+ + W_-). You will implement it in the code exercise.

SAMME. With K>2K > 2 classes, condition εt<1/2\varepsilon_t < 1/2 is too demanding: with K=10K = 10, 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:

αt=log⁡1−εtεt+log⁡(K−1),Dt+1(i)∝Dt(i) eαt 1[ht(xi)≠yi],H(x)=arg max⁡k∑tαt 1[ht(x)=k].\alpha_t = \log\frac{1 - \varepsilon_t}{\varepsilon_t} + \log(K - 1), \qquad D_{t+1}(i) \propto D_t(i)\, e^{\alpha_t\, \ind[h_t(\vb{x}_i) \neq y_i]}, \qquad H(\vb{x}) = \argmax_k \sum_t \alpha_t\,\ind[h_t(\vb{x}) = k].

The vote is positive if and only if εt<1−1/K\varepsilon_t < 1 - 1/K, i.e. hth_t beats random guessing among KK classes. With K=2K = 2, αt\alpha_t is twice AdaBoost’s and reweighting multiplies only errors by (1−εt)/εt(1-\varepsilon_t)/\varepsilon_t, 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.

[ ]SAMME from scratch versus scikit-learnBrowser
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 120°120°, first-stump weighted error is 0.3430.343 and none of 100 exceeds 0.3920.392, far from threshold 2/32/3; test error falls from 37.2 %37.2\,\% with one stump to 4.78 %4.78\,\% with 10 and 3.43 %3.43\,\% with 100. Wrapping our stump in scikit-learn’s interface, AdaBoostClassifier reproduces our αt\alpha_t within 10−1410^{-14}, 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 TT, default 50), and learning_rate (factor ν\nu multiplying each αt\alpha_t; with ν<1\nu < 1 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.

[ ]AdaBoost versus AdaBoostClassifierBrowser
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 2αt2\alpha_t (SAMME with K=2K = 2), matching twice our αt\alpha_t to 10−1510^{-15}. Second, decision_function returns not ff but 2f/∑α2f/\sum\alpha: twice normalized margin, in [−2,2][-2, 2]. Third, the default stump minimizes weighted Gini, not weighted error, so chooses different splits (the first splits x2x_2 at 0.6870.687 rather than 0.3980.398) and the entire sequence changes; after 60 rounds test error is 6.09 %6.09\,\% versus our 5.29 %5.29\,\%. 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

NumericA learner's vote
In an AdaBoost round the weak learner has weighted error εt=0.3\varepsilon_t = 0.3. What is its vote αt\alpha_t?
NumericHow much an error grows
In a round with εt=0.2\varepsilon_t = 0.2, two examples had equal weight before reweighting; hth_t gets the first right and second wrong. After reweighting, how many times the first's weight does the second have?
NumericRounds to zero error
The weak learner guarantees advantage γt≥0.1\gamma_t \ge 0.1 every round. With n=1000n = 1000 examples, what is the fewest rounds TT for which bound e−2γ2Te^{-2\gamma^2 T} guarantees exactly zero training error?
NumericA multiclass vote
In SAMME with K=3K = 3 classes, a stump has weighted error 0.60.6. What is its vote αt\alpha_t?
NumericFrom score to probability
Suppose FF minimizes population exponential loss and at a point F(x)=0.8F(\vb{x}) = 0.8. What is P(Y=1∣x)\Pr(Y = 1 \given \vb{x})?
QuizA learner that is too good
You use AdaBoost with unpruned decision trees as base learner and the first tree correctly classifies every training example. What happens?
QuizXOR with stumps
In the first figure, AdaBoost with stumps on XOR reduces training error each round but true error stays near 50 %. Why?
QuizWhat margin theory does and does not say
Which statements are correct?

More than one answer may be correct.

QuizHandling noisy labels
You suspect 15 % of training labels are wrong and want boosting with stumps. Based on the lesson, what change protects most?
ProofAdaBoost increases margins
Prove: For every θ∈[0,1)\theta \in [0, 1), the fraction of training examples with normalized margin ρi=yif(xi)/∑tαt≤θ\rho_i = y_i f(\vb{x}_i)/\sum_t\alpha_t \le \theta satisfies P^[ρ≤θ]≤∏t=1T2εt1−θ(1−εt)1+θ\hat{P}[\rho \le \theta] \le \prod_{t=1}^T 2\sqrt{\varepsilon_t^{1-\theta}(1-\varepsilon_t)^{1+\theta}}.
0
Use AdaBoost notation: f=∑tαthtf = \sum_t \alpha_t h_t with αt=12log⁡1−εtεt>0\alpha_t = \frac12\log\frac{1-\varepsilon_t}{\varepsilon_t} > 0, and recall that the training-error bound gave 1n∑ie−yif(xi)=∏tZt\frac1n\sum_i e^{-y_i f(\vb{x}_i)} = \prod_t Z_t.

Step 1 of 4. What pointwise inequality replaces 1[yif(xi)≤0]≤e−yif(xi)\mathbb{1}[y_i f(\mathbf{x}_i) \le 0] \le e^{-y_i f(\mathbf{x}_i)}?

ProofHalf the log-odds
Prove: If p(x)=P(Y=1∣x)∈(0,1)p(\vb{x}) = \Pr(Y = 1 \given \vb{x}) \in (0, 1), the minimizer of E[e−YF∣x]\E[e^{-YF} \given \vb{x}] over F∈RF \in \R is F∗(x)=12log⁡p(x)1−p(x)F^*(\vb{x}) = \frac12\log\frac{p(\vb{x})}{1 - p(\vb{x})}.
0
Fix x\vb{x} and write p=p(x)p = p(\vb{x}). Since Y∈{−1,+1}Y \in \{-1, +1\}, the conditional expectation is a function of one real number FF.

Step 1 of 3. What is the conditional expectation?

CodeReal AdaBoost with stumps
Implement real_adaboost_fit(X, y, T, suave=1e-6) with y in {−1,+1}\{-1, +1\}. In each round with weights DtD_t: choose feature jj and threshold uu (midpoint between consecutive distinct xjx_j values) minimizing 2∑hojasW+W−2\sum_{\text{hojas}}\sqrt{W_+W_-}; put c=12log⁡W++suaveW−+suavec = \frac12\log\frac{W_+ + \text{suave}}{W_- + \text{suave}} in each leaf; and reweight Dt+1(i)∝Dt(i)e−yiht(xi)D_{t+1}(i) \propto D_t(i)e^{-y_i h_t(\vb{x}_i)}. Return (tocones, Z), where tocones[t] = (j, u, c_izq, c_der) (ht(x)=cderh_t(\vb{x}) = c_\text{der} if xj>ux_j > u) and Z[t] is normalizer ∑iDt(i)e−yiht(xi)\sum_i D_t(i)e^{-y_i h_t(\vb{x}_i)}. Tests check criterion, leaves, normalizers, and that training error never exceeds ∏tZt\prod_t Z_t 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, Z
Shift+Enter to run

Summary

Key idea
AdaBoost reweights examples so the last learner is at chance and forces the next to correct it; it thereby minimizes exponential loss stagewise, with training error falling like e−2∑γt2e^{-2\sum\gamma_t^2} and population minimizer half the log-odds.
  • A weak learner has advantage γ>0\gamma > 0 over chance for any data weighting. AdaBoost uses αt=12log⁡1−εtεt\alpha_t = \frac12\log\frac{1-\varepsilon_t}{\varepsilon_t} and Dt+1(i)∝Dt(i)e−αtyiht(xi)D_{t+1}(i) \propto D_t(i)e^{-\alpha_t y_i h_t(\vb{x}_i)}, leaving hth_t at error exactly 1/21/2.
  • Training error is bounded by ∏tZt=∏t2εt(1−εt)≤e−2∑tγt2\prod_t Z_t = \prod_t 2\sqrt{\varepsilon_t(1-\varepsilon_t)} \le e^{-2\sum_t\gamma_t^2}: 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 12log⁡p1−p\frac12\log\frac{p}{1-p}, 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 TT 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 Zt=2∑W+W−Z_t = 2\sum\sqrt{W_+W_-}; SAMME extends AdaBoost to KK classes by adding log⁡(K−1)\log(K-1) to the vote, and is what AdaBoostClassifier implements.