AI Wiki中文/EN

AdaBoost: change the sample weights, then combine the learners

AdaBoost

Derive binary boosting from weighted errors and exponential loss; run exact stump updates with explicit zero-error, no-edge and voting rules.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

The next learner sees a different set of priorities

Consider three training records on a line: (0, -1), (1, +1), (2, -1). A single threshold cannot isolate the positive point in the middle. It can get two records right, but one remains wrong. AdaBoost builds a sequence of such simple classifiers, changing which training mistakes matter most before fitting the next one.

The first learner in our example predicts −1 everywhere. It misses only the middle record. AdaBoost raises that record’s share of the training weight from 1/3 to 1/2. The next learner has a stronger incentive to classify it correctly, even if doing so introduces a mistake elsewhere. Earlier learners remain in the final combination, each with its own vote weight.

There are two different weights to keep apart. A sample weight belongs to a training record and controls the next fitting problem. A coefficient belongs to an already fitted classifier and controls its contribution to the final prediction. In Hedge in online learning, the maintained distribution instead assigns weight to experts or actions, and observed losses change how much they are trusted. AdaBoost’s distribution is over examples: recent mistakes become more influential in training. The mathematical connection through multiplicative updates does not make their indices or purposes interchangeable. Freund and Schapire, A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting

This chapter treats binary labels −1 and +1, deterministic decision stumps and the unshrunk AdaBoost update. It builds on decision trees and empirical risk. It is not a multiclass voting recipe or a regression algorithm.

From weighted mistakes to an additive classifier

Give each of n nonempty training records initial weight 1/n. At round t, D_t is a positive distribution over the records. The weak learner produces a binary classifier h_t. Its weighted error, coefficient and the accumulated score are

εt=∑i=1nDt(i)1[ht(xi)≠yi],αt=12ln⁡1−εtεt,FT(x)=∑t=1Tαtht(x).\varepsilon_t=\sum_{i=1}^{n}D_t(i)\mathbf 1[h_t(x_i)\ne y_i],\qquad \alpha_t=\frac12\ln\frac{1-\varepsilon_t}{\varepsilon_t},\qquad F_T(x)=\sum_{t=1}^{T}\alpha_t h_t(x).

For now assume every accepted round has error strictly between zero and 1/2. Then alpha is finite and positive. The final prediction is +1 for a positive score and −1 otherwise; this explicitly assigns a zero-score tie to −1. Error is measured using the current D_t, not the uniform training error or a test set. A threshold with a small unweighted error may be a poor choice after reweighting.

The usual exponential update is

Dt+1(i)=Dt(i)exp⁡[−αtyiht(xi)]Zt,Zt=(1−εt)e−αt+εteαt=2εt(1−εt).D_{t+1}(i)=\frac{D_t(i)\exp[-\alpha_t y_i h_t(x_i)]}{Z_t},\qquad Z_t=(1-\varepsilon_t)e^{-\alpha_t}+\varepsilon_t e^{\alpha_t}=2\sqrt{\varepsilon_t(1-\varepsilon_t)}.

Correct predictions have y_i h_t(x_i)=+1, while mistakes have value −1. Consequently, a mistake receives a larger multiplier. Multiplying every unnormalized weight by the same positive factor does not change the normalized distribution. Multiply by exp(−alpha) and define beta as error divided by one minus error. This gives an equivalent update using only rational numbers:

βt=εt1−εt,Dt+1(i)=Dt(i) βt1[ht(xi)=yi]2εt.\beta_t=\frac{\varepsilon_t}{1-\varepsilon_t},\qquad D_{t+1}(i)=\frac{D_t(i)\,\beta_t^{\mathbf 1[h_t(x_i)=y_i]}}{2\varepsilon_t}.

The denominator is beta times the total correct weight, plus the total mistake weight: beta(1−error)+error=2error. After normalization, the records that this particular learner got wrong have total weight exactly 1/2. The correct records share the other half. Individual mistake weights increase by 1/(2error), while correct weights decrease by 1/[2(1−error)]. Thus weights can rise and fall across rounds; being difficult once does not mean a record’s weight grows forever.

