AI Wiki中文/EN

Online learning: predict, receive feedback, then update

在线学习

Run exact full-information Hedge, audit timing and static regret, and separate fixed-rate behavior from a horizon-tuned guarantee.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A forecast must come before its answer

Two inspection rules predict whether the next batch will fail a quality check. The result arrives only after the forecast. You can then score both rules and change how much you trust them for the following batch. Scoring today’s forecast after updating it with today’s answer would erase the problem you intended to solve.

Online learning studies such sequential decisions. The essential order is prediction, feedback and update. It does not mean that the software needs an internet connection. Nor does feeding a dataset to an optimizer one row at a time automatically evaluate an online learner: its losses must be recorded before each row’s feedback is used. Shalev-Shwartz states this protocol explicitly. Online Learning and Online Convex Optimization, introduction, pp. 108–110.

We will combine a fixed list of experts using Hedge. An expert can be a rule, a model or a human forecaster; the algorithm only needs its loss after each round. The implementation uses binary expert losses and exact fractions, so it exposes both the forecast weights and the cost paid before updating. It is a small replay of a full-information protocol, not a network service or a reinforcement-learning agent.

Compare with the best expert fixed for the whole sequence

On round t, choose a distribution pₜ over K experts. Then observe their complete loss vector ℓₜ. Each loss is between zero and one. The learner’s mixture loss and static regret after T rounds are:

ℓ^t=∑i=1Kpt,iℓt,i,RT=∑t=1Tℓ^t−min⁡1≤i≤K∑t=1Tℓt,i.\widehat\ell_t=\sum_{i=1}^K p_{t,i}\ell_{t,i},\qquad R_T=\sum_{t=1}^T\widehat\ell_t-\min_{1\le i\le K}\sum_{t=1}^T\ell_{t,i}.

The comparator is one expert chosen retrospectively for the entire sequence. It is not the best expert on each separate round. The latter comparator can switch freely and is much harder to compete with. Low regret also does not imply low absolute loss: if every expert is wrong frequently, matching the best of them may still be disappointing. The survey defines this fixed-comparator interpretation in §1.1. Expert-advice setting, p. 111.

Full information means that every expert’s loss becomes available after the decision, including experts not selected. In a bandit setting only the chosen action’s loss is observed; the program below cannot simply invent the missing feedback. If one expert is sampled according to pₜ, the mixture loss is its conditional expected loss provided the current loss vector does not depend on that fresh draw. A sampled run’s actual loss need not equal that expectation. No expert is sampled in this program.

Exponential weights retain the history without committing to one leader

Start all expert weights at one. Normalize the weights before each decision, then penalize experts according to the losses just revealed:

w1,i=1,pt,i=wt,i∑jwt,j,wt+1,i=wt,ie−ηℓt,i,η>0.w_{1,i}=1,\qquad p_{t,i}=\frac{w_{t,i}}{\sum_jw_{t,j}},\qquad w_{t+1,i}=w_{t,i}e^{-\eta\ell_{t,i}},\quad\eta>0.

Thus pₜ depends on losses through round t−1, not through t. Larger η changes relative weights more sharply. An expert is never removed merely because it made one mistake. The CMU notes give this Hedge update and the probability-simplex loss interpretation. 15-850, §14.4, pp. 178–179.

For losses in [0,1], a potential calculation gives the following bound for every finite realized loss sequence:

RT≤log⁡Kη+ηT8.R_T\le\frac{\log K}{\eta}+\frac{\eta T}{8}.

Here is the constant’s derivation. For a fixed round define g(s)=log(Σᵢpₜ,ᵢexp(sℓₜ,ᵢ)). Its second derivative is the variance of the loss under the exponentially tilted probabilities. A variable in [0,1] has variance at most one-quarter: its variance is at most its mean squared distance from one-half. Therefore g(−η)≤−ηℓ̂ₜ+η²/8. Let Wₜ be the sum of the unscaled Hedge weights. Summing this inequality over rounds and comparing with the weight of the best fixed expert gives:

