Bandits and exploration¶
A bandit is reinforcement learning with the hard parts removed except one: you must act to learn, and every action spent learning is an action not spent earning. The whole page is about one trade-off, exploration against exploitation, and the three good answers to it: act randomly sometimes, act optimistically, or act on a sample of your beliefs.
10,000 ft
Supervised learning is told the right answer. A reinforcement learner is only told how good the answer it chose was, so it has to try things to find out what is good, and trying costs. The multi-armed bandit isolates exactly this problem: no states, no delayed consequences, just repeated choices with noisy rewards. It is the place where exploration was first made rigorous (Thompson in 1933, Robbins in 1952, Lai and Robbins in 1985) and its answers reappear everywhere later: UCB inside the tree search of AlphaZero, ε-greedy in DQN, the incremental-average update in every temporal-difference method, the softmax preference update that grows into policy gradients. Bandits also run in production on their own: ad and news selection, recommendation, adaptive clinical trials and A/B tests that stop wasting traffic. Add states and you get a Markov decision process.
2,000 ft
You face \(k\) arms with unknown average rewards \(\mu_1,\dots,\mu_k\). Each round you pick one, see a noisy reward, and update your estimate of that arm. The score is regret: how much reward you lost compared with always pulling the best arm. Good algorithms keep regret growing like \(\log T\); naive ones let it grow like \(T\).
- Greedy (always pick the best-looking arm) can lock onto a bad arm forever.
- ε-greedy explores at random a fixed fraction of the time: simple, but regret grows linearly.
- UCB adds an uncertainty bonus to each estimate and picks the highest: optimism in the face of uncertainty.
- Thompson sampling samples a plausible mean for each arm from its posterior and picks the highest sample: probability matching.
- No algorithm can beat \(\Omega(\log T)\) regret on every problem (Lai and Robbins); UCB and Thompson sampling achieve it.
Ground level¶
The problem, precisely¶
There are \(k\) arms. Pulling arm \(a\) gives a reward drawn from a fixed distribution \(P_a\) with mean \(\mu_a\), independently of everything else. You do not know the \(P_a\). At each round \(t = 1,\dots,T\) you choose \(A_t\) based on everything seen so far and receive \(R_t \sim P_{A_t}\). Write \(\mu^\ast = \max_a \mu_a\) and the gap of arm \(a\) as \(\Delta_a = \mu^\ast - \mu_a\).
Maximising total reward is equivalent to minimising the regret
where \(N_a(T)\) is the number of times arm \(a\) was pulled. The second form (the regret decomposition, derived in the maths) says regret is just how often you pulled each bad arm, weighted by how bad it is. Every algorithm below is a strategy for keeping the pulls of bad arms small without ever being sure which arms are bad.
Throughout this page we use one running example, five arms with Bernoulli rewards (think five headlines, reward 1 if clicked):
| Arm | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| true click rate \(\mu_a\) | 0.10 | 0.25 | 0.40 | 0.55 | 0.60 |
| gap \(\Delta_a\) | 0.50 | 0.35 | 0.20 | 0.05 | 0 |
Arm 4 is best, but arm 3 is only 0.05 behind: telling them apart takes hundreds of pulls, because the standard deviation of one Bernoulli(0.6) reward is \(\sqrt{0.6 \cdot 0.4} \approx 0.49\), ten times the gap.
Estimating an arm: the update rule you will see everywhere¶
The natural estimate of \(\mu_a\) is the sample mean of the rewards seen from arm \(a\). You never need to store the rewards; after the \(n\)-th reward \(R_n\) from that arm,
Read it as new estimate = old estimate + step size × (target − old estimate). That one line is the skeleton of nearly every learning rule in reinforcement learning: Monte Carlo prediction replaces the target with a return, TD learning replaces it with \(r + \gamma V(s')\), Q-learning with \(r + \gamma \max_{a'} Q(s',a')\), and gradient descent on a squared error is the same rule with a learned function in place of a table.
If the arm's mean drifts over time, averaging over all history is wrong: a reward from a thousand pulls ago counts as much as the last one. A constant step size \(\alpha\) fixes this. Unrolling the update gives
an exponentially weighted average in which a reward's weight halves every \(\ln 2 / \alpha\) steps (about 7 steps for \(\alpha = 0.1\)). Step sizes \(1/n\) converge to the true mean; constant \(\alpha\) never converges but keeps tracking. Which one you want depends on whether the world is stationary, and in full RL it almost never is, because the agent's own improving policy changes the data it sees.
Greedy: why you cannot just pick the best-looking arm¶
Pull each arm once, then always pull the arm with the highest sample mean. On the running example this locks in a wrong arm in more than half the runs. Suppose the first pulls give arm 3 a reward of 1 and arm 4 a reward of 0. Arm 3's estimate is 1.0, arm 4's is 0.0. Greedy pulls arm 3 again and again; its estimate settles near 0.55, which is still above arm 4's estimate of 0.0, so arm 4 is never pulled again and the mistake is never discovered. The estimate of the arm you avoid can never be corrected, because the only way to correct it is to pull it.
In our simulation (200 runs; the code is in Build it) greedy ends with arm 4 as its most-pulled arm in only 45% of runs, and its regret grows linearly: 1,753 after 20,000 pulls.
Exploitation is not the same as estimation error
Greedy's failure is not that its estimates are noisy. It is that the data it collects depends on its estimates, so an early unlucky estimate is self-confirming. Every adaptive system that learns from the consequences of its own choices (a recommender trained on what it chose to show, a credit model trained only on approved loans) has this feedback loop.
ε-greedy: explore at random a fixed fraction of the time¶
With probability \(\varepsilon\) pick an arm uniformly at random; otherwise pick greedily. Every arm keeps being pulled about \(\varepsilon T / k\) times, so every estimate converges, and the greedy choice is eventually right. But the exploration never stops, and it is undirected: it spends as much on arm 0 (clearly terrible after a few dozen pulls) as on arm 3 (genuinely uncertain). The forced exploration alone costs
that is 440 of regret over 20,000 pulls, growing linearly forever. The simulation measured 507: the extra 67 is the greedy part's early mistakes. Decaying \(\varepsilon_t \propto 1/t\) fixes the linear growth in theory, but the right constant depends on the unknown gaps.
ε-greedy is still the default exploration in value-based deep RL (DQN anneals ε from 1.0 to 0.1) because it needs nothing but an argmax.
A close relative is softmax (Boltzmann) exploration: pick arm \(a\) with probability \(\propto e^{Q(a)/\tau}\). It explores bad arms less than good ones, which is better than uniform, but it still ignores how uncertain each estimate is.
Optimism in the face of uncertainty: UCB¶
The key idea: an arm deserves to be pulled if it could plausibly be the best. So for each arm compute an optimistic, high-probability upper bound on its mean, and pull the arm with the highest bound. UCB1 (Auer, Cesa-Bianchi and Fischer, 2002) uses
The bonus is large for arms pulled rarely and shrinks like \(1/\sqrt{N_a}\). Two things can make an arm's bound high: a high estimate (exploit) or a small count (explore). Either way pulling it is useful: either it really is good and you gain reward, or its bound collapses and you have learned it is not.
A worked choice. At \(t = 100\), suppose:
| Arm | \(\hat\mu_a\) | \(N_a\) | bonus \(\sqrt{2\ln 100/N_a}\) | UCB |
|---|---|---|---|---|
| A | 0.60 | 50 | 0.429 | 1.029 |
| B | 0.50 | 10 | 0.960 | 1.460 |
| C | 0.30 | 3 | 1.752 | 2.052 |
UCB1 pulls C, the arm with the worst estimate, because three pulls say almost nothing. As counts grow the bonuses shrink, and arms whose bound falls below the best arm's estimate stop being pulled, except that the \(\ln t\) in the numerator slowly grows, so every arm is revisited at ever-longer intervals. That is exactly logarithmic exploration.
Where does \(\sqrt{2\ln t/N}\) come from? From Hoeffding's inequality: the sample mean of \(N\) rewards in \([0,1]\) undershoots the true mean by more than \(\varepsilon\) with probability at most \(e^{-2N\varepsilon^2}\). Setting that probability to \(t^{-4}\) and solving for \(\varepsilon\) gives \(\varepsilon = \sqrt{2\ln t / N}\). So the bound is wrong with probability that shrinks fast enough for the total number of mistakes to stay finite. The full argument is in the maths.
On the running example UCB1 finds the best arm in every one of 200 runs, but its regret, 291 at \(t = 20{,}000\), is far above Thompson sampling's. The culprit is arm 3: with gap 0.05 its bonus keeps pulling it, and Hoeffding's bound is conservative for Bernoulli arms with means near 0.5 (it assumes the worst possible variance). KL-UCB replaces the Hoeffding radius with the tightest Bernoulli confidence bound and is asymptotically optimal.
Why optimism works
If you are optimistic about an arm and you are wrong, pulling it corrects you quickly. If you are pessimistic about an arm and you are wrong, you never pull it and never find out. Optimism makes mistakes self-correcting; pessimism makes them permanent. That asymmetry is the whole argument, and it carries over to full RL (optimistic initial values, exploration bonuses, UCB-style planning in MCTS).
A cheap form of optimism is optimistic initial values: start every \(Q(a)\) at, say, 1.0 on a \([0,1]\) reward. Every arm looks disappointing after its first pulls, so the greedy learner tries them all. It works for stationary problems and costs nothing, but its exploration is a transient: once the initial value is averaged away, it is greedy again.
Thompson sampling: act on a sample of your beliefs¶
Keep a posterior distribution over each arm's mean. Each round, draw one sample from each posterior and pull the arm whose sample is highest. That is the entire algorithm (Thompson, 1933). For Bernoulli rewards with a uniform prior, the posterior after \(s\) successes in \(n\) pulls is \(\operatorname{Beta}(1+s,\, 1+n-s)\) (see Bayesian estimation), so the update is two counters per arm.
Thompson sampling pulls each arm with exactly the probability that it is the best arm under your current beliefs. It explores an arm in proportion to how plausible it is that the arm is optimal, which is precisely the right currency. A worked example:
| Arm | data | posterior | mean | sd | P(sample is highest) |
|---|---|---|---|---|---|
| A | 6 of 10 | Beta(7, 5) | 0.583 | 0.137 | 0.496 |
| B | 25 of 50 | Beta(26, 26) | 0.500 | 0.069 | 0.161 |
| C | 1 of 2 | Beta(2, 2) | 0.500 | 0.224 | 0.343 |
UCB and Thompson reach the same verdict here (explore C before B) for the same reason, but by different mechanisms: UCB with a deterministic bonus, Thompson with randomness. The randomness is a practical advantage: when rewards arrive late or in batches (an ad shown now is clicked an hour later), a deterministic rule like UCB keeps choosing the same arm until the feedback lands, while Thompson spreads its choices naturally. Chapelle and Li (2011) found it state of the art on simulated data, display advertising and Yahoo! news recommendation, sometimes significantly better than UCB, and markedly more robust than UCB when feedback was delayed by up to an hour; they argued it should be a standard baseline.
On the running example Thompson sampling has regret 65 after 20,000 pulls, against 291 for UCB1 and 507 for ε-greedy.
How good can any algorithm be?¶
Lai and Robbins (1985) proved a lower bound that every reasonable algorithm must pay. For any algorithm whose regret is \(o(T^c)\) for every \(c > 0\) on every problem (a "consistent" algorithm), each suboptimal arm must be pulled at least
times, where KL is the Kullback–Leibler divergence between the arm's reward distribution and the best arm's. The intuition is information-theoretic: to rule out that arm \(a\) is secretly the best, you need enough samples to distinguish its distribution from the best one, and each sample buys about \(\mathrm{KL}\) nats of evidence.
For the running example, the Bernoulli KL divergences from 0.6 are 0.551, 0.253, 0.081 and 0.0051 nats for arms 0–3, so arm 3 needs about \(\ln T / 0.0051 \approx 196 \ln T\) pulls and contributes two-thirds of the bound's constant (\(\sum_a \Delta_a / \mathrm{KL}_a = 14.48\)). Note the bound is asymptotic: at \(T = 20{,}000\) the formula gives \(14.48 \ln T \approx 143\), more than Thompson's measured 65, because 1,900 pulls of arm 3 is not yet negligible next to 20,000. UCB1, KL-UCB and Thompson sampling all achieve logarithmic regret; KL-UCB and Thompson sampling (for Bernoulli arms, Kaufmann, Korda and Munos 2012) match the Lai–Robbins constant exactly.
A second, problem-independent benchmark: in the worst case over all problems with \(k\) arms, no algorithm can guarantee regret better than order \(\sqrt{kT}\), and good algorithms achieve it up to constant or logarithmic factors. Gap-dependent bounds (\(\log T/\Delta\)) are tighter when gaps are large; the worst case is gaps of size about \(\sqrt{k/T}\), too small to detect cheaply but large enough to cost.
Beyond the basic bandit¶
- Contextual bandits. Each round you see a feature vector (the user, the query) before choosing. LinUCB (Li, Chu, Langford and Schapire, 2010) models each arm's reward as linear in the context and adds a confidence-ellipsoid bonus \(\alpha\sqrt{\mathbf{x}^\top A_a^{-1}\mathbf{x}}\), where \(A_a\) is that arm's regularised design matrix; it was evaluated on Yahoo!'s front-page news module. Contextual bandits are the honest model of most recommendation and personalisation problems: the action does not change who the next user is.
- Adversarial bandits. Drop the assumption that rewards are drawn from fixed distributions: an adversary picks them. EXP3 (Auer, Cesa-Bianchi, Freund and Schapire, 2002) keeps exponential weights and mixes in uniform exploration; it guarantees regret of order \(\sqrt{Tk\ln k}\) against the best single arm in hindsight.
- Bayes-optimal bandits. If you have a prior and a discount factor, the exploration problem is itself an MDP over belief states, and for independent arms it has an elegant exact solution: the Gittins index (Gittins and Jones, 1974; Gittins, 1979). Compute one number per arm from its own posterior alone and pull the arm with the highest index. Elegant, but expensive and fragile outside its assumptions, so practitioners rarely use it.
- Best-arm identification. Sometimes you do not care about reward during the experiment, only about naming the best arm at the end with confidence. That is a different objective (pure exploration), and it is what an A/B test is really for.
- Non-stationary bandits. Means drift. Use constant step sizes, sliding windows, or discounted counts, and accept that you can never stop exploring.
Exploration in full RL¶
In an MDP, exploration is harder because rewards can be many steps away: random actions reach a state ten steps deep with probability that shrinks exponentially in the depth. The bandit ideas generalise:
- ε-greedy and entropy bonuses (undirected): DQN uses ε-greedy; policy-gradient methods like PPO add an entropy term to keep the policy stochastic.
- Count-based optimism: add a bonus \(\beta/\sqrt{N(s)}\) to the reward, the RL analogue of the UCB bonus. In large state spaces, exact counts are replaced by pseudo-counts from a density model (Bellemare et al., 2016) or by the prediction error of a network trying to match a fixed random network (random network distillation, Burda et al., 2018), both of which made progress on Montezuma's Revenge, the Atari game with very sparse rewards.
- UCB in tree search: UCT (Kocsis and Szepesvári, 2006) treats each node of a Monte Carlo search tree as a bandit; AlphaZero's PUCT rule is a variant with the policy network as a prior (model-based RL and planning).
- Posterior sampling for RL: sample an entire MDP from the posterior, act optimally in it for an episode, repeat; Thompson sampling lifted to MDPs.
In RL for language models, exploration mostly comes from sampling several completions per prompt at non-zero temperature: GRPO, for example, scores a group of sampled answers to each question and pushes up the better ones (RL with verifiable rewards). The bandit lesson still applies: a policy that never samples a correct answer cannot be reinforced towards it.
First principles¶
Why exploration is unavoidable. Information about an arm only arrives when you pull it. So the value of a pull has two parts: the reward now, and the information it buys, which is worth something only because you will act on it later. Greedy ignores the second part. A policy that always exploits is a policy that values information at zero, and the lock-in example shows that can cost linear regret. Any good algorithm must put a positive price on information, and the price must fall as uncertainty falls.
Why logarithmic. Suppose arm \(a\) has gap \(\Delta\). To be confident it is worse than the best arm, you need roughly \(1/\Delta^2\) samples (the standard error of a mean is \(\sigma/\sqrt{n}\)). But "confident" must keep tightening: over a horizon of \(T\) pulls you can afford a mistake probability of about \(1/T\), and by Hoeffding the samples needed for error probability \(\delta\) grow like \(\ln(1/\delta)/\Delta^2\). So you pay about \(\ln T/\Delta^2\) pulls at cost \(\Delta\) each: regret \(\approx \ln T/\Delta\) per bad arm. That is UCB1's bound up to constants, and the Lai–Robbins bound with KL in place of \(\Delta^2\) (for Bernoulli arms, \(\mathrm{KL} \approx \Delta^2/(2\mu(1-\mu))\) for small gaps).
What fixed-budget exploration costs. The A/B-test strategy is explore-then-commit: pull every arm \(m\) times, then commit to the best-looking one. With two arms and gap \(\Delta\), it pays \(m\Delta\) during exploration and, by Hoeffding, picks the wrong arm with probability at most \(e^{-m\Delta^2/2}\), paying \(T\Delta\) if it does. With \(\Delta\) known you can tune \(m\) to get logarithmic regret; with \(\Delta\) unknown the best fixed choice is \(m \propto T^{2/3}\), which gives regret of order \(T^{2/3}\), worse than the \(\sqrt{T}\) worst case that adaptive algorithms achieve. Adaptivity, stopping exploration of an arm as soon as the data condemn it, is what buys the improvement.
Why randomisation helps. Thompson sampling's randomness is not noise for its own sake. It makes the probability of pulling an arm a smooth function of the evidence, which is robust to delayed and batched feedback and needs no tuned confidence radius. The price is that its analysis is harder: logarithmic regret for Thompson sampling was only proved in 2012, 79 years after the algorithm was proposed.
The maths¶
Setup and notation
Arms \(a \in \{1,\dots,k\}\) with reward distributions \(P_a\) on \([0,1]\), means \(\mu_a\); \(\mu^\ast = \max_a \mu_a\), \(\Delta_a = \mu^\ast - \mu_a\). \(N_a(t)\) = pulls of \(a\) in rounds \(1..t\); \(\hat\mu_a(t)\) = their sample mean. Regret \(\mathcal{R}_T = T\mu^\ast - \mathbb{E}\sum_{t\le T} R_t\).
Derivation: the regret decomposition
Condition on the arm chosen. \(\mathbb{E}[R_t \mid A_t] = \mu_{A_t}\), so
Since \(\sum_a N_a(T) = T\), we can write \(T\mu^\ast = \sum_a \mu^\ast\, \mathbb{E}[N_a(T)]\) and subtract:
So bounding regret reduces to bounding the expected number of pulls of each suboptimal arm.
Derivation: the UCB1 confidence radius from Hoeffding's inequality
Hoeffding. If \(X_1,\dots,X_n\) are independent in \([0,1]\) with mean \(\mu\), then for \(\varepsilon > 0\)
Choose the failure probability \(\delta = t^{-4}\) and solve \(e^{-2n\varepsilon^2} = t^{-4}\): \(\varepsilon = \sqrt{2\ln t / n}\). So \(\hat\mu_a + \sqrt{2\ln t/N_a}\) is an upper confidence bound that fails with probability at most \(t^{-4}\).
Why a suboptimal arm stops being pulled. UCB1 pulls a suboptimal arm \(a\) at round \(t\) only if its index beats the best arm's. That requires at least one of: (i) the best arm's bound is below \(\mu^\ast\) (probability \(\le t^{-4}\)); (ii) arm \(a\)'s estimate is above \(\mu_a + \sqrt{2\ln t/N_a}\) (probability \(\le t^{-4}\)); (iii) the radius itself is wider than half the gap, \(2\sqrt{2\ln t/N_a} > \Delta_a\), which is impossible once \(N_a \ge 8\ln t/\Delta_a^2\). Summing the failure probabilities over all rounds and all possible counts gives a constant, so
This is Theorem 1 of Auer, Cesa-Bianchi and Fischer (2002). For the running example at \(T = 20{,}000\) it evaluates to 2,370, eight times the measured 291: worst-case bounds are loose, which is why you simulate.
The Lai–Robbins lower bound
For any consistent algorithm and reward distributions from a one-parameter family (Bernoulli, Gaussian with known variance, …),
For Bernoulli arms \(\mathrm{KL}(p\,\|\,q) = p\ln\frac{p}{q} + (1-p)\ln\frac{1-p}{1-q}\). The proof is a change-of-measure argument: if the algorithm pulled arm \(a\) fewer times than this, it could not distinguish the true problem from a modified one in which arm \(a\) is slightly better than \(a^\ast\), so it would suffer linear regret on that modified problem, contradicting consistency.
Thompson sampling for Bernoulli arms
Prior \(\theta_a \sim \operatorname{Beta}(1,1)\). After \(s_a\) successes and \(f_a\) failures the posterior is \(\operatorname{Beta}(1+s_a, 1+f_a)\), with mean \(\frac{1+s_a}{2+s_a+f_a}\) and variance \(\frac{(1+s_a)(1+f_a)}{(2+s_a+f_a)^2(3+s_a+f_a)}\). Each round: draw \(\tilde\theta_a \sim \operatorname{Beta}(1+s_a, 1+f_a)\) for every arm, pull \(A_t = \arg\max_a \tilde\theta_a\), then increment \(s_{A_t}\) or \(f_{A_t}\). By construction \(\Pr(A_t = a \mid \text{data}) = \Pr(a \text{ is optimal} \mid \text{data})\). For Gaussian rewards use a Normal posterior; for anything else, any approximate posterior you can sample from (bootstrap ensembles are the usual deep-learning substitute).
The gradient bandit: the seed of policy gradients
Keep a preference \(H(a)\) per arm and act with \(\pi(a) = e^{H(a)} / \sum_b e^{H(b)}\). To maximise \(J = \mathbb{E}_{A\sim\pi}[\mu_A] = \sum_a \pi(a)\mu_a\), take its gradient: \(\partial \pi(b)/\partial H(a) = \pi(b)(\mathbf{1}[a{=}b] - \pi(a))\), so
for any constant baseline \(\bar R\) (it cancels because \(\sum_b \pi(b)(\mathbf{1}[a{=}b]-\pi(a)) = 0\)). Replacing the expectation by the one sample you observe gives the stochastic update \(H(a) \leftarrow H(a) + \alpha (R_t - \bar R_t)(\mathbf{1}[a{=}A_t] - \pi(a))\). This is REINFORCE with a baseline, for a one-step problem; policy gradients generalise it to sequences, and the baseline becomes the critic of actor-critic methods.
History¶
From drug trials to slot machines to ad servers
William R. Thompson (1933), writing in Biometrika about choosing between two medical treatments, proposed allocating patients according to the probability that each treatment is better: Thompson sampling, decades before anyone called it that. Herbert Robbins (1952) framed the "sequential design of experiments", and the slot-machine name stuck (a "one-armed bandit" is a slot machine; a \(k\)-armed bandit has \(k\) levers). Gittins and Jones (1974) and Gittins (1979) found the index solution to the discounted Bayesian problem. Lai and Robbins (1985) proved the logarithmic lower bound and built the first asymptotically optimal upper-confidence rules. Auer, Cesa-Bianchi and Fischer (2002) gave UCB1 and its finite-time analysis, the version everyone implements. Thompson sampling was rediscovered by industry: Chapelle and Li (2011) at Yahoo! showed it working on display ads and news, Agrawal and Goyal (2012) gave the first logarithmic regret proof, and Kaufmann, Korda and Munos (2012) proved it asymptotically optimal for Bernoulli rewards. LinUCB (2010) brought contextual bandits to news recommendation. In 1989 Watkins's thesis introduced the term "action value" and possibly the first use of ε-greedy, according to Sutton and Barto's historical notes.
Build it¶
The five-arm example, all algorithms, vectorised over 200 independent runs (NumPy, about two seconds):
import numpy as np
p = np.array([0.10, 0.25, 0.40, 0.55, 0.60]) # true click rates; arm 4 is best
K, T, R = len(p), 20000, 200 # arms, steps, independent runs
rng = np.random.default_rng(0)
def run(policy):
n = np.zeros((R, K)); s = np.zeros((R, K)) # pulls and total reward per arm
regret = np.zeros((R, T)); rows = np.arange(R)
for t in range(T):
a = policy(n, s, t)
r = rng.random(R) < p[a] # Bernoulli reward
n[rows, a] += 1; s[rows, a] += r
regret[:, t] = p.max() - p[a] # expected regret of this pull
return regret.cumsum(1).mean(0), (n.argmax(1) == p.argmax()).mean()
def mean(n, s): return np.where(n > 0, s / np.maximum(n, 1), 0.0)
def greedy(n, s, t):
if t < K: return np.full(R, t) # pull each arm once
return mean(n, s).argmax(1)
def eps_greedy(eps):
def pol(n, s, t):
explore = rng.random(R) < eps
return np.where(explore, rng.integers(0, K, R), greedy(n, s, t))
return pol
def ucb1(n, s, t):
if t < K: return np.full(R, t)
return (mean(n, s) + np.sqrt(2 * np.log(t) / n)).argmax(1)
def thompson(n, s, t):
return rng.beta(1 + s, 1 + n - s).argmax(1) # one posterior sample per arm
for name, pol in [("greedy", greedy), ("eps-greedy 0.1", eps_greedy(0.1)),
("eps-greedy 0.01", eps_greedy(0.01)), ("UCB1", ucb1),
("Thompson", thompson)]:
reg, hit = run(pol)
print(f"{name:16s} regret@100 {reg[99]:6.1f} @1000 {reg[999]:6.1f} "
f"@20000 {reg[-1]:6.1f} best arm most-pulled {hit:.0%}")
greedy regret@100 10.6 @1000 90.6 @20000 1753.2 best arm most-pulled 45%
eps-greedy 0.1 regret@100 9.1 @1000 44.3 @20000 507.0 best arm most-pulled 96%
eps-greedy 0.01 regret@100 12.2 @1000 72.1 @20000 456.1 best arm most-pulled 66%
UCB1 regret@100 13.8 @1000 70.2 @20000 291.4 best arm most-pulled 100%
Thompson regret@100 9.3 @1000 29.2 @20000 65.1 best arm most-pulled 100%
Read the table across time, not just at the end. At \(t = 100\) UCB1 is the worst of the five: it is still paying to explore every arm. ε = 0.01 has lower final regret than ε = 0.1 but finds the best arm in only 66% of runs: too little exploration looks cheap until the lock-ins add up.
The probability-matching example from the Thompson section:
import numpy as np
rng = np.random.default_rng(1)
arms = {"A": (6, 10), "B": (25, 50), "C": (1, 2)} # (successes, pulls)
S = np.stack([rng.beta(1 + s, 1 + n - s, 200_000) for s, n in arms.values()])
for (k, (s, n)), share in zip(arms.items(), np.bincount(S.argmax(0), minlength=3) / S.shape[1]):
a, b = 1 + s, 1 + n - s
mean, sd = a / (a + b), np.sqrt(a * b / ((a + b) ** 2 * (a + b + 1)))
print(f"arm {k}: Beta({a},{b}) mean {mean:.3f} sd {sd:.3f} P(chosen) {share:.3f}")
arm A: Beta(7,5) mean 0.583 sd 0.137 P(chosen) 0.496
arm B: Beta(26,26) mean 0.500 sd 0.069 P(chosen) 0.161
arm C: Beta(2,2) mean 0.500 sd 0.224 P(chosen) 0.343
Things to try
- Make the gap tiny: set arm 3 to 0.59. Which algorithm suffers most, and does UCB1 still find the best arm in every run by \(T = 20{,}000\)?
- Replace UCB1's radius with KL-UCB: the largest \(q\) with \(N_a\,\mathrm{KL}(\hat\mu_a \,\|\, q) \le \ln t\) (solve by bisection). Compare its regret with Thompson sampling.
- Make the problem non-stationary: swap the means of arms 3 and 4 at \(t = 10{,}000\). Watch sample-mean methods fail, then fix them with a constant step size or a sliding window.
- Delay feedback: reveal rewards only every 100 rounds. Compare UCB1 and Thompson sampling.
- Add optimistic initialisation (start counts at one fake success per arm) to greedy and see how much of the lock-in it removes.
In practice¶
- Bandit or A/B test? An A/B test fixes the split, then commits; it is designed for unbiased effect estimates and valid confidence intervals. A bandit shifts traffic as evidence arrives; it is designed to lose less reward during the experiment. If you need to report the effect size, beware: sample means of adaptively sampled arms are biased (typically downward for arms the algorithm stops pulling after bad luck; Nie et al., 2018). Many teams run a bandit for allocation and a held-out uniform slice for measurement.
- Default choice. Thompson sampling with a Beta (binary rewards) or Normal (continuous) posterior is the robust default: no tuning, good with delays, easy to extend to contexts with a Bayesian linear model.
- Rewards are rarely what you want. A click is a proxy. Optimising click-through can promote clickbait; the bandit will find whatever the reward actually rewards. This is the bandit version of reward design, and the same failure mode as reward hacking in RLHF.
- Off-policy evaluation. Logged bandit data (context, action, reward, probability of the action) lets you estimate how a new policy would have done, by inverse-propensity weighting. Always log the propensity; it is the first thing you will wish you had.
Check yourself¶
Two arms: A has true mean 0.6, B has 0.5. Greedy pulls each once; A returns 0 and B returns 1. What happens next, and why is the mistake permanent?
Greedy's estimates are A = 0, B = 1, so it pulls B. B's estimate will drift towards 0.5 but can never fall to 0 (it has at least the one success), while A's estimate stays at exactly 0 because A is never pulled again. Greedy pulls B forever and pays \(0.1\) regret per round, linear regret. The mistake is permanent because the only data that could correct A's estimate come from pulling A.
Why does ε-greedy with constant ε have linear regret even though its estimates converge?
Because it keeps pulling uniformly random arms in an ε fraction of rounds forever, and each such pull costs the average gap in expectation. Regret is at least \(\varepsilon \bar\Delta T\) where \(\bar\Delta\) is the mean gap: 0.022T on the running example. Convergent estimates make the greedy rounds right, but cannot stop the random ones.
Derive UCB1's bonus. What would happen to exploration if you used a fixed confidence level (say 95%) instead of one that tightens with t?
Hoeffding gives \(\Pr(\hat\mu_n \le \mu - \varepsilon) \le e^{-2n\varepsilon^2}\); setting this to \(t^{-4}\) gives \(\varepsilon = \sqrt{2\ln t/n}\). With a fixed 95% level the radius \(\sqrt{\ln(20)/(2n)}\) would not grow with \(t\), so once the best arm's bound is wrongly low (a 5% event that will certainly happen at some point over a long horizon) nothing forces you back to it, and with constant probability you lock out the best arm: linear regret. The slowly growing \(\ln t\) guarantees every arm is revisited eventually.
In the Thompson-sampling example, arms B and C have the same posterior mean. Why is C chosen twice as often, and is that the right behaviour?
C's posterior, Beta(2, 2), is wide (sd 0.224), so its samples often exceed A's; B's, Beta(26, 26), is narrow (sd 0.069) and rarely does. It is the right behaviour: a pull of C is far more likely to reveal that C is the best arm, and far more informative either way. Thompson sampling allocates pulls in proportion to the probability of being optimal, which naturally favours uncertain arms with plausible upside.
Which arm of the running example dominates the Lai–Robbins bound, and roughly how many times must any consistent algorithm pull it by T = 10⁶?
Arm 3 (mean 0.55): KL(0.55 ‖ 0.6) ≈ 0.0051 nats, so it needs at least about \(\ln T / 0.0051 \approx 196 \ln T\) pulls asymptotically. At \(T = 10^6\), \(\ln T \approx 13.8\), so about 2,700 pulls, costing \(0.05 \times 2{,}700 \approx 135\) regret. Arm 0, despite its huge gap, needs only about \(13.8/0.551 \approx 25\) pulls: bad arms are cheap to rule out; nearly-good arms are expensive.
Why is a constant step size the right choice for non-stationary bandits, and what do the Robbins–Monro conditions say about it?
A constant α weights recent rewards exponentially more than old ones, so the estimate tracks a moving mean. The Robbins–Monro conditions for convergence to a fixed target, \(\sum_n \alpha_n = \infty\) and \(\sum_n \alpha_n^2 < \infty\), are violated by a constant α (the second sum diverges), which is exactly the point: the estimate never stops moving, so it never stops adapting. Its variance stays at about \(\alpha\sigma^2/2\) in steady state.
Hard: in a contextual bandit for recommendations, why might you prefer Thompson sampling to UCB when the model is retrained only once an hour?
Between retrains the estimates are frozen. UCB is deterministic given the estimates, so for a given context it shows the same item for an hour, and the exploration it intends is collapsed into one arm. Thompson sampling draws a fresh posterior sample each time, so its choices remain spread across plausible items within the hour, gathering information on several at once. Randomised exploration is robust to delayed and batched feedback, one of the reasons Chapelle and Li recommended it for ad serving.
Go deeper¶
Papers
- Finite-time Analysis of the Multiarmed Bandit Problem — Auer, Cesa-Bianchi and Fischer, Machine Learning 2002. UCB1 and the proof sketched above; section 2 and Theorem 1 are the core.
- Asymptotically Efficient Adaptive Allocation Rules — Lai and Robbins, Advances in Applied Mathematics 1985. The lower bound that defines "optimal" for bandits.
- On the likelihood that one unknown probability exceeds another in view of the evidence of two samples — Thompson, Biometrika 1933. The origin of Thompson sampling, framed as a medical-trial problem.
- An Empirical Evaluation of Thompson Sampling — Chapelle and Li, NeurIPS 2011. Why industry adopted Thompson sampling; read the delayed-feedback results.
- Analysis of Thompson Sampling for the Multi-armed Bandit Problem — Agrawal and Goyal, 2012. The first logarithmic regret bound for Thompson sampling.
- Thompson Sampling: An Asymptotically Optimal Finite Time Analysis — Kaufmann, Korda and Munos, 2012. Thompson sampling meets the Lai–Robbins constant for Bernoulli arms.
- A Contextual-Bandit Approach to Personalized News Article Recommendation — Li, Chu, Langford and Schapire, 2010. LinUCB and offline evaluation from logged data, on Yahoo! news.
- Why Adaptively Collected Data Have Negative Bias and How to Correct for It — Nie et al., 2018. Read before reporting effect sizes from a bandit experiment.
- Unifying Count-Based Exploration and Intrinsic Motivation — Bellemare et al., 2016. Pseudo-counts: UCB-style bonuses for deep RL.
- Exploration by Random Network Distillation — Burda, Edwards, Storkey and Klimov, 2018. A simple novelty bonus that cracked hard-exploration Atari games.
Videos and lectures
- RL Course by David Silver, Lecture 9: Exploration and Exploitation — DeepMind x UCL. Bandits to MDPs, with UCB, Thompson sampling and information state search in one lecture.
- Stanford CS234: Reinforcement Learning — Emma Brunskill, Winter 2019. The exploration lectures are among the clearest treatments of regret and PAC exploration.
Articles
- The Multi-Armed Bandit Problem and Its Solutions — Lilian Weng, 2018. ε-greedy, UCB and Thompson sampling with code and plots.
Courses and books
- Bandit Algorithms — Lattimore and Szepesvári, Cambridge 2020 (free PDF). The definitive text: chapters 7–8 (UCB), 15–16 (lower bounds), 36 (Thompson sampling).
- A Tutorial on Thompson Sampling — Russo, Van Roy, Kazerouni, Osband and Wen, 2018. Practical, with many worked models beyond Bernoulli.
- Introduction to Multi-Armed Bandits — Slivkins, 2019. A shorter, very readable monograph; good on contextual and adversarial bandits.
- Reinforcement Learning: An Introduction, chapter 2 — Sutton and Barto, 2nd ed. 2018. The 10-armed testbed, optimistic initial values and the gradient bandit.
Code
- Vowpal Wabbit — A production contextual-bandit library with off-policy evaluation built in.
Where this leads¶
- MDPs and the Bellman equations — add states, and actions start to have consequences.
- Q-learning and DQN — ε-greedy exploration inside a full RL agent.
- Policy gradients and REINFORCE — the gradient bandit, generalised to sequences.
- Model-based RL and planning — UCB at every node of a search tree.
- RL with verifiable rewards — sampling groups of answers as exploration for reasoning models.