Why this coefficient appears

Define exponential training loss as the mean of exp(−y_i F(x_i)). Repeated updates make D_t proportional to the current individual exponential losses. Holding h_t fixed and adding a coefficient a gives

L(F)=1n∑i=1nexp⁡[−yiF(xi)],L(Ft−1+aht)L(Ft−1)=(1−εt)e−a+εtea.L(F)=\frac1n\sum_{i=1}^{n}\exp[-y_iF(x_i)],\qquad \frac{L(F_{t-1}+a h_t)}{L(F_{t-1})}=(1-\varepsilon_t)e^{-a}+\varepsilon_t e^a.

Differentiate the right side. Setting its derivative to zero equates error times exp(a) with one minus error times exp(−a), yielding the half-log coefficient above. The second derivative is positive, so this is the unique finite minimizer when the error lies strictly between zero and one. Within the positive-edge range, choosing a lower weighted error also lowers the optimal loss factor. Our weak learner exhaustively finds the minimum-error stump in its fixed candidate family. A practical approximate weak learner need not find that exact minimum. This stagewise loss interpretation connects AdaBoost to additive modeling and coordinate-wise optimization. Schapire, Explaining AdaBoost, §4

A misclassified record has y_i F_T(x_i) at most zero, so its exponential loss is at least one, including an incorrectly resolved zero-score tie. Starting from F_0=0 gives the finite-round training bound

R^(HT)≤L(FT)=∏t=1T2εt(1−εt)≤exp⁡ ⁣[−2∑t=1Tγt2],γt=12−εt.\widehat R(H_T)\le L(F_T)=\prod_{t=1}^{T}2\sqrt{\varepsilon_t(1-\varepsilon_t)}\le \exp\!\left[-2\sum_{t=1}^{T}\gamma_t^2\right],\qquad \gamma_t=\frac12-\varepsilon_t.

The last inequality follows from each factor being the square root of 1−4gamma² and the inequality log(1−u)≤−u. If every round has gamma at least a fixed positive value, the bound is at most exp(−2T gamma²). That is a condition on all the weighted learning problems encountered, not a conclusion obtained from a stump doing well on the initial sample. Here gamma is a weak learner’s edge; it differs from an individual example’s classification margin y_i F_T(x_i).

This proof concerns training loss and training error under the uniform initial distribution. A test-error conclusion requires additional sampling and complexity assumptions. Nor does a decreasing upper bound force the actual zero-one training error to decrease at every step. Freund and Schapire, §4.2, Theorem 6 and §4.3

Exact weights and exact voting without epsilon clipping

A stump is (threshold, polarity): it predicts polarity at or below the threshold and its negative above it. A None threshold denotes a constant. We test constants −1 and +1 first, then increasing midpoints between distinct training feature values, testing polarity −1 before +1. The first candidate with minimum weighted error wins. Conflicting labels at the same feature value remain separate weighted records.

The stopping rules are part of the implementation:

  • If the selected stump has zero error, return perfect and use that stump for predictions. There is no finite half-log coefficient at zero. This is an explicit limiting convention: a coefficient tending to positive infinity dominates any existing finite score. Positive weights mean the stump fits every training record, not every possible future record. With our fixed exhaustive candidate family, an available perfect stump is already found on the first attempted round.
  • If error is at least 1/2, return no-edge without adding that stump or changing the weights. Because the family contains both polarities, a minimum above 1/2 is impossible for valid inputs; the realizable boundary is equality. Negating any binary classifier changes its weighted error to one minus the original error. At equality there is no positive edge and the coefficient is zero.
  • Otherwise add the finite stage and update the distribution. Reaching max_rounds returns round-limit; it does not assert convergence. A zero round limit performs no weak-learner attempts. An empty ensemble predicts −1 by the zero-score tie rule.

No automatic stop is triggered merely because the ensemble has zero training error. That differs from a single weak learner having zero weighted error.

Finite stages also allow exact classification without approximating logarithms. At a query, compare the following rational product with one:

