Upper confidence bounds: why an uncertain arm gets another turn
置信上界算法
Build UCB1 from empirical means and uncertainty radii; track initialization, the global clock and the inverse-gap regret bound.
ucbThe lower average can deserve the next pull
Suppose two arms have empirical means 0.55 and 0.40 after 90 and 10 pulls. The first average is higher, but the second rests on much less evidence. Should a learner immediately stop trying it?
UCB1 adds an uncertainty radius to each empirical mean. With 100 completed pulls, the radii are about 0.3199 and 0.9597, giving indices about 0.8699 and 1.3597. It chooses the second arm. An index above 1 is permitted even for rewards in [0,1]: the index is a decision score, not a predicted reward or a clipped probability.
Auer, Cesa-Bianchi and Fischer’s 2002 paper states UCB1 and its finite-time expected-regret bound. Sutton and Barto explain the broader upper-confidence-bound idea. We use the paper’s specific coefficient and clock convention so the implementation and theorem refer to the same rule.
Mean plus a radius, after initialization
Assume K≥2 arms. Each arm supplies independent, identically distributed rewards bounded in [0,1], and the reward sequences are independent across arms. Arm a has unknown mean mu_a. Pull every arm once. Afterwards, let n be the total number of completed pulls, N_a(n) its arm-specific count, and hat_mu_a(n) its empirical mean. The next action is
The natural logarithm uses the global count, while the denominator uses a local count. Figure 1 of the original paper explicitly defines n as plays done so far. Some presentations index the next round instead; do not silently switch conventions inside a trace. Our exact-score ties choose the lowest index, and unseen arms are pulled in index order before finite scores are computed.
Where does the square root come from?
For a fixed prefix of s independent rewards of one bounded arm, Hoeffding’s inequality gives one-sided bounds
Set the right-hand side to n⁻⁴ and solve for the radius:
That explains the score’s form. It does not yet prove a confidence statement for a random, adaptively chosen sample count. UCB’s choice changes which prefixes get inspected. The paper’s proof of Theorem 1 handles all possible relevant prefix counts rather than assuming the selected count was fixed in advance.
Why do suboptimal arms eventually lose their advantage?
Choose an optimal arm a_*, and let Delta_a=mu_*−mu_a>0 for a suboptimal arm. If a is chosen despite having many samples, at least one of three things must happen: the optimal empirical mean is unusually low; a’s mean is unusually high; or its radius is still large relative to the gap. For a horizon T, the last possibility is excluded once
To see the logic, if neither empirical deviation occurs, the optimal arm’s upper index exceeds its true mean, while the inferior arm’s index is below its own mean plus twice its radius. Once that twice-radius fits inside the gap, the inferior arm cannot beat the optimal index. The exceptional empirical events must therefore pay for any additional selections.
For each clock value n there are at most n² pairs of prefix counts to consider. Two one-sided probabilities of size n⁻⁴ produce a summable bound of at most 2/n². Including initialization and rounding gives the paper’s count bound
Multiplying by each gap and summing gives the expected regret guarantee
This is a bound on expectation, not a promise for every random run. The leading term contains inverse gaps. Nearby means take more evidence to distinguish, even though each mistake costs less. The displayed theorem on PDF20 of Silver’s lecture instead shows a sum of gaps; the original paper’s statement and proof resolve that discrepancy. The lecture’s index formula remains useful for intuition.
The bound is instance-dependent and becomes loose near a tie; it does not say actual regret diverges when all arms are equal. Equal-mean arms have zero gaps and contribute zero regret. The program also accepts a one-arm environment as a trivial zero-regret case, separately from the paper’s K≥2 theorem.
Reward units are part of the algorithm
For known support [L,U] with U>L, normalize rewards before applying this form of UCB1. Equivalently, use a radius scaled by the range:
The transformed ranking follows by multiplying normalized scores by U−L and adding L. Using the unit-range radius unchanged with rewards measured in hundreds changes the exploration rule. Gaussian or heavy-tailed rewards need suitable methods and assumptions; a visual resemblance to this formula does not transfer its theorem.
Expose the clock and the components of the index
Save this standard-library Python 3 program as ucb.py and run python3 ucb.py. select handles initialization before calling scores; the latter rejects zero-count input instead of serializing infinite scores. The learner receives only observed actions and rewards. Known synthetic means [0.25,0.45,0.70] are used by the environment and evaluator.
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 UCB1:
def __init__(self, arms):
integer(arms, 'arms', 1)
self.counts = [0] * arms; self.values = [0.] * arms
def scores(self):
n = sum(self.counts)
if not all(self.counts): raise ValueError('initialize every arm before computing finite scores')
return [q + math.sqrt(2 * math.log(n) / count) for q, count in zip(self.values, self.counts)]
def select(self):
for a, count in enumerate(self.counts):
if not count: return a
scores = self.scores()
return max(range(len(scores)), key=scores.__getitem__)
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 regret_bound(means, horizon):
means = probabilities(means); integer(horizon, 'horizon', len(means))
gaps = [max(means) - x for x in means]
return 8 * math.log(horizon) * sum(1 / g for g in gaps if g > 0) + (1 + math.pi**2 / 3) * sum(gaps)
def run(seed, steps=800):
integer(steps, 'steps', 3); means = [.25, .45, .7]; env = Bernoulli(means, seed)
agent = UCB1(3); loss = 0.; rows = []
for t in range(steps):
scores = agent.scores() if all(agent.counts) else None
a = agent.select(); r = env.pull(a)
if t < 12: rows.append(dict(completed=t, counts=list(agent.counts), means=list(agent.values), scores=scores, action=a, reward=r))
agent.observe(a, r); loss += max(means) - means[a]
return dict(counts=agent.counts, estimates=agent.values, pseudoregret=loss, early=rows)
def demo():
runs = [run(s) for s in range(30)]; n = 100
means = [.55, .4]; counts = [90, 10]
return dict(horizon=800, seeds=list(range(30)), pseudoregret=summary([x['pseudoregret'] for x in runs]),
theorem_expected_bound=regret_bound([.25, .45, .7], 800), trivial_path_bound=800 * .45,
index_example=dict(completed=n, counts=counts, estimates=means,
radii=[math.sqrt(2 * math.log(n) / c) for c in counts],
scores=[q + math.sqrt(2 * math.log(n) / c) for q, c in zip(means, counts)]),
single_seed=runs[0])
if __name__ == '__main__':
import json
print(json.dumps(demo(), indent=2, allow_nan=False))
For 30 seed labels 0–29 and 800 pulls per run, mean path pseudo-regret is 40.63 with standard error about 1.34484. The theorem’s expected-regret upper bound is approximately 335.7480 for this instance. The largest possible gap is 0.45, so the simpler pathwise bound 800×0.45=360 also holds. The observed mean lying below a theorem’s bound is a consistency check, not a proof of that theorem.
The first 12 decisions log counts, means and scores before the new reward is observed. In the fourth decision’s record, three pulls are complete and all counts equal one. This makes clock mistakes and accidental use of the current reward visible.
Computing all scores and their maximum costs O(K) per round; updating one mean costs O(1). The agent stores O(K) state, and the short teaching trace adds O(K) data per retained checkpoint. Running m repetitions of horizon T costs O(mTK); this bound includes the score scans, not just mean updates.
An upper index is not a universal safety margin
The theorem assumes fixed reward laws and bounded independent draws. Nonstationarity, dependent feedback, informative censoring or model misspecification can break its argument. An empirical interval becoming narrower does not prove that an old average still describes the current world.
UCB deliberately revisits apparently inferior arms. It can therefore lose to a more aggressive method on a short easy instance while retaining a useful worst-case guarantee over its stated model class. Thompson sampling introduces a prior and posterior sampling; contextual bandits can share evidence through features. Their estimates, assumptions and bounds must be stated separately.
Check the radius before trusting the curve
-
Why must the implementation deal with untried arms before computing finite scores?
Answer: Their counts are zero, so the radius would divide by zero and the empirical mean is undefined. Pulling each arm once supplies the missing observations; initializing a number alone does not.
-
Both arms have one pull, with rewards 1 and 0. Which logarithm appears in the next indices under this article’s convention?
Answer:
ln(2), because two pulls are complete. The scores are1+sqrt(2ln2)andsqrt(2ln2). Using an arm’s local count inside the logarithm would incorrectly remove exploration here. -
Holding T fixed, what happens to the leading suboptimal-count bound if a positive gap is halved?
Answer: Its
1/Delta²term becomes four times as large. Multiplication by the gap makes the leading regret contribution twice as large. This explains why the regret bound uses inverse gaps rather than gaps. -
Can you apply this unchanged implementation to rewards in
[0,100]and keep the same theorem?Answer: No. Normalize by 100 or scale the radius by 100 in the original units. The current program deliberately rejects rewards outside
[0,1]; lifting that check alone would not fix the algorithm’s units.
A confidence argument needs a sampling argument
Auer et al. combine concentration with control of adaptive arm counts. The textbook working draft presents a broader tunable UCB family, while Silver connects the radius to optimism. This article implements the original unit-range UCB1 rule, not every method carrying the UCB name. Its proof sketch follows the stated Theorem 1 reading scope; UCB2 and the paper’s other algorithms are not implemented here.
Make a prediction, then check
A rarely sampled arm has a lower empirical mean but a higher UCB index. Which does UCB1 choose?
Learning objectives
- Compute indices from completed pulls without dividing by zero or confusing local and global counts.
- State the stochastic bounded-reward assumptions and distinguish a theorem from an empirical curve.
Prerequisites & connections
Explore related knowledge →References
- Finite-time Analysis of the Multiarmed Bandit Problem
Peter Auer, Nicolò Cesa-Bianchi, Paul Fischer · 2002 - Reinforcement Learning: An Introduction — second-edition working draft (2014–2015)
Richard S. Sutton; Andrew G. Barto · 2015 - Lecture 9: Exploration and Exploitation
David Silver · 2015
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: 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. PDF55–56 §2.6 UCB selection and limits; actual guarantee and clock convention follow Auer PDF3/8–9. Read2026-09-23; historical remarks are not current impossibility claims. Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse. 7 paired equations and four explained exercises. Checked completed-pull clock, forced initialization, exact ties, mean-plus-radius arithmetic, inverse-gap expected bound, unit rescaling and count-derived loss. Within-arm IID and across-arm independence explicit; a fixed-prefix inequality is not treated as an adaptive confidence proof.
- Checked completed-pull clock, forced initialization, exact ties, mean-plus-radius arithmetic, inverse-gap expected bound, unit rescaling and count-derived loss. Within-arm IID and across-arm independence explicit; a fixed-prefix inequality is not treated as an adaptive confidence proof.
- 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:
- Finite-time Analysis of the Multiarmed Bandit Problem · 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.
- Reinforcement Learning: An Introduction — second-edition working draft (2014–2015) · PDF55–56 §2.6 UCB selection and limits; actual guarantee and clock convention follow Auer PDF3/8–9. Read2026-09-23; historical remarks are not current impossibility claims.
- Lecture 9: Exploration and Exploitation · Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse.
Related topics