−ηmin⁡i∑t=1Tℓt,i−log⁡K≤log⁡WT+1W1≤−η∑t=1Tℓ^t+Tη28.-\eta\min_i\sum_{t=1}^T\ell_{t,i}-\log K\le\log\frac{W_{T+1}}{W_1}\le-\eta\sum_{t=1}^T\widehat\ell_t+\frac{T\eta^2}{8}.

Rearranging proves the regret bound. It uses no IID assumption. For deterministic mixture losses, the algebra even permits an environment that sees pₜ before choosing ℓₜ. The random-expert interpretation additionally needs the environment not to see that round’s private draw; the survey makes this distinction in §2.1.1. Randomization and feedback, pp. 121–122.

A fixed learning rate is not an indefinite no-regret guarantee

Sublinear regret means the per-round excess over the fixed comparator tends to zero. The displayed bound with a fixed positive η has a term linear in T, so it does not establish that property. For K>1 and a known horizon T, the bound is minimized at η=√(8 log K/T), giving √(T log K/2). That is a choice made before observing the losses.

Our exact program instead uses integer q≥2 and η=log(q/(q−1)), so exp(−η)=(q−1)/q. This restricted family allows a simple rational update. If the positive horizon T is known, choose q=ceil(√T)+1. The elementary logarithm bounds give:

1q≤η=log⁡qq−1≤1q−1,RT≤qlog⁡K+T8(q−1).\frac1q\le\eta=\log\frac{q}{q-1}\le\frac1{q-1},\qquad R_T\le q\log K+\frac{T}{8(q-1)}.

For fixed K this is O(√T), since q is of order √T. It is a sufficient horizon-dependent tuning, not the optimal dependence on K. The helper requires a positive announced horizon; the core replay permits zero rounds. Unknown-horizon restarts or changing-rate algorithms need their own analysis and are not implemented here. An upper bound can also be loose: a lower observed regret need not come with a lower bound value on a particular short sequence.

Use integer weights and preserve the pre-update trace

For binary loss, multiplying a weight by (q−1)/q on a mistake and by one otherwise is equivalent, after multiplying every expert’s weight by the same q, to this integer update:

a1,i=1,at+1,i=at,i(q−ℓt,i),pt,i=at,i∑jat,j.a_{1,i}=1,\qquad a_{t+1,i}=a_{t,i}(q-\ell_{t,i}),\qquad p_{t,i}=\frac{a_{t,i}}{\sum_j a_{t,j}}.

The shared factor cancels from each prediction. hedge accepts a complete list or tuple of binary loss rows for replay, a positive declared expert count and q≥2. It validates shapes but uses only earlier feedback to compute each stored distribution. Labels here are expert losses, not the original classification targets. Booleans, floats, missing entries and losses outside zero or one are rejected; this API implements a narrower case than the [0,1] theorem.

The return value includes every pre-update distribution and mixture loss, the cumulative learner loss, each expert’s cumulative loss, all best-expert ties and static regret. Empty input has zero loss and regret, with every expert tied. There is no randomized action sampler, bandit estimator, partial-result budget or automatic choice of q from feedback.

from fractions import Fraction
from math import isqrt, log


def integer(value, minimum):
    if type(value) is not int or value < minimum:
        raise ValueError('integer below minimum or invalid type; no Booleans')
    return value


def sequence(value):
    if type(value) not in (list, tuple):
        raise ValueError('expected list or tuple')
    return value


def horizon_q(rounds):
    """Choose before seeing losses, for a known positive horizon."""
    rounds = integer(rounds, 1)
    root = isqrt(rounds)
    return root + 1 + int(root * root < rounds)