RT(x)=∏t=1T(1−εtεt)ht(x)=exp⁡[2FT(x)].R_T(x)=\prod_{t=1}^{T}\left(\frac{1-\varepsilon_t}{\varepsilon_t}\right)^{h_t(x)}=\exp[2F_T(x)].

A ratio above one means a positive score; equality is an exact tie. This quantity is a transformed vote score, not an estimate of posterior odds. The method relies on binary outputs, rational errors and the unshrunk coefficients specified above. It is not a generic substitute for numerical scoring in arbitrary boosting variants.

from fractions import Fraction as Q


def coordinate(x):
    if isinstance(x, bool) or not isinstance(x, (int, Q)):
        raise ValueError('features must be integers or Fractions')
    return Q(x)


def read_rows(rows):
    if not isinstance(rows, (list, tuple)) or not rows:
        raise ValueError('rows must be a nonempty list or tuple')
    data = []
    for row in rows:
        if not isinstance(row, (list, tuple)) or len(row) != 2:
            raise ValueError('each row must contain one feature and a label')
        x, y = row
        if type(y) is not int or y not in (-1, 1):
            raise ValueError('labels must be the integers -1 or +1')
        data.append((coordinate(x), y))
    return tuple(data)


def stump_output(stump, x):
    threshold, polarity = stump
    return polarity if threshold is None or x <= threshold else -polarity


def candidates(data):
    xs = sorted(set(x for x, y in data))
    result = [(None, -1), (None, 1)]
    for left, right in zip(xs, xs[1:]):
        result.extend((((left+right)/2, -1), ((left+right)/2, 1)))
    return tuple(result)


def best_stump(data, weights, pool):
    best, error = None, Q(2)
    for stump in pool:
        loss = sum((w for (x, y), w in zip(data, weights)
                    if stump_output(stump, x) != y), Q(0))
        if loss < error:
            best, error = stump, loss
    return best, error


def fit_adaboost(rows, max_rounds):
    data = read_rows(rows)
    if type(max_rounds) is not int or max_rounds < 0:
        raise ValueError('max_rounds must be a nonnegative integer')
    weights = (Q(1, len(data)),) * len(data)
    pool, history, perfect = candidates(data), [], None
    status, attempts = 'round-limit', 0
    for _ in range(max_rounds):
        stump, error = best_stump(data, weights, pool)
        attempts += 1
        if error == 0:
            perfect, status = stump, 'perfect'
            break
        if error >= Q(1, 2):
            status = 'no-edge'
            break
        beta = error / (1-error)
        raw = tuple(w * (beta if stump_output(stump, x) == y else 1)
                    for (x, y), w in zip(data, weights))
        normalizer = sum(raw, Q(0))
        after = tuple(w / normalizer for w in raw)
        history.append({'stump': stump, 'error': error, 'beta': beta,
                        'before': weights, 'after': after})
        weights = after
    return {'status': status, 'attempts': attempts, 'rounds': tuple(history),
            'weights': weights, 'perfect': perfect}


def predict(model, xs):
    # model must be an unmodified result of fit_adaboost.
    if not isinstance(xs, (list, tuple)):
        raise ValueError('queries must be a list or tuple')
    queries = tuple(coordinate(x) for x in xs)
    result = []
    for x in queries:
        if model['perfect'] is not None:
            result.append(stump_output(model['perfect'], x))
            continue
        vote_ratio = Q(1)
        for stage in model['rounds']:
            ratio = 1 / stage['beta']
            vote_ratio *= ratio if stump_output(stage['stump'], x) == 1 else 1/ratio
        result.append(1 if vote_ratio > 1 else -1)
    return tuple(result)


