AI Wiki中文/EN

Multi-armed bandits: learn from the reward you get to see

多臂老虎机

Define partial feedback, update arm means and separate pseudo-regret from a noisy observed reward shortfall.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Six decisions do not reveal eighteen rewards

An invented machine has three buttons with hidden Bernoulli success probabilities [0.25,0.45,0.70]. You choose actions [0,1,2,2,0,2] and observe rewards [1,0,1,1,0,1]. The observations say something about each selected button. They do not tell you what the other two buttons would have paid on those same rounds.

That missing feedback is the defining difficulty of a multi-armed bandit. A supervised table might contain a label for every example; here the action determines which outcome becomes visible. The learner must decide what to measure while trying to earn reward. Sutton and Barto’s chapter on bandits separates evaluative from instructive feedback. Auer, Cesa-Bianchi and Fischer give a precise stochastic model and an expected-regret objective.

The six rewards total 4. Always selecting the best mean would have expected reward 4.2 over six rounds. Is the loss therefore only 0.2? That number describes this noisy reward realization. The chosen actions’ mean gaps tell a different, equally useful story.

The same six observations yield mean-gap loss1.15, reward-noise contribution−0.95 and observed shortfall0.20; a lucky optimal arm can have negative shortfall.
The same six observations yield mean-gap loss1.15, reward-noise contribution−0.95 and observed shortfall0.20; a lucky optimal arm can have negative shortfall.

Specify the feedback before specifying the algorithm

Let K be the number of arms. For each arm a, imagine an infinite sequence of potential rewards X_(a,1),X_(a,2),…. The stationary stochastic model assumes each arm’s sequence is identically distributed with mean mu_a, and independent reward draws within and across arms. The learner observes a sequence entry only when it pulls that arm. In the bounded version,

Xa,n∈[0,1],μa=E[Xa,n],Na(t)=∑s=1t1[As=a],Rt=XAt,NAt(t).X_{a,n}\in[0,1],\qquad \mu_a=\mathbb E[X_{a,n}],\qquad N_a(t)=\sum_{s=1}^{t}\mathbf1[A_s=a],\qquad R_t=X_{A_t,N_{A_t}(t)}.

N_a(t) counts pulls through round t. The action must use past feedback and independent action randomization, not an unseen reward or a private mean vector. Thus its conditional expected reward is mu_(A_t). This is an assumption about the environment and information flow, not a fact established by a short experiment.

For a sampled arm, its empirical mean and incremental update are

μ^a,n=1n∑j=1nXa,j,μ^a,n=μ^a,n−1+Xa,n−μ^a,n−1n.\widehat\mu_{a,n}=\frac1n\sum_{j=1}^n X_{a,j},\qquad \widehat\mu_{a,n}=\widehat\mu_{a,n-1}+\frac{X_{a,n}-\widehat\mu_{a,n-1}}{n}.

Multiply the old mean by n−1, add the new reward and divide by n to obtain the update. With n=1, the initialized value cancels out. With n=0, there is no empirical mean; a displayed zero must be accompanied by a zero count. The working draft’s incremental implementation explains this storage reduction.

In the opening trace, the counts are [2,1,3] and the estimates are [0.5,0,1]. Arm 2’s estimate of 1 does not prove its success probability is 1. Nor does arm 1’s one observed failure prove its mean is zero.

Three quantities that should not share one unlabeled curve

Define mu_*=max_a mu_a and gap Delta_a=mu_*−mu_a. The cumulative path pseudo-regret uses the chosen actions but replaces noisy rewards by their means:

R‾T=∑t=1TΔAt=∑a=1KΔaNa(T)≥0.\overline{\mathcal R}_T=\sum_{t=1}^{T}\Delta_{A_t} =\sum_{a=1}^{K}\Delta_aN_a(T)\geq0.

This is random when the action sequence depends on random feedback. The count identity just groups equal action indices; it does not require a learning algorithm or a convergence claim. In the example the gaps are [0.45,0.25,0], giving 2×0.45+1×0.25=1.15.

The expected regret of a policy averages over its action and reward randomness. Under the stated stationary feedback assumptions,

RT=Tμ∗−E[∑t=1TRt]=E[R‾T]=∑aΔaE[Na(T)].\mathcal R_T =T\mu_* -\mathbb E\left[\sum_{t=1}^{T}R_t\right] =\mathbb E[\overline{\mathcal R}_T] =\sum_a\Delta_a\mathbb E[N_a(T)].

The key step is conditional expectation: knowing the past and the chosen action, the next reward still has that arm’s mean. This is the regret convention used by Auer and colleagues. Different literature sometimes uses “pseudo-regret” for the expected quantity; write the formula to remove ambiguity.

Finally define the observed shortfall against the best-mean baseline, and the reward noise accumulated along the selected actions:

DT=Tμ∗−∑t=1TRt,MT=∑t=1T(Rt−μAt),DT=R‾T−MT.D_T=T\mu_* -\sum_{t=1}^{T}R_t,\qquad M_T=\sum_{t=1}^{T}(R_t-\mu_{A_t}),\qquad D_T=\overline{\mathcal R}_T-M_T.

