Multi-Armed Bandits & Regret
Slot machines, regret, and why greedy play fails.
Greedy play can lose a fixed amount on every pull, forever; the best algorithms lose less and less. To tell them apart you need a precise model, a precise scoreboard, and one identity that turns regret into a question about how often each arm is pulled. This lesson builds all three and uses them to analyze greedy play, ε-greedy and explore-then-commit, with incremental estimates, optimistic initial values and drifting arms along the way.
What you’ll learn
- Formalize the stochastic -armed bandit, define expected regret and pseudo-regret, and prove the decomposition .
- Implement sample-average and incremental value estimates, and explain when a constant step size is the right choice.
- Prove that greedy play and constant-ε exploration have linear regret, and state when a decaying ε achieves logarithmic regret.
- Derive the regret bound of explore-then-commit, tune its exploration length, and explain what the tuning requires you to know.
- Explain optimistic initial values and the limits of a one-time push to explore, including on nonstationary arms.
The stochastic bandit and its regret
A stochastic multi-armed bandit has arms. Arm has a reward distribution , unknown to the learner, with mean . Write for the best mean and for arm 's suboptimality gap.
In rounds the learner chooses an arm , using only the history and perhaps its own coin flips, and then receives a reward drawn from , independently of everything before given . The rule mapping histories to (distributions over) arms is the learner's policy. The count is how often arm was pulled in the first rounds.
Condition on the arm chosen. Given (and the past), is a fresh draw from , so its conditional mean is . The tower rule gives
Group the rounds by arm. Each round contributes the mean of the arm it used, so the sum of the chosen means counts every arm's mean once per pull:
The counts add up to the horizon, , so . Subtract and take expectations:
Every pull of arm costs in expectation, whatever the policy. Bounding regret therefore means bounding how often each suboptimal arm is pulled, and every analysis in this topic starts here.
Three arms have means 0.8, 0.6 and 0.3. Over 1,000 rounds a policy pulls them 900, 70 and 30 times in expectation. What is its regret?
- 100
- 29
- 51
- 0, because it pulled the best arm most of the time
Show the answer
B. 29
The gaps are 0, 0.2 and 0.5, so . Equivalently, the policy earns in expectation against for always pulling the best arm.
Estimating values: averages and step sizes
Almost every bandit algorithm keeps an estimate of each arm's mean. The sample average of an arm's first rewards needs no stored history: write and peel off the last term to get the incremental form . It is the template of every learning rule in this course: new estimate = old estimate + step size × (target − old estimate). A constant step size changes what the estimate means.
Unroll one step at a time:
All the way back to the initial value :
The weights add up to , so this is a weighted average, but recent rewards weigh most and old ones fade geometrically: an exponential recency-weighted average with a memory of about rewards. The initial value's weight never vanishes in finite time, so the estimate is biased by , less and less.
import numpy as np
class EpsilonGreedy:
def __init__(self, k, eps=0.1, step=None, q0=0.0, seed=0):
self.q = np.full(k, q0, dtype=float) # value estimates
self.n = np.zeros(k, dtype=int) # pull counts
self.eps, self.step = eps, step # step=None: sample average
self.rng = np.random.default_rng(seed)
def act(self):
if self.rng.random() < self.eps: # explore
return int(self.rng.integers(len(self.q)))
best = np.flatnonzero(self.q == self.q.max())
return int(self.rng.choice(best)) # exploit, break ties at random
def update(self, arm, reward):
self.n[arm] += 1
alpha = 1.0 / self.n[arm] if self.step is None else self.step
self.q[arm] += alpha * (reward - self.q[arm])An ε-greedy agent with incremental updates: constant memory per arm and constant time per step. With eps=0 it is greedy; with q0 above every plausible reward it uses optimistic initial values (the last step of this lesson).
With a constant step size , what weight does the estimate give to the reward received 10 pulls before the most recent one?
Show the answer
0.035
The most recent reward has weight , and each step back multiplies by : . The last 10 rewards together carry of the total weight, so the estimate reacts within tens of pulls to a change in the arm.
Greedy and ε-greedy: linear regret, and the way out
The decomposition turns "this policy is bad" into a statement about pull counts. For greedy play the counts can be catastrophically wrong with constant probability, and for constant-ε exploration they are wrong by a constant fraction of .
Greedy. Take two Bernoulli arms with , and let greedy pull each arm once and then always pull the higher sample average (ties broken at random). With probability , arm 1's first reward is 0 and arm 2's is 1:
On that event arm 1's estimate is 0 and stays 0, because arm 1 is never pulled again, while arm 2's average is at least after pulls. So greedy pulls arm 2 in every remaining round:
For that is at least : linear. Constant ε. In every round each arm is chosen at random with probability at least , so and
The schedule must shrink like , but with the right constant. By round each arm has had about random pulls, enough that confusing two arms a gap apart has probability polynomially small in , with an exponent above 1 when is large enough. A schedule like still explores forever, since , and is greedy in the limit (GLIE), but each arm then gets only about random pulls: misidentification probabilities can decay too slowly to sum, leaving regret that grows polynomially in .
The catch is : the theorem needs a lower bound on the smallest gap, which is exactly what you do not know. In Auer et al.'s experiments a well-tuned schedule was often the best policy they tried, but its performance degraded rapidly when the constant was off.
Explore-then-commit
The cleanest way to separate learning from earning is to do one and then the other. Explore-then-commit (ETC) pulls every arm times in turn, then commits to the arm with the best sample average for the remaining rounds. Its analysis needs one more ingredient: a random variable is -subgaussian if for all , which gives the tail bound . Rewards in are -subgaussian (Hoeffding's lemma), hence also 1-subgaussian.
Let arm 1 be optimal. Exploration is deterministic (each arm exactly times), and arm gets all remaining rounds if it wins the comparison:
Rewrite the event around the gap, with the average of arm 's exploration rewards:
An average of independent 1-subgaussian variables is -subgaussian, and the difference of two independent ones is -subgaussian (variance proxies add). The tail bound with gives
Multiply by and sum over arms, using the regret decomposition. For two arms with gap the bound is ; setting its derivative in to zero gives the tuned length and the resulting bound:
Two arms with gap and horizon . How many pulls per arm does the tuned explore-then-commit use before committing?
Show the answer
1288
, so about a quarter of the horizon goes to exploration. The bound is , against for splitting the pulls evenly forever.
The tuned needs the gap , which is unknown, and the horizon . If may depend only on , the best worst-case guarantee falls to order , against order when is known (Lattimore & Szepesvári, ch. 6). ETC is also wasteful on easy instances: with a large gap a few pulls would settle the question, yet the schedule keeps exploring.
Both problems have the same fix: decide from the data when to stop exploring an arm. Eliminating an arm once a confidence interval separates it from the leader adapts to the unknown gaps (Best-Arm Identification), and UCB never commits at all but keeps every arm's exploration proportional to how plausible it still is (Optimism: Upper Confidence Bounds).
Optimistic initial values and drifting arms
A cheap way to make a greedy learner explore is to start every estimate far above any plausible reward, an optimistic initialization. Every arm then disappoints when pulled, its estimate drops below the untried ones, and greedy play works through all the arms before settling. In Sutton and Barto's 10-armed testbed (true values drawn from a standard normal), greedy play with and eventually beats ε-greedy with started at , after a slow start.
The push is temporary. With sample averages it lasts exactly one pull per arm, since erases the initial value. With a constant step size it fades geometrically. After that the learner is plain greedy, with all its failure modes. Optimism that is renewed by uncertainty, rather than spent once, is the idea behind UCB.
A greedy learner starts every estimate at for rewards in and updates by sample averages (). What does the optimism buy it?
- Logarithmic regret on every instance
- Exactly one pull of each arm, after which it behaves like ordinary greedy play
- Exploration that continues forever at a slowly decreasing rate
- Nothing: greedy ignores initial values
Show the answer
B. Exactly one pull of each arm, after which it behaves like ordinary greedy play
The first update of an arm replaces its estimate by its first reward, , so the optimism forces each arm to be tried once and is then gone. From there the learner can lock onto a worse arm exactly as greedy play does. With a constant step size the optimism decays over several pulls instead, but it still runs out.
Real arms drift: click rates change with seasons, prices and fashion. In a nonstationary bandit the sample average reacts ever more slowly, since the -th reward has weight , while a constant step size keeps tracking. UCB has forgetful versions too: discounted UCB and sliding-window UCB compute their indices from discounted or recent data only (Garivier & Moulines, 2011).
There is a genuine tension, not just a tuning problem. Lattimore and Szepesvári (Theorem 31.2) show that, already with two arms, a policy with regret on a stationary bandit with gap has regret at least on some bandit whose means switch at most twice while keeping a gap of at least , as soon as is large enough. A policy with logarithmic regret on fixed arms must therefore suffer regret of order on some switching problem. Being ready for change means checking the apparently worse arms often, and that costs regret when nothing changes.
Key takeaways
- A stochastic bandit has arms with unknown means; regret is minus the expected reward, and it decomposes as for every policy.
- Incremental updates with give sample averages; a constant gives an exponential recency-weighted average that tracks drifting arms but never settles.
- Greedy play locks onto a worse arm with constant probability and constant-ε exploration pays per arm per round: both have linear regret. A decaying achieves logarithmic regret, but only with a lower bound on the gap.
- Explore-then-commit has regret at most ; tuned with the gap it is , but the tuning needs , and without it the worst case is of order .
- Optimistic initial values force early exploration and then run out. Drifting arms call for forgetting, and a policy with logarithmic regret on fixed arms must pay heavily on some switching ones.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Why can the regret of any policy be written as ?
- Because the policy pulls each arm equally often in expectation
- Because given the arm chosen in a round, that round's reward has the arm's mean as its conditional expectation, so each pull of arm costs in expectation
- Because rewards are bounded in
- Because the policy is deterministic
Show the answer
B. Because given the arm chosen in a round, that round's reward has the arm's mean as its conditional expectation, so each pull of arm costs in expectation
by the tower rule, since the reward is drawn from the chosen arm independently of the past. Grouping rounds by arm and using gives the identity, for any policy, randomized or not, adaptive or not.
ε-greedy with plays 4 arms with gaps 0, 0.1, 0.2 and 0.3 for 10,000 rounds. What is the guaranteed lower bound on its regret from random exploration alone?
- 75
- 7.5
- 300
- 0, because the estimates converge
Show the answer
A. 75
Each arm is pulled at random with probability at least per round, so , and the bound keeps growing linearly with .
In tuned explore-then-commit, . Ignoring the logarithm, what happens to the exploration length if the gap is halved?
- It halves
- It doubles
- It stays the same
- It grows about fourfold
Show the answer
D. It grows about fourfold
scales like : telling apart two arms that are half as far apart takes four times the samples, because a sample average's error shrinks like . The regret bound scales like , since each of those pulls costs only .
Which step-size sequence makes the incremental estimate of a stationary arm converge with probability 1, by the Robbins–Monro conditions?
Show the answer
C.
The conditions are and . For : the harmonic series diverges and . That is the sample average.
Go deeper
- Regret Lower Bounds · Lai–Robbins and minimax bounds: what no algorithm can beat, and why log T appears.
- Best-Arm Identification · When only the final choice counts: fixed-confidence and fixed-budget exploration.
- Adversarial Bandits & EXP3 · Regret against an adversary: exponential weights with importance-weighted estimates.
Further reading
- T. Lattimore & C. Szepesvári, Bandit Algorithms, ch. 4 and 6 (Cambridge University Press, 2020).
- P. Auer, N. Cesa-Bianchi & P. Fischer, "Finite-time analysis of the multiarmed bandit problem," Machine Learning 47, 235–256 (2002).
- R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 2 (MIT Press, 2nd ed., 2018).