if __name__ == '__main__':
    rows = ((0, -1), (1, 1), (2, -1))
    model = fit_adaboost(rows, 3)
    print('status:', model['status'], 'attempts:', model['attempts'])
    for t, stage in enumerate(model['rounds'], 1):
        print('round', t, 'stump:', stage['stump'],
              'error:', stage['error'], 'beta:', stage['beta'])
        print('weights:', ', '.join(map(str, stage['after'])))
    print('predictions:', predict(model, (0, 1, 2)))
    print('zero error:', fit_adaboost(((0, -1), (1, 1)), 3)['status'])
    blocked = fit_adaboost(((0, -1), (0, 1)), 3)
    print('no edge:', blocked['status'], 'prediction:', predict(blocked, (0,)))
    print('zero rounds:', predict(fit_adaboost(rows, 0), (0, 1, 2)))

The complete standard-library example prints:

status: round-limit attempts: 3
round 1 stump: (None, -1) error: 1/3 beta: 1/2
weights: 1/4, 1/2, 1/4
round 2 stump: (Fraction(1, 2), -1) error: 1/4 beta: 1/3
weights: 1/6, 1/3, 1/2
round 3 stump: (Fraction(3, 2), 1) error: 1/6 beta: 1/5
weights: 1/2, 1/5, 3/10
predictions: (-1, 1, -1)
zero error: perfect
no edge: no-edge prediction: (-1,)
zero rounds: (-1, -1, -1)

The first stage uses the constant −1 because it ties with two thresholds at error 1/3 and appears first. The next stages address different mistakes. Their vote ratios at x=0, 1 and 2 are respectively 5/6, 15/2 and 3/10, giving the three correct labels. All stage errors remain positive; no individual stump solves the dataset. Three accepted rounds exhaust the requested limit.

Let M be the number of candidate stumps, A the number of weak-learner attempts and R the number of accepted finite stages. Here M is at most 2n, A is at most max_rounds, and R≤A. Training uses O(n log(n+1)+AnM) arithmetic/comparison operations, under expected constant-time hashing for candidate construction. It retains O(n(R+1)) entries because the audit history saves before-and-after weight vectors; retaining only stumps would be smaller. Predicting m queries takes O(1+m(R+1)) arithmetic/comparison operations and O(1+m) extra entries. These bounds include zero rounds and empty queries. They ignore rational bit lengths, which can grow substantially through repeated products. Public input validation covers raw rows, the round limit and queries; prediction expects an unmodified fitted result.

The difficult record may be mislabeled

The weights express where the current fitting procedure is struggling. They do not distinguish an informative exception from a corrupted label, missing feature or impossible contradiction. For (0, -1) and (0, +1) with equal initial weights, any deterministic classifier of that feature must miss one. Our stump family returns error 1/2 and stops. Increasing the requested round count cannot manufacture an edge.

Even error counts on the training set can behave differently from the optimized loss. On the original five-point dataset ((0,-1),(1,-1),(2,+1),(3,-1),(4,-1)), the same code makes zero training mistakes after three stages and one after four. Its exponential loss nevertheless decreases. The surrogate rewards the sizes of signed scores as well as their signs; a score can cross zero while the total surrogate improves. This counterexample is about the supplied deterministic learner and tie rules, not a claim that boosting generally gets worse at round four.

Exponential loss penalizes strongly negative margins heavily. That can focus learning on useful hard cases, but also on noise. Repeatedly decreasing training loss is not evidence that performance on fresh data keeps improving. Schapire’s analysis separates the roles of margins, loss minimization, regularization and noise rather than treating any one perspective as a universal performance guarantee. Explaining AdaBoost, §§3–6

In an experiment, choose the round count and learner complexity using a suitable validation procedure, then assess the chosen model on data protected from that choice. If a learning-rate multiplier is introduced, the exact line minimizer, loss factor and rational-vote implementation above must be reconsidered; simply changing one formula while retaining the others would define an inconsistent algorithm. The official AdaBoost interface exposes such choices and supports variants with different outputs and objectives. scikit-learn 1.7.2: AdaBoost

Follow one mistake through the update

  1. On the three-point example, the first classifier misses only x=1. Compute its error, beta, coefficient and new sample weights.

