Exploration and multi-armed bandits: ε-greedy, UCB and Thompson sampling
Before this lesson: lesson 01 (actions and rewards); foundations 08 (means and randomness). The proofs use Hoeffding's inequality (probability 07) and Beta–Bernoulli updating (probability 10); we restate both here. Time: about 70 minutes, plus the notebook.
Why this matters #
Lesson 01 assumed that we know the rewards and transitions of the MDP. From now on the agent learns from samples, and then it must explore. A bandit is an MDP with one state, so it isolates this problem: there are no transitions and no delayed rewards, only the choice between trying and using.
- Every RL agent explores. DQN uses ε-greedy (lesson 05 and lesson 06); policy-gradient methods and SAC add an entropy bonus (lesson 08); Monte Carlo tree search in AlphaGo and AlphaZero chooses moves with a UCB-type rule at every node (lesson 10).
- Bandits are used directly. Adaptive A/B tests, news and product recommendation (LinUCB for the Yahoo! front page, Li et al. 2010), ad placement, adaptive clinical trials, and the choice of the next experiment in Bayesian optimization (GP-UCB).
- Hyperparameter search. Successive halving and Hyperband treat each configuration as an arm and stop the bad ones early.
1. Predict first #
2. The picture #
One state, K arms #
A -armed bandit has arms . Pulling arm gives a random reward in with an unknown mean . Rewards of different pulls are independent. In our examples the arms are Bernoulli: arm pays 1 with probability and 0 otherwise.
- The best mean is .
- The gap of arm is . The best arm has gap 0.
- In round the agent pulls arm and receives the reward .
- is the number of pulls of arm in the first rounds.
Estimating a mean, one sample at a time #
The natural estimate of is the sample mean of the rewards of arm . We do not need to store all rewards. Let be the mean of the first rewards . Then
- ;
- divide by : , that is,
Read it as new estimate = old estimate + step size × (target − old estimate). The same form returns in TD learning (lesson 04) and in Q-learning (lesson 05).
With a constant step size instead of , unrolling the update gives
The weights add up to 1 (including the weight of the start value ), and they shrink geometrically for older samples. This exponential recency-weighted average follows a mean that changes over time (a nonstationary problem), but it never settles: it keeps moving with the newest samples. The step sizes satisfy the conditions and (Robbins–Monro), which give convergence to the true mean; a constant does not.
Greedy can lock onto a bad arm #
The greedy rule pulls the arm with the largest estimate. Take two Bernoulli arms with , estimates that start at 0, and ties broken at random.
- While every observed reward is 0, both estimates are 0 and the agent picks an arm at random.
- In such a round, the first reward 1 comes from arm 1 with probability and from arm 2 with probability .
- So with probability , arm 1 pays first. From then on its sample mean is above 0 for ever (it contains at least one 1), while arm 2's estimate is 0. Greedy never pulls arm 2 again and loses per round, for ever.
The cause: greedy only learns about the arm it pulls. An arm that looked bad once is never checked again. This is the exploration–exploitation trade-off: to be sure about the best arm, you must sometimes pull arms that look worse.
Pull the arms by hand first (the buttons 1–4), about 20 times, and guess which arm is best; then press Reveal. Then press Reset and let an algorithm play. The blue dot is the sample mean ; in UCB1 mode the yellow bar above it is the exploration bonus, and its top is the index that UCB1 maximizes. In Thompson mode the yellow diamond is the posterior sample . The last pulled arm is orange. After Reveal, the aqua dashes are the true means and the chart shows the cumulative regret. Notice how the algorithms stop pulling the bad arms, but never completely.
An arm has sample mean after 4 pulls. The 5th pull gives reward 1. What is ?
. Check: the sum of the first 4 rewards is , and . The answer uses a constant step instead of ; averages only the old mean and the new reward.
3. Definitions and main results #
Regret #
Definition (pseudo-regret). After rounds,
It is the expected loss compared with pulling the best arm in every round. It uses the true means , not the observed rewards: since , the observed rewards have the same expectation, but the true means remove the reward noise.
Lemma (regret decomposition). .
Proof.
- Group the rounds by arm: .
- Every round pulls exactly one arm, so and .
- Subtract: .
- Take expectations.
So a good algorithm pulls each bad arm rarely, and the arms with large gaps most rarely. Example: means and pull counts give regret .
ε-greedy #
ε-greedy: in each round, with probability pull an arm chosen uniformly at random; otherwise pull the arm with the largest estimate.
Theorem (fixed ε gives linear regret). For a fixed , .
Proof. In each round, arm is chosen by the random part with probability , so for every arm. Put this into the regret decomposition.
The bound grows like as long as some arm has . Because every arm is pulled infinitely often, the estimates converge to the true means, so the greedy part soon picks the best arm, and the regret per step tends to exactly .
Two repairs.
- Decaying ε. With , the expected number of random pulls up to is , so the exploration cost grows like . With chosen from the smallest gap, Auer et al. (2002) prove regret for this rule. The catch: you must know (a bound on) the gaps to choose .
- Optimistic initial values. Start every estimate far above any possible mean, e.g. for rewards in with a constant step (Sutton & Barto §2.6). Then even the greedy rule tries every arm: each pull lowers the estimate of that arm, so another arm now looks better. This explores only at the start, so it does not help when the means change later. With the sample mean () the first reward replaces completely, so the optimism lasts only one pull per arm.
Both ideas point to one principle: optimism in the face of uncertainty. UCB1 makes it precise.
Two Bernoulli arms have means and . ε-greedy runs with for a long time. What does its regret per step tend to?
The greedy part soon pulls the best arm, so only the random part costs regret. In a round it picks the bad arm with probability and loses : per step. The answer forgets that the random arm is the best arm half of the time.
UCB1: optimism from Hoeffding's inequality #
Hoeffding's inequality. Let be independent, with values in and mean , and let be their sample mean. Then for every ,
The sample mean is rarely far from , and "far" shrinks like .
The idea. Do not use the estimate itself. Use an optimistic value: the largest mean that is still plausible given the data. An arm with few pulls has a wide range of plausible means, so its optimistic value is high, and it gets pulled. If it is really bad, a few pulls shrink its range and it stops being pulled. If it is good, pulling it was right. In both cases we lose little.
Deriving the bonus, step by step.
- We want a number that is above the true mean with high probability. By Hoeffding, it fails (that is, ) with probability at most , where .
- Let the failure probability shrink with time : choose . The power 4 is large enough that the failures, summed over all rounds and all possible counts, stay bounded (see the proof below).
- Take logarithms: , so and
- UCB1 (Auer, Cesa-Bianchi and Fischer, 2002): pull every arm once. Then, in every round, pull
where is the number of pulls made so far and the number of pulls of arm . The value in brackets is the index of arm , and is the exploration bonus.
The bonus shrinks like when the arm is pulled, and it grows slowly, like , when it is not. So no arm is abandoned for ever, but bad arms are tried less and less often. The first round of pulls is needed because the bonus is undefined for .
Move and . The yellow curve is the bonus for the chosen ; grey curves are . Doubling divides the bonus by ; multiplying by 10 changes it only a little. The number line shows the interval and the index. Switch to Hoeffding vs exact to compare the bound with the exact tail for fair coin flips: for , the bound is 0.2019 and the true probability is 0.0577. The bound is loose, but it holds for every reward distribution on .
Theorem (UCB1 regret, Auer et al. 2002). For rewards in and every arm with ,
So, by the regret decomposition,
The regret grows like , and arms with small gaps cost the most.
Proof sketch of the UCB1 bound
Think of the rewards of each arm as a list of independent samples drawn in advance; is the mean of the first entries of arm 's list. Write . Fix a bad arm and let .
- Arm is pulled at most times while . So .
- Suppose UCB1 pulls at time with , and the best arm has pulls. Then . This forces at least one of three events: (i) (the best arm is underestimated by more than its bonus); (ii) (arm is overestimated by more than its bonus); (iii) . Indeed, if all three fail, then , so arm would not be chosen.
- Event (iii) is impossible: gives , so .
- By Hoeffding, for fixed and , each of (i) and (ii) has probability at most . The counts are random, so take a union bound over all : the probability that arm is pulled at time with is at most .
- Summing over : . Multiply by and sum over the bad arms to get the regret bound.
Lower bound (Lai and Robbins, 1985). No reasonable algorithm can do better than . Call an algorithm consistent if its regret is for every on every bandit of the class. For Bernoulli arms, every consistent algorithm satisfies
for every arm with . So is the best possible order; only the constant can improve. Example: , gives , so at least about pulls of arm are needed, while the UCB1 bound allows . UCB1 has the right order with a large constant. KL-UCB and Thompson sampling reach the Lai–Robbins constant for Bernoulli arms.
A bound that does not depend on the gaps
The bound blows up for tiny gaps, but tiny gaps also cost little per pull. Split the bad arms at a threshold . Arms with cost at most in total. Arms with cost at most (plus a constant). Choose to balance the two terms: plus a term that does not grow with . So UCB1's worst-case regret is , and the minimax lower bound for any algorithm is of order (Lattimore and Szepesvári, ch. 15).
After pulls, an arm has pulls and sample mean . What is its UCB1 index?
. The index can be above 1 even though the rewards are in : it is an optimistic bound, not an estimate. forgets the factor 2; uses instead of the natural logarithm.
Thompson sampling #
Beta–Bernoulli updating. Put a prior on the unknown mean of a Bernoulli arm. Its density is proportional to , and its mean is . After successes and failures, Bayes' rule multiplies the prior by the likelihood :
so the posterior is . The Beta family is conjugate to the Bernoulli likelihood: the posterior stays in the family, and the update is two counters. Its variance shrinks like as data comes in. The prior is uniform on .
Thompson sampling (Thompson, 1933) for Bernoulli arms, with priors. In every round:
- for every arm, draw one sample from its posterior;
- pull and observe ;
- update that arm: and .
Why it explores: probability matching. The samples are one draw of all the arm means from their posterior. The pulled arm is the one that is best in this draw. So
each arm is pulled with exactly the posterior probability that it is the best arm. An arm with few pulls has a wide posterior, so it sometimes draws the largest sample and gets pulled. As data comes in, the posteriors narrow, and an arm that is clearly worse almost never wins the draw. The exploration comes from the randomness of the posterior, not from a parameter.
Regret. For Bernoulli arms, Thompson sampling has logarithmic regret with the optimal Lai–Robbins constant (Agrawal and Goyal 2012; Kaufmann, Korda and Munos 2012). In practice it is often better than UCB1, and it works well with delayed or batched feedback, because random draws spread the pulls over the arms even when the posteriors are not updated after every pull.
Press "Sample once" a few times, then "Sample 100 times". The curves are the posteriors Beta(6, 2) (arm 1: 5 successes, 1 failure) and Beta(3, 3) (arm 2: 2 and 2). Each draw marks one per arm; the orange line is the largest, and that arm is pulled. The frequency of arm 1 approaches the exact . Try more data (same means, about ten times the pulls): the posteriors narrow, and arm 2 almost never wins.
An arm has posterior . It is pulled and gives reward 0. What is the new posterior, and its mean?
A failure adds 1 to : , with mean . swaps the update (a success raises ). Counts never decrease, so is impossible, and a failure is as informative as a success.
The methods side by side #
Before you press Run, predict which curves keep growing like a straight line and which bend. The mean regret over 100 runs is shown for four Bernoulli arms with means 0.2, 0.4, 0.6, 0.8 and . Greedy and fixed ε-greedy grow linearly (greedy leaves the chart); UCB1, decaying ε and Thompson sampling bend. Switch the axis to logarithmic: a curve that grows like becomes a straight line there. Thompson sampling is almost straight already; UCB1 still bends upward at this horizon, because its behaviour starts late (its constant is large). The table divides the final regret by .
What the simulation shows (mean of 100 runs, ): greedy about 1240, fixed ε-greedy about 166, UCB1 about 107, decaying ε about 48 and Thompson sampling about 20. Two lessons follow. First, the order wins in the long run, but constants matter: UCB1 is worse than ε-greedy until about , because its constant is large. Second, the decaying-ε rule does well here only because its constant suits these gaps; with other gaps it can explore too little or too much.
| Method | Parameters | Regret | Notes |
|---|---|---|---|
| greedy | none | linear (can lock onto a bad arm) | never checks an arm again |
| ε-greedy, fixed ε | linear: | simple; default in deep RL | |
| ε-greedy, | (needs the gaps) | with a good | explores at random, also bad arms |
| optimistic start | , | explores only at the start | not for changing means |
| UCB1 | none | deterministic; large constant | |
| Thompson sampling | prior | , optimal constant (Bernoulli) | needs a posterior; often best in practice |
Beyond the basic bandit #
- Contextual bandits. Before each round the agent sees a feature vector (user, item, time). LinUCB (Li et al., 2010) models the reward as linear, , fits by ridge regression, with and over the pulls of , and pulls the arm with the largest . The bonus is large in feature directions with little data.
- Exploration in MDPs is harder, because an action also changes the next state. The ideas carry over: ε-greedy in Q-learning and DQN (lesson 05), optimism and count-based bonuses, entropy bonuses in policy methods (lesson 08), and UCB applied at every node of a search tree (UCT and PUCT in lesson 10).
Answers to section 1. (1) No. With probability it still pulls a random arm, also arms it knows are bad, so the regret per step tends to , not 0. The regret grows linearly. (2) Through the randomness of the posterior. An arm with few pulls has a wide posterior, so it sometimes draws the largest sample and gets pulled (probability matching).
4. Worked example #
(a) UCB1 at . Arm 1 has pulls with mean 0.7; arm 2 has with mean 0.6; arm 3 has with mean 0.0. First, . Then
- arm 1: ;
- arm 2: ;
- arm 3: .
UCB1 pulls arm 2. It is not the arm with the best mean (arm 1) and not the least-pulled arm (arm 3): arm 2 has a good mean and a medium bonus. Arm 3 has the largest bonus, but its observed mean 0.0 pulls its index below arm 2's.
(b) Thompson sampling. Arm 1 has 5 successes and 1 failure: posterior , mean . Arm 2 has 2 and 2: , mean 0.5. Thompson sampling pulls arm 1 with probability
where is the density of and the distribution function of : arm 1 must be the larger one, so we integrate its density times the probability that arm 2 is below. Arm 2 is still pulled about 15% of the time: it has only 4 observations, and a mean above 0.75 is still plausible for it.
(c) ε-greedy. Means , , . The gaps are . In the long run the regret per step is , and the regret after rounds is at least .
5. In code #
SciPy checks the numbers above. The notebook implements the algorithms.
import numpy as np
from scipy import integrate, stats
# Hoeffding vs the exact tail: 20 fair coin flips, deviation c = 0.2
n, c = 20, 0.2
print(round(stats.binom.sf(13, n, 0.5), 4)) # 0.0577 exact P(mean >= 0.7) = P(X >= 14)
print(round(np.exp(-2 * n * c**2), 4)) # 0.2019 Hoeffding bound
# UCB1 indices of the worked example (t = 50 pulls so far)
t = 50
for n_a, mean in [(30, 0.7), (15, 0.6), (5, 0.0)]:
print(round(mean + np.sqrt(2 * np.log(t) / n_a), 3)) # 1.211, 1.322, 1.251
# Thompson sampling: P(theta_1 > theta_2) for Beta(6, 2) and Beta(3, 3)
p = integrate.quad(lambda x: stats.beta.pdf(x, 6, 2) * stats.beta.cdf(x, 3, 3), 0, 1)[0]
print(round(p, 4), round(28 / 33, 4)) # 0.8485 0.8485
rng = np.random.default_rng(0)
theta1, theta2 = rng.beta(6, 2, 100_000), rng.beta(3, 3, 100_000)
print(np.mean(theta1 > theta2)) # 0.84825 (Monte Carlo estimate)
# epsilon-greedy: limit of the regret per step, means (0.2, 0.5, 0.7), eps = 0.1
mu = np.array([0.2, 0.5, 0.7])
print(round(0.1 * np.mean(mu.max() - mu), 4)) # 0.0233
Hoeffding is loose here (0.20 against 0.06), but it holds for every distribution on , and that is what UCB1 needs.
6. Where it shows up #
- Deep RL exploration. DQN on Atari uses ε-greedy with decayed from 1 to 0.1 (later 0.01) over the first million frames: decaying ε, as in section 3.
- MCTS and AlphaZero. UCT (Kocsis and Szepesvári, 2006) applies UCB1 to choose a child at every node of the search tree; AlphaGo and AlphaZero use the PUCT variant with a prior from the policy network (lesson 10).
- Online experiments and recommenders. Thompson sampling and UCB move traffic between variants (ads, layouts, prompts, news articles) while they learn which is best. They waste fewer users on bad variants than a fixed A/B split, but the data is no longer a simple random sample, so classical tests need care.
- Bayesian optimization for science. GP-UCB chooses the next experiment, simulation or hyperparameter setting by the posterior mean plus a multiple of the posterior standard deviation of a Gaussian process: UCB with a smooth model over a continuous set of arms. It is used in materials and drug discovery and in tuning simulators.
- LLMs. Choosing among prompts or models online, and sampling several answers and keeping the best, are bandit problems; the "best-of-" trade-off is again exploration against cost.
7. Common mistakes #
- Regret with observed rewards. The pseudo-regret uses the true means . Observed rewards add noise and can even make the "regret" negative.
- UCB without the first round. With the bonus is undefined (division by zero). Pull each arm once first, or give unpulled arms index .
- instead of . The bonus uses the natural logarithm, which comes from solving .
- Swapped Beta update. A success increases , a failure increases .
- "ε-greedy converges, so its regret is fine." Its estimates converge, but with a fixed it keeps pulling bad arms at rate , so the regret is linear.
- Optimism with sample means. With the step , the first reward replaces the optimistic ; optimistic initial values need a constant step size or a pseudo-count.
- Ties with
argmax.np.argmaxalways returns the first maximum. With estimates that start equal, this means "always arm 0", not a random choice. Break ties at random.
8. Check yourself #
- Write the pseudo-regret as a sum over arms, and compute it for gaps and pull counts .
Answer
with . Here . - Which failure probability gives the bonus , and why does it shrink with ?
Answer
: solving gives . It shrinks with so that the failures, summed over all rounds and all possible counts (a union bound gives per round), have a finite total, . - Why does Thompson sampling keep pulling an arm with few observations now and then?
Answer
Its posterior is wide, so it sometimes draws the largest sample . Each arm is pulled with the posterior probability that it is the best (probability matching), and for an arm with little data this probability is not small. - Arm 1 has 40 pulls with mean 0.5; arm 2 has 10 pulls with mean 0.45; . Which arm does UCB1 pull?
Answer
. Arm 1: . Arm 2: . UCB1 pulls arm 2: its lower mean is outweighed by its larger bonus. - What is the best possible order of the regret, and which result says so?
Answer
. The Lai–Robbins lower bound: every consistent algorithm pulls each bad arm at least about times. UCB1 and Thompson sampling reach this order; Thompson sampling also reaches the constant for Bernoulli arms. - Why do optimistic initial values not help when the arm means change over time?
Answer
The optimism is used up at the start: after a few pulls every estimate is close to its arm's mean, and the greedy rule stops exploring. When a mean changes later, nothing makes the agent try that arm again.
What is the pseudo-regret of a bandit algorithm, as a sum over arms?
, with gap and the pulls of arm up to .
Why does ε-greedy with a fixed have linear regret?
It pulls every arm with probability at least in every round, so and .
Write the incremental update of a sample mean.
: old estimate plus step size times (target minus old estimate).
An arm has mean estimate 0.6 after 4 pulls; the 5th reward is 1. Give the new sample mean.
.
Write the UCB1 index of arm .
, with the pulls so far and the pulls of arm (after one pull of every arm).
Where does the UCB1 bonus come from?
From Hoeffding's inequality , with the failure probability set to : .
What is the best possible order of the regret, and who proved it?
(Lai and Robbins, 1985): each bad arm needs about pulls.
How does Thompson sampling update a Beta posterior after a Bernoulli reward ?
and (a success raises , a failure raises ).
What is probability matching in Thompson sampling?
Each arm is pulled with the posterior probability that it is the best arm, because the pulled arm is the argmax of one posterior sample.
How do optimistic initial values make a greedy agent explore, and what is their limit?
Every estimate starts too high, so each pull disappoints and another arm looks better; this explores only at the start, so it does not help when the means change.
9. Interview angle #
- "Explain exploration vs exploitation." — To find the best action you must try actions that look worse. Measure the cost with regret; show that greedy can lock onto a bad arm.
- "UCB or Thompson sampling?" — UCB: deterministic optimism from a confidence bound, no prior, easy to analyze, large constant. Thompson: randomized probability matching, needs a posterior, usually better in practice, robust to delayed or batched feedback.
- "Why can a fixed ε be a bad idea?" — Linear regret: it keeps exploring arms it knows are bad. Decay , or use UCB or Thompson sampling.
- "Derive the UCB bonus." — Hoeffding, failure probability , solve for : .
- "What regret is possible?" — per instance (Lai–Robbins); in the worst case over instances, up to log factors for UCB1.
- "How would you run an A/B test with a bandit, and what is the catch?" — Thompson sampling over variants; the catch is that adaptive allocation biases naive estimates and p-values.
10. Practice #
The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:
pseudo_regret: the cumulative regret from the true means and the chosen arms.epsilon_greedy: fixed and decaying , with random tie-breaking; see linear regret.ucb1: pull every arm once, then the largest index; check the bound on bad-arm pulls.thompson_bernoulli: Beta posteriors; check the final counts.- Regret curves on a 10-armed testbed over many seeds; check that UCB1's regret divided by stays bounded while fixed ε-greedy's grows.
11. Watch and read #
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd edition, free PDF: chapter 2 (incremental means, ε-greedy, optimistic initial values, UCB).
- Lattimore and Szepesvári, Bandit Algorithms, free PDF: ch. 4 (regret decomposition), 5 (concentration), 7 (UCB), 16 (lower bounds), 36 (Thompson sampling).
- Auer, Cesa-Bianchi and Fischer, Finite-time analysis of the multiarmed bandit problem (2002): UCB1 and its proof.
- Russo, Van Roy, Kazerouni, Osband and Wen, A Tutorial on Thompson Sampling: §3–4 for Bernoulli bandits.
- Li, Chu, Langford and Schapire, A contextual-bandit approach to personalized news article recommendation (2010): LinUCB.
Runs in your browser with nothing to install. The notebook repeats the key demos and has exercises with checks; solutions are inside, folded.
No Google account needed: Python runs inside your browser. The first start downloads about 40 MB; your changes are saved in this browser only.