The example’s selected means sum to 3.05, so its reward noise is 4−3.05=0.95. Therefore D_T=1.15−0.95=0.20. Nothing contradicts anything: the action choices lost 1.15 in mean reward while their observed outcomes were 0.95 above those means.

If the optimal 0.7 arm pays 1 on all three pulls, pseudo-regret is zero but observed shortfall is 2.1−3=−0.9. The baseline is an expectation, not a maximum possible reward. This shortfall is also different from regret against the best arm’s realized counterfactual reward sequence, which the program does not observe.

Cumulative performance is not best-arm identification

A cumulative-reward learner pays for exploratory pulls along the way. A pure identification task instead asks which arm to recommend after a sampling budget. For a final recommendation hat_a, a common measure is its simple regret,

rsimple=μ∗−μa^.r_{\mathrm{simple}}=\mu_* -\mu_{\widehat a}.

Two methods can give the same final recommendation but incur different cumulative losses. Conversely, a method can earn substantial reward while leaving a close competitor uncertain. State the task before comparing methods. Exploration and exploitation discusses elementary choices; UCB and Thompson sampling use different information about uncertainty.

Keep the learner and the evaluator separate

Save the standalone standard-library Python 3 program as bandits.py and run python3 bandits.py. RunningMeans.observe accepts only the selected action and its observed bounded reward. It cannot use unchosen rewards. audit belongs to the evaluator: it receives the synthetic means so it can compute all three performance quantities.

import math
import random
import statistics


def integer(x, name, minimum=0):
    if isinstance(x, bool) or not isinstance(x, int) or x < minimum:
        raise ValueError(name + ' must be an integer >= ' + str(minimum))
    return x


def finite(x, name, low=None, high=None):
    if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x):
        raise ValueError(name + ' must be finite')
    if (low is not None and x < low) or (high is not None and x > high):
        raise ValueError(name + ' is outside its domain')
    return float(x)


def probabilities(values):
    p = [finite(v, 'probability', 0, 1) for v in values]
    if not p:
        raise ValueError('at least one arm is required')
    return p


class Bernoulli:
    """The learner receives only pull(action), never the mean vector."""
    def __init__(self, means, seed):
        self._means = probabilities(means)
        integer(seed, 'seed')
        self._streams = [random.Random(seed + 104729 * a) for a in range(len(means))]

    def pull(self, action):
        integer(action, 'action')
        if action >= len(self._means):
            raise ValueError('unknown action')
        return int(self._streams[action].random() < self._means[action])


def summary(values):
    if len(values) < 2:
        raise ValueError('at least two independent runs are needed for an SE')
    return dict(mean=statistics.mean(values), se=statistics.stdev(values) / math.sqrt(len(values)))


class RunningMeans:
    def __init__(self, arms):
        integer(arms, 'arms', 1)
        self.counts = [0] * arms; self.values = [0.] * arms

    def observe(self, action, reward):
        integer(action, 'action'); reward = finite(reward, 'reward', 0, 1)
        if action >= len(self.values): raise ValueError('unknown action')
        self.counts[action] += 1
        self.values[action] += (reward - self.values[action]) / self.counts[action]


def audit(actions, rewards, means):
    means = probabilities(means)
    if len(actions) != len(rewards): raise ValueError('unaligned feedback')
    counts = [0] * len(means); gaps = [max(means) - x for x in means]
    total = 0.; selected_expectation = 0.; path = []
    for a, r in zip(actions, rewards):
        integer(a, 'action'); r = finite(r, 'reward', 0, 1)
        if a >= len(means): raise ValueError('unknown action')
        counts[a] += 1; total += r; selected_expectation += means[a]
        path.append(dict(action=a, observed=r, gap=gaps[a]))
    pseudo = math.fsum(n * gap for n, gap in zip(counts, gaps))
    noise = total - selected_expectation
    return dict(counts=counts, reward=total, selected_mean_sum=selected_expectation,
                pseudoregret=pseudo, observed_shortfall=len(actions) * max(means) - total,
                reward_noise=noise, path=path)


def demo():
    means = [.25, .45, .7]; actions = [0, 1, 2, 2, 0, 2]
    rewards = [1, 0, 1, 1, 0, 1]; estimator = RunningMeans(3)
    for a, r in zip(actions, rewards): estimator.observe(a, r)
    lucky = audit([2] * 3, [1] * 3, means)
    traces = []
    for seed in range(40):
        env = Bernoulli(means, seed); seq = [i % 3 for i in range(600)]
        traces.append(audit(seq, [env.pull(a) for a in seq], means))
    return dict(hand=audit(actions, rewards, means), estimates=estimator.values,
                lucky=lucky, horizon=600, seeds=list(range(40)),
                observed_shortfall=summary([x['observed_shortfall'] for x in traces]),
                pseudoregret=summary([x['pseudoregret'] for x in traces]))