Answer: Error is 1/3, beta is 1/2 and alpha is half of log 2. Unnormalized weights become 1/6, 1/3 and 1/6. Their sum is 2/3, giving normalized weights 1/4, 1/2 and 1/4. These are weights on records; the classifier’s vote coefficient is a different object.

  1. A fitted classifier has current weighted error 1/2. Why not replace the error by 1/2 minus a tiny epsilon and continue? What if it has exactly zero error?

Answer: At 1/2 the honest coefficient is zero, so the round offers no positive edge. Perturbing the error would invent an edge and break the stated update and loss identities. At zero the half-log has no finite value. Our explicit rule stops with the perfect stump as the dominating classifier, rather than replacing zero by an arbitrary small number. That certifies training fit only.

  1. The three finite stages have beta values 1/2, 1/3 and 1/5. At a query their predictions are −1, −1 and +1. What is the ensemble label, and is the calculated ratio a calibrated probability?

Answer: The ratio is 5/(2×3)=5/6, below one, so the output is −1. It equals exp(2F), a transformed score. It is not a calibrated probability or a proven posterior-odds estimate. A zero-stage ensemble instead has ratio one and also predicts −1, this time by the tie rule.

  1. Suppose every accepted round has weighted error at most 0.4. What training-error bound follows after T finite rounds? Does it force the next actual mistake count or test error to decrease?

Answer: Every edge is at least 0.1, so the bound is exp(−0.02T). Its assumptions must hold at every reweighted round. It does not make the actual zero-one error monotone: the five-point example goes from zero mistakes to one while exponential loss falls. It also says nothing by itself about test error, for which sampling, model complexity and selection matter.

Adaptive boosting and the later loss interpretation

Freund and Schapire’s work connected a general online decision framework with boosting. The extended abstract appeared in 1995; the journal article appeared in 1997. An important feature of AdaBoost is that a round’s contribution adapts to its observed weighted error, rather than requiring one fixed advantage to be known in advance. The training bound reflects the whole sequence of achieved edges. The article also develops extensions beyond binary classification; their losses and combination rules should not be silently identified with the binary algorithm here. Freund and Schapire

The stagewise exponential-loss view asks a different question: what objective does this sequence of reweightings decrease? It connects the procedure to coordinate descent and to later developments in additive models. The margin view asks about the distribution of signed voting strength, which retains information that a count of correct labels discards. Neither a low training loss nor a large score alone is a complete generalization argument. Schapire’s Explaining AdaBoost is useful continued reading because it compares these explanations and their assumptions, including where noise and a restricted weak-learner family cause difficulty. Schapire, §§3–6

For the next method comparison, contrast bagging, whose bootstrap fits are aggregated without this sequential sample-weight feedback, with gradient boosting, pending, which broadens the loss-based construction. Also keep the binary rule separate from multiclass SAMME and regression AdaBoost.R2; those names in an implementation refer to different algorithms, not merely different output labels. Official variant overview

Make a prediction, then check

A selected binary weak learner has weighted error exactly 1/2. What does this implementation do?

Choose one answer

Learning objectives

  • Distinguish training-record weights, classifier vote coefficients and Hedge expert weights.
  • Derive finite-stage exponential-loss reduction and the conditional training-error bound from weighted weak errors.
  • Run exact stump updates and voting with explicit perfect, no-edge, round-limit and tie semantics.

Prerequisites & connections

Explore related knowledge →

References

  1. A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting
    Yoav Freund; Robert E. Schapire · 1997
  2. Explaining AdaBoost
    Robert E. Schapire
  3. AdaBoost — scikit-learn 1.7.2 documentation
    scikit-learn contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Nine tests pass. Fifty-five complete fit reports match an independent signed-prefix-correlation weak learner and weights reconstructed from all previous mistake sets, rather than the implementation’s correct-case incremental beta update. Twelve 80-digit Decimal reconstructions check final weights, margin predictions, exponential-loss product identities and training bounds.
  • Verified the 1/3, 1/4, 1/6 three-stage errors; half-total mistake mass after updates; positive normalized weights; perfect/no-edge/zero-round boundaries; deterministic ties; duplicate and reordered records; immutable inputs; invalid tail items; 100-digit features. A five-point counterexample changes zero-one mistakes from 0 to 1 at stage 4 while exponential loss decreases.
  • Complete bilingual original prose, identical Python and eleven stdout lines; six matching display formulas, six required anchors and four answered exercises. Strict MDX/KaTeX/React HTML, actual MathML and emphasis checks pass. Only article_text controls test article paths. Pinned Humanizer rules applied; remains written, with AI author checks only. No human review, production benchmark, whole-site build or browser UI acceptance.
  • Reread both full articles, six derivations, four answers and program; nine author tests and strict MDX/KaTeX/actual HTML pass. Independently checked half-log line minimization,2ε normalization, positive weights, zero-error limit, no-edge/empty-ensemble ties and finite-round status.
  • An exact squared exponential-loss identity checks all16 four-point labelings and48 finite stages: cumulative beta times the squared mean inverse-beta mistake products equals the product of4ε(1−ε). Uses no logarithms, exponentials, floating point or implementation normalization; also verifies the squared stationary-point identity.
  • Sufficient bound versus actual zero-one loss, training versus test, and example weights versus learner coefficients remain distinct; five-point nonmonotonic example executes. No substantive changes required; five hashes and exact source IDs/URLs bind reviewed files, with publication navigation separately recorded.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting · Actually read author-hosted PDF: cover lines 0–39 identifies publication and extended-abstract dates; §4.2, Theorem 6 and equations 14, 21–23 (PDF pages 14–16, printed 14–16) give the finite sample bound and achieved-edge dependence; §4.3 distinguishes generalization; binary/M1 discussion and Figure 3 (PDF pages 21–22) show beta updates and label voting. Princeton legacy URL failed; current author URL succeeded. A university mirror also opened, but citations and checks bind the author-hosted file. PDF screenshot calls did not produce a model-visible image, so only textual reading is claimed.
  • Explaining AdaBoost · Actually read the 16-page author PDF: Figure 1 on printed page 2 gives ±1 labels, half-log alpha, exponential update and weighted sign; §2 pages 3–4 specifies the weak learning condition and complexity qualifications; §3 pages 5–6 separates margins from zero-one errors; §4 pages 7–9 gives exponential-loss/coordinate-descent interpretation and limits of objective-only explanations; §6 pages 12–14 discusses noise and restricted weak-hypothesis classes. No experimental figures, tables or numerical claims reproduced.
  • AdaBoost — scikit-learn 1.7.2 documentation · Actually read §1.11.7, extracted lines 889–934, on the fixed 1.7 path displaying 1.7.2: sequential reweighting, classifier SAMME versus regressor R2, stump default, learning_rate and n_estimators. Our text derives the exact update instead of adopting the guide’s informal suggestion that hard examples gain influence monotonically. Binary coefficient and tie/zero-error conventions are explicitly ours, not claims of matching library details.
  • A Decision-Theoretic Generalization of On-Line Learning and an Application to Boosting · Independently opened current author-hosted35-page PDF. Header lines0–39 dates manuscript1996-12-19, identifies JCSS55(1):119–139(1997) and March1995 extended abstract. Introduction lines118–179 explains examples-as-distribution, adaptive achieved accuracies and binary guarantee. Readings are textual, not a visual or experimental reproduction; does not identify1997 as first announcement.
  • Explaining AdaBoost · Independently read author16-page PDF Figure1/lines27–73 for ±1, half-log, exponential update and weighted sign; lines87–115 and147–165 separate weak learning/complexity and continued training after ensemble zero error; §4 lines275–350 treats coordinate descent and limits of minimizing exponential loss alone. Algebra and exact loss certificate checked independently; no benchmark results reused.
  • AdaBoost — scikit-learn 1.7.2 documentation · Independently read fixed1.7.2 guide §1.11.7 lines889–934. Checked sequential weights, SAMME/R2 distinction, stump default and learning_rate/n_estimators. Did not adopt informal monotonically increasing hard-case weights; article derives per-round mistake mass and distinguishes variants. No library execution.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.