def hedge(loss_rows, experts, q=2):
    """Exact full-information Hedge for binary expert losses and beta=(q-1)/q."""
    experts, q = integer(experts, 1), integer(q, 2)
    rows = []
    for row in sequence(loss_rows):
        row = tuple(sequence(row))
        if len(row) != experts or any(type(x) is not int or x not in (0, 1) for x in row):
            raise ValueError('one binary loss per expert required')
        rows.append(row)
    weights, totals = [1] * experts, [0] * experts
    cumulative = Fraction()
    history = []
    for row in rows:
        # Prediction depends only on previous feedback.
        normalizer = sum(weights)
        prediction = tuple(Fraction(w, normalizer) for w in weights)
        loss = sum((p * x for p, x in zip(prediction, row)), Fraction())
        cumulative += loss
        history.append((prediction, loss))
        # Multiplying every standard Hedge weight by q changes no probabilities.
        for i, x in enumerate(row):
            weights[i] *= q - x
            totals[i] += x
    best_loss = min(totals)
    return {'history': tuple(history), 'loss': cumulative,
            'expert_losses': tuple(totals),
            'best_experts': tuple(i for i, loss in enumerate(totals) if loss == best_loss),
            'regret': cumulative - best_loss}


if __name__ == '__main__':
    losses = ((0, 1), (1, 0)) * 6
    for q in (2, horizon_q(len(losses))):
        result = hedge(losses, 2, q)
        eta = log(q / (q - 1))
        bound = log(2) / eta + eta * len(losses) / 8
        print('q:', q, 'loss:', str(result['loss']), 'best:', min(result['expert_losses']),
              'regret:', str(result['regret']), 'bound:', round(bound, 6))
    result = hedge(losses[:2], 2)
    print('first predictions:', tuple(tuple(str(p) for p in probs) for probs, loss in result['history']))
    print('two-round losses:', tuple(str(loss) for probs, loss in result['history']))
    print('best fixed experts:', result['best_experts'])
    print('empty-sequence regret:', str(hedge((), 2)['regret']))

Actual output:

q: 2 loss: 7 best: 6 regret: 1 bound: 2.039721
q: 5 loss: 19/3 best: 6 regret: 1/3 bound: 3.440999
first predictions: (('1/2', '1/2'), ('2/3', '1/3'))
two-round losses: ('1/2', '2/3')
best fixed experts: (0, 1)
empty-sequence regret: 0

The two experts alternate losses (0,1), then (1,0). With q=2, the first distribution is (1/2,1/2); after the first feedback it becomes (2/3,1/3), favoring the expert about to lose in the second round. Those losses are 1/2 and 2/3. After two rounds both integer weights equal two, so the pattern repeats. Each pair costs 7/6 while either fixed expert costs one. On any even horizon, regret is exactly T/12: this fixed-rate example has linear regret.

On twelve rounds, the preannounced-horizon choice gives q=5 and regret 1/3 instead of one. Both fixed experts have total loss six; a freely switching comparator has loss zero. Comparing with that switching oracle would produce learner loss itself, not the reported static regret. These are authored loss sequences, not measured forecasts.

Fractions and integer updates are exact. The printed logarithmic bounds are floating-point diagnostics for the two displayed q values, not a rigorous interval-arithmetic certificate for arbitrary enormous inputs. The mathematical bound does not depend on rounding those diagnostics.

Ignoring bit costs, the replay performs O((T+1)K) integer/rational operations and retains O((T+1)K) numeric slots, including the copied input and complete history. Integer weights have O(1+T log q) bits, while an individual probability denominator has O(1+T log q+log K) bits. Summing losses across rounds can produce a cumulative denominator with O(1+T² log q+T log K) bits. Exact fraction reduction and arithmetic therefore cost more than fixed-width operations. Retaining the full trace also takes more memory than an online state consisting only of current weights and cumulative scores. horizon_q uses integer square root, whose cost depends on the horizon’s encoding length.

The comparator and feedback define the problem

Online learning describes a timing and information protocol. Reinforcement learning additionally studies actions whose consequences can change future states and rewards. Our losses are supplied for all experts on the realized sequence. Static regret on those losses does not evaluate the counterfactual state trajectory that would have occurred if another policy had controlled an environment throughout.

Likewise, a static-regret bound is not a tracking guarantee for a rapidly changing best expert. Allowing the comparator to switch, adding delayed feedback, hiding unchosen losses or changing the expert pool alters the problem. Those extensions need additional assumptions or algorithms, rather than a different label on this replay.

The mixture loss is appropriate for a fractional allocation with linear costs, or as an expected loss for a suitable random expert choice. It is not automatically the loss of a deterministic majority vote, and it is not the error of a single sampled action. If an adversary sees the actual sampled expert and assigns loss one only to that expert, the conditional-expectation calculation no longer applies.

Low average regret does not promise that absolute error vanishes, that the latest weights identify a permanently best expert, or that the model generalizes to an unrelated future distribution. Converting an online guarantee into an IID batch-learning guarantee is a separate theorem. The PAC learning and empirical risk chapters address different questions.

For an operational stream, keep the decision timestamp, the feedback availability time and the update together. A delayed label must not enter a forecast made before it arrived. Rescaling losses also changes the meaning of η and the bound’s constants. This program’s binary, immediate, full-feedback contract makes those choices explicit.

Move the update and watch what changes

  1. For q=2 and first loss vector (0,1), what distribution must be recorded before the feedback? What false advantage appears if the update is performed first?

    Answer: The valid distribution is (1/2,1/2), with mixture loss 1/2. Updating first would record (2/3,1/3) and loss 1/3 on information that should still be hidden. That is look-ahead, not a better online decision.

  2. On twelve alternating rounds, each fixed expert loses six times. Why is q=2 regret one rather than seven? Does this show sublinear regret as the horizon grows?

    Answer: Learner loss is seven, so static regret is 7−6=1. The comparator that switches to the correct expert every round has loss zero but is not the stated benchmark. Repeating the pair gives regret T/12, which is linear for fixed q=2.

  3. If all K experts have loss one on every round, what are the learner’s loss and regret? What if there is only one expert or no rounds?

    Answer: Mixture loss is T and the best expert also loses T, so regret is zero despite uniformly bad predictions. One expert always has zero static regret relative to itself. With no rounds, both losses are zero and every declared expert is tied.

  4. Why may the loss vector depend on the announced mixture but not on the fresh sampled action in the random-expert interpretation? What does choosing q from a known horizon add?

    Answer: The potential proof holds for every realized vector paired with its mixture. Interpreting the dot product as expected sampled loss requires the vector to be fixed without seeing that round’s random draw. Choosing q=ceil(√T)+1 before feedback makes the displayed bound sublinear for fixed K; keeping q=2 forever does not do so. The program evaluates mixtures and samples no actions.

Specify the loss before comparing online methods

Shalev-Shwartz’s author-hosted survey gives the sequential protocol, regret relative to a fixed hypothesis and the randomization restriction. Its header identifies volume 4(2), 2011, pp. 107–194, while the copyright line is 2012. Those are recorded separately. Only relevant sections were read; no claim is made to reproduce its many other online algorithms.

The CMU Fall 2020 advanced-algorithms notes present Hedge and a potential proof in §14.4. Their displayed theorem uses losses in [−1,1], a learning-rate restriction and a different constant. This chapter independently derives the [0,1] bound with the variance argument above; it does not copy a constant across incompatible assumptions. The full PDF failed to open directly, so the relevant official search-extracted pages and course attribution were read instead.

Tests recompute every distribution directly from prefix expert-loss totals, independently of the integer weight updates. Short complete loss sequences, prefix invariance, comparator ties, fixed-rate linear regret and exact sampling expectations make timing errors observable. No course code, forecast data or external model is used.

Make a prediction, then check

Twelve alternating rounds give learner loss 7 and each expert loss 6. What is the static regret?

Choose one answer

Learning objectives

  • Enforce prediction before feedback and distinguish full information, bandit feedback and action-dependent environments.
  • Compute exact mixture losses and static regret against the best fixed expert, without replacing it by a switching oracle.
  • Derive the Hedge potential bound and explain why fixed rates differ from preannounced-horizon tuning.

Prerequisites & connections

Explore related knowledge →

References

  1. Online Learning and Online Convex Optimization
    Shai Shalev-Shwartz · 2011
  2. 15-850 Advanced Algorithms, Fall 2020 — Hedge and the probability-simplex game
    Anupam Gupta and course contributors; Carnegie Mellon University · 2020

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 passed. Direct powers of prefix loss totals, not recursive integer updates, check 828 complete replays: all two-expert sequences through length four and three-expert sequences through length two, at q=2 and q=5. Full histories, totals, best-expert ties and regret agree.
  • Checked pre-feedback prefix invariance, the update-before-prediction failure, fixed-rate regret T/12, horizon tuning, empty/single-expert cases, permutation and input preservation. Nine 65-digit Decimal checks verify the potential and regret bounds; eight action paths verify sampled expected loss, with an explicit counterexample when the current draw is revealed to the adversary.
  • Complete original bilingual articles, six identical displays, six anchors, four answered exercises and identical Python with six actual stdout lines. Strict MDX/KaTeX and actual React HTML passed. Humanizer reread; AI author checks only, review written pending independent review. No action sampler, bandit estimator, RL environment, source code reuse or whole-site build.
  • Reread both full protocols, six derivations, bit-cost discussion and four answers; no changes required. Nine author tests and strict MDX/KaTeX/React HTML pass in both languages, with six anchors/four answers and matching code/stdout.
  • Third reference builds partition polynomials from cumulative-error histograms, evaluates them by Horner and recovers mixture loss from consecutive partition ratios, without weight updates or summing per-expert probability losses. Thirty-six replays/108 rounds check losses and regret; twelve alternating sequences verify pairs/(4q−2), and six horizons including a 100-digit integer check ceiling-root tuning.
  • Verified potential bounds, tilted variance <=1/4 and announced-horizon versus fixed-q behavior; distinctions among full feedback/bandits, mixture/randomized realized loss, static/switching comparators and counterfactual policies are explicit. Floating bounds are diagnostics for displayed small q, not certified arbitrary-integer numerical bounds.
  • 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.

Source locations checked:

  • Online Learning and Online Convex Optimization · Actually opened the 90-page author-hosted PDF. Header lines 0–7 and 37–46 identify author, journal volume year 2011, copyright 2012 and DOI 10.1561/2200000018. Read printed 108–111 (PDF indices 3–6), lines 59–166: prediction before feedback, no IID requirement, static regret and fixed experts. Read §2.1.1 printed 121–122 (indices 16–17), lines 497–534: randomizing over experts, linear expected loss and the restriction that the environment cannot condition the loss vector on this round’s random bits. No full-survey or visual-page review claimed.
  • 15-850 Advanced Algorithms, Fall 2020 — Hedge and the probability-simplex game · Direct web opening of the combined PDF returned Internal Error. Actually read the official PDF’s search-extracted printed pp. 178–179, §14.4 and §14.4.1: simplex decision, subsequent loss vector, normalized exponential weights and Theorem 14.7 potential proof. It uses losses in [-1,1] and rate at most 1/2; the article separately derives its all-positive-rate [0,1] constant using tilted variance at most 1/4. Also read the Fall 2020 official course page identifying lecturer Anupam Gupta, and the notes’ contributor description. No copied implementation, entire-course review or source-figure reuse.
  • Online Learning and Online Convex Optimization · Root independently opened author-hosted OLsurvey.pdf, read §2.1.1 printed pp.121–122, extracted lines497–534: choose expert by a distribution, reveal full loss vector, expected linear loss, adversary cannot use current random bits, compare fixed expert vertices. Publication-header details remain separately documented in author check; no full-survey/visual claim.
  • 15-850 Advanced Algorithms, Fall 2020 — Hedge and the probability-simplex game · Root independently read official course-PDF indexed extracts §14.4/14.4.1 printed178–179 from exact /academic/class/15850-f20/www/notes/cmu850-f20.pdf: distribution first, subsequent [-1,1] losses, exponential weights and theorem14.7 with learning-rate <=1/2 and epsilon*T+lnN/epsilon. Confirmed article separately derives [0,1] eta*T/8 bound, not copied from this different theorem. No whole-file fetch or source code execution claimed.

Related topics

No matches. Try a synonym or acronym.

0 results shown

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