if __name__ == '__main__':
    import json
    print(json.dumps(demo(), indent=2, allow_nan=False))

The output includes the opening hand trace, the lucky optimal-arm trace, and 40 seeded runs of a fixed round-robin allocation. Every run has 600 pulls, 200 per arm. Its path pseudo-regret is therefore always 140, with zero variation across runs; reward noise still changes observed shortfall. The latter has sample mean 137.75 and standard error about 1.81155 in this run set. It estimates the same expected value, but 40 noisy realizations need not average exactly to 140.

Each arm uses a separate pseudorandom stream, so pulling another arm does not consume its next reward. Seeds make the demonstration reproducible. This is a simulation design, not access to real counterfactual outcomes in a deployed system.

A selected-arm mean update takes O(1) work and the learner stores O(K) numbers. The audit deliberately retains T rows, so its time and memory are O(T+K). The simulation constructs an action sequence and reward list for each run and retains all audited traces, costing O(mT+mK) for m runs. These teaching logs are not necessary for an online sample-mean learner.

What changes when the world is not a stationary bandit?

The model above excludes adversarial reward sequences, drift, delayed feedback and actions that change future external states. A fixed mean-gap decomposition no longer describes every such task. Context-dependent rewards require a policy that can react to the context; see contextual bandits. If actions affect later states and rewards, an MDP provides a different model.

Adaptive sampling also changes how estimates should be interpreted. A mean based on many observed samples can be useful, but a confidence interval chosen after inspecting many arms or stopping when a result looks good requires appropriate analysis. Replacing a fixed sample count by a random adaptive count in a textbook bound is not sufficient justification.

Zero counts, failed feedback and a genuine zero reward are different records. The implementation rejects out-of-range actions and nonfinite or out-of-range rewards before changing its state. An application needs equally explicit conventions for missing and delayed outcomes.

Audit the information and the loss

  1. After one failure from an arm, its estimate is zero. How does that differ from an untried arm whose initialized estimate is zero?

    Answer: The counts are one and zero. The first estimate summarizes a real observation; the second does not. An action-selection rule must declare how it treats untried arms.

  2. Recompute the opening trace’s gap-count loss and observed shortfall.

    Answer: Counts [2,1,3] multiply gaps [0.45,0.25,0] to give 1.15. Six best-mean rewards would total 4.2 in expectation; observed reward is 4, giving 0.2. The difference is reward noise 0.95.

  3. Can negative observed shortfall invalidate the nonnegativity of pseudo-regret?

    Answer: No. Pseudo-regret sums nonnegative mean gaps. A favorable reward realization can exceed an expected baseline; three successes from the 0.7 arm give shortfall −0.9 and pseudo-regret zero.

  4. Two experiments recommend the same final arm, but one pulls weak arms many more times. Are they equally successful?

    Answer: Their final simple regret can be equal, while cumulative regret differs. Decide whether the purpose is earning reward during learning or identifying a final recommendation; report the corresponding metric and sampling budget.

A feedback protocol supports many algorithms

The textbook working draft supplies the learning problem and incremental estimation. Auer et al. use expected counts to analyze finite-time allocation. The program here verifies accounting identities on original data; it does not reproduce the paper’s benchmark distributions or prove that a particular controller achieves its bound.

Make a prediction, then check

An optimal Bernoulli arm wins on every pull in a short run. Can realized reward exceed T times its mean?

Choose one answer

Learning objectives

  • Audit which rewards and counts a learner is allowed to use.
  • Derive the gap-count identity and explain why observed shortfall can be negative.

Prerequisites & connections

Explore related knowledge →

References

  1. Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
    Richard S. Sutton; Andrew G. Barto · 2015
  2. Finite-time Analysis of the Multiarmed Bandit Problem
    Peter Auer, Nicolò Cesa-Bianchi, Paul Fischer · 2002

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: PDF45–48 feedback and sample averages;51–52 incremental mean and distinction from constant-step tracking. Read2026-09-23; no replication of the Gaussian ten-arm testbed. Read physical PDF1–3 and the Fact1/Theorem1 proof on8–9; directly viewed3. Fixed independent arm reward streams in[0,1], expected regret, initialization and completed-pull clock, inverse-gap bound and union over possible sample counts. No full UCB2/epsilon proof or original benchmark replication. 6 paired equations and four explained exercises. Checked bounded selected feedback, exact count/mean updates, unobserved arms, gap-count pseudo-regret, noise decomposition and negative observed shortfall. Round-robin pseudo-regret is constant while realized reward varies; audit memory is distinguished from learner state.

  • Checked bounded selected feedback, exact count/mean updates, unobserved arms, gap-count pseudo-regret, noise decomposition and negative observed shortfall. Round-robin pseudo-regret is constant while realized reward varies; audit memory is distinguished from learner state.
  • Four computed SVG variants per topic;12 numeric/geometry tests and30 responsive cases passed. Ten selected current captures inspected: seven final captures directly viewed, three byte-identical to directly viewed earlier captures; actual byte identity checked. Browser inputs bound by SHA before integration. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

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