Level 3 In-Depth AI · Reinforcement Learning
Multi-Armed Bandits and Exploration
The simplest reinforcement-learning problem. You choose among options with unknown payoffs and must balance trying new ones against using the best one found so far. Epsilon-greedy, UCB and Thompson sampling solve it, and A/B testing is its everyday cousin.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 1 hour to read, an afternoon to practise
- Builds on
- 4 concepts →
- Quiz
- 5 questions ↓
Read first
Reinforcement Learning: The BasicsThis leads to
—The full path from zero — 4 concepts before this one
- What Is AI?
- How Machines Learn
- Supervised, Unsupervised and Reinforcement Learning
- Reinforcement Learning: The Basics
- Multi-Armed Bandits and Exploration
Read them roughly in this order. See it on the concept map →
Why it matters
Every learning agent faces the same dilemma. Should it do the thing that has worked best so far, or try something else that might be better? A restaurant-goer who always orders the same dish never discovers a better one. One who always orders something new rarely enjoys a meal they know they'll like. This is the exploration–exploitation trade-off, and every agent in reinforcement learning has to manage it.
The multi-armed bandit strips RL down until only this dilemma is left. There are no states to move between and no delayed consequences. You just make repeated choices and get rewards. That makes it the cleanest place to study exploration, and the methods invented here (ε-greedy, upper confidence bounds, Thompson sampling) reappear inside Q-Learning, Deep Q-Networks and the tree search of AlphaGo.
Bandits are also directly useful. Websites use them to choose which headline, ad or layout to show. Clinical-trial designers use them to send more patients to the treatment that seems to work. Recommender systems use them to try new items without wrecking the experience (Recommender Systems). They are a smarter version of the classic A/B test.
The intuition
Picture a row of slot machines (old slang: "one-armed bandits"). Each pays out with a different, unknown probability. You have 1,000 coins. How do you play to win as much as possible?
If you knew which machine was best, you'd play it every time. You don't, so you have to learn by pulling. Each pull earns money (exploitation) and information (exploration), and the two pull in opposite directions:
- Play only the machine that looks best right now, and you may lock onto a mediocre one after a lucky early streak. You'll never find out that another machine was better.
- Spread your pulls evenly to measure every machine carefully, and you waste hundreds of coins on machines you already know are bad.
The good strategies all share one idea. Explore where you are uncertain, and exploit where you are confident. A machine you've pulled twice is a mystery, so it deserves another look. A machine you've pulled 50 times with poor results has had its chance.
Key idea Exploration costs reward now but buys information that earns more reward later. Good bandit algorithms explore in proportion to uncertainty: a lot at first, less and less as estimates firm up.
How it works
The setup
There are actions (arms). Pulling arm gives a random reward whose average is , the arm's true action value. The agent doesn't know . At each step it picks an action and receives a reward . (Bandits have no next state, so here the reward simply shares the action's time index.)
The agent keeps an estimate of each arm's value. The obvious estimate is the average reward received from that arm so far.
Updating the average without storing everything
Keeping every reward to average them is wasteful. There is a neater way. If is the average of the first rewards from an arm and the -th reward is , the new average is
Read it as: new estimate = old estimate + step size × (what happened − what I expected). The bracket is an error: how surprised you were. This "move the estimate a fraction of the way towards the target" pattern runs through all of RL. It is the same shape as the Q-Learning update.
Worked example. An arm has paid out on 2 of its 4 pulls, so . The fifth pull wins (). The new estimate is , which is indeed 3 wins out of 5.
If the arms' payoffs drift over time, replace with a constant step size such as 0.1. Then recent rewards count more than old ones.
Measuring success: regret
To compare strategies we measure regret: how much reward was lost compared with always pulling the best arm. After pulls,
where is the best arm. Each pull of a worse arm adds its shortfall. A strategy that never stops exploring at a fixed rate, or one that gets stuck on a bad arm, has regret that grows in a straight line with . The best possible strategies have regret that grows only like . Lai and Robbins proved in 1985 that no strategy can do better than that in general.
Strategy 1: greedy
Always pick the arm with the highest current estimate: . ( means "the that gives the largest value".) This is pure exploitation. If the best arm happens to disappoint on its first pull, the greedy agent may never return to it.
Strategy 2: ε-greedy
With a small probability (epsilon), say 0.1, pick an arm completely at random. Otherwise act greedily. It is simple and robust, and it is the default exploration method in Q-Learning and Deep Q-Networks.
With 5 arms and , the agent picks its current favourite with probability . So even when it knows the best arm, 8% of its pulls go elsewhere. The regret keeps growing in a straight line, just more slowly than greedy's. A common fix is to shrink over time.
Strategy 3: upper confidence bound (UCB)
Instead of exploring at random, explore on purpose. Give each arm a bonus that is large when it has been tried rarely, and pick the arm with the highest estimate plus bonus. The UCB1 rule is:
Here is how many times arm has been pulled, is the natural logarithm of the current step, and sets how much to explore ( in the original UCB1). The bonus shrinks as an arm is pulled more ( grows). It slowly grows for arms that are neglected while ticks up. The idea is optimism in the face of uncertainty: treat each arm as if it were as good as it could plausibly be, and the truth will sort itself out.
Worked example. At step , , so with the bonus is . Take the three arms in the picture:
| Arm | Pulls | Estimate | Bonus | + bonus |
|---|---|---|---|---|
| A | 4 | 0.50 | 1.44 | 1.94 |
| B | 55 | 0.60 | 0.39 | 0.99 |
| C | 6 | 0.17 | 1.18 | 1.35 |
Greedy would pull B. UCB pulls A, because A is the arm we know least about relative to its promise.
Strategy 4: Thompson sampling
Thompson sampling is the Bayesian answer (see Bayes' Theorem). For each arm keep a whole probability distribution over its win rate, not just one number. For win/lose rewards the natural choice is a Beta distribution. Start each arm at Beta(1, 1), which is flat: every win rate equally plausible. After wins and losses the belief is Beta(, ). These are the curves in the figure above.
Each step:
- For each arm, draw one random sample from its belief distribution.
- Pull the arm whose sample is highest.
- Update that arm's wins or losses.
That is the whole algorithm. An arm gets picked with exactly the probability that it is the best, given what you know. In the figure, B's narrow curve almost always produces a sample near 0.6. A's wide curve sometimes produces 0.7 or 0.8, and when that happens A gets a pull. Sampling a million times from those three curves picks A about 33% of the time and B about 66%. As evidence piles up the curves narrow and the exploration fades away on its own.
In code
Five Bernoulli arms (each pays 1 with a hidden probability, else 0), four strategies, 1,000 pulls each, averaged over 500 repeated runs:
import numpy as np
true_p = np.array([0.20, 0.35, 0.50, 0.55, 0.60]) # each arm's (hidden) win rate
K, T, RUNS = len(true_p), 1000, 500
def run(strategy, rng):
N = np.zeros(K) # pulls per arm
Q = np.zeros(K) # estimated value per arm
wins, losses = np.ones(K), np.ones(K) # Beta(1,1) priors for Thompson
regret = 0.0
for t in range(1, T + 1):
if t <= K and strategy != "Thompson":
a = t - 1 # try each arm once
elif strategy == "greedy":
a = np.argmax(Q)
elif strategy == "eps-greedy":
a = rng.integers(K) if rng.random() < 0.1 else np.argmax(Q)
elif strategy == "UCB1":
a = np.argmax(Q + np.sqrt(2 * np.log(t) / N))
elif strategy == "Thompson":
a = np.argmax(rng.beta(wins, losses)) # sample a belief, act on it
r = float(rng.random() < true_p[a]) # pull: 1 = win, 0 = loss
N[a] += 1
Q[a] += (r - Q[a]) / N[a] # incremental average
wins[a] += r; losses[a] += 1 - r
regret += true_p.max() - true_p[a]
return regret, N[-1] / T
rng = np.random.default_rng(0)
for s in ["greedy", "eps-greedy", "UCB1", "Thompson"]:
res = np.array([run(s, rng) for _ in range(RUNS)])
print(f"{s:10s} regret after {T} pulls: {res[:,0].mean():5.1f} "
f"best arm chosen {100*res[:,1].mean():4.1f}% of the time")
# greedy regret after 1000 pulls: 71.0 best arm chosen 40.3% of the time
# eps-greedy regret after 1000 pulls: 40.9 best arm chosen 57.5% of the time
# UCB1 regret after 1000 pulls: 67.5 best arm chosen 43.6% of the time
# Thompson regret after 1000 pulls: 32.8 best arm chosen 63.6% of the time
The three best arms (0.50, 0.55, 0.60) are hard to tell apart, which makes this a tough problem. Greedy locks onto the wrong arm in most runs. Run the same experiment for longer and the shapes of the regret curves appear:
UCB1 is behind ε-greedy at 1,000 pulls but its curve is flattening while ε-greedy's is still a straight line. Thompson sampling wins at every horizon here. That matches what practitioners usually find, and it is why Thompson sampling is popular in industry.
Common pitfalls
- Ties in argmax.
np.argmaxreturns the first maximum. If all estimates start at 0, a greedy agent always picks arm 0 first. Break ties randomly, or pull every arm once at the start, as the code does. - Never stopping ε-exploration. A fixed wastes 10% of pulls forever. Decay it, or use UCB or Thompson, which reduce exploration on their own.
- Assuming the world stands still. Click-through rates drift with the seasons. Sample averages ( step size) adapt ever more slowly. Use a constant step size or discount old data.
- Peeking at A/B tests. Classic A/B tests split traffic evenly for a fixed time, then pick a winner with a significance test (Statistics: Mean, Variance and Sampling). Stopping the moment one variant looks ahead inflates false positives. Bandits avoid wasting traffic on the loser, but they make clean statistical conclusions harder, because the loser gets few samples.
- Delayed rewards. If a "conversion" arrives days after the ad was shown, the algorithm is updating on stale information. Thompson sampling copes better than UCB here because its randomness spreads pulls out while results are pending.
Watch out Greedy looks fine in a demo and fails quietly in production. With noisy rewards it routinely commits to a mediocre option after a lucky start and never finds out. Always keep some principled exploration.
Variations
- Optimistic initial values. Start every estimate high (for example when rewards are at most 1). Each arm disappoints when tried, so a greedy agent works its way through all of them. It is a cheap trick that only explores at the beginning.
- Contextual bandits. The best arm depends on side information, such as who the user is or the time of day. The agent learns a model from context to reward for each arm. Yahoo's news-recommendation work (Li et al., 2010) made this approach famous. It is what most "personalisation" systems really are.
- Adversarial bandits (e.g. the EXP3 algorithm) make no assumptions about how rewards are generated and still guarantee low regret.
- Full RL. Add states and let actions change them, and the bandit becomes a Markov decision process. Exploration gets much harder, because information about a state can only be gathered by getting there.
- Tree search. The UCT algorithm runs a UCB bandit at every node of a game tree. It is the heart of Monte Carlo tree search (Monte Carlo Tree Search and AlphaGo).
A bit of history
William R. Thompson proposed what we now call Thompson sampling in 1933, for deciding which of two medical treatments to give. Herbert Robbins framed the general bandit problem in 1952. In 1985, Tze Leung Lai and Robbins proved that regret must grow at least logarithmically and gave strategies that achieve it. In 2002, Peter Auer, Nicolò Cesa-Bianchi and Paul Fischer published UCB1, a simple rule with a proven logarithmic regret bound for any number of steps. Thompson sampling was largely ignored for decades. It made a comeback around 2011–2012, when experiments at Microsoft and Yahoo showed it working very well on ad and news data and new proofs confirmed its regret guarantees. Today bandit algorithms run inside ad platforms, recommendation engines and experimentation tools across the web.
Try it
- Change the arms to
[0.1, 0.2, 0.3, 0.4, 0.9], an easy problem with a clear winner. How does greedy do now? Why?- In the UCB1 line, replace
2with0.5(less exploration). Does regret after 1,000 pulls go down? Try8too.- Make the problem non-stationary. After step 500, swap the win rates of the first and last arms. Which strategy recovers? Fix ε-greedy with a constant step size
Q[a] += 0.1 * (r - Q[a]).Hint for 3: Thompson's Beta counts never forget, so it adapts slowly unless you discount old wins and losses.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
Reinforcement Learning: An Introduction
The foundational RL textbook by the field's founders. Free PDF.
A Tutorial on Thompson Sampling
A readable tutorial on Thompson sampling with worked examples, from Bernoulli bandits to shortest-path problems.
Bandit Algorithms
The modern reference on bandits: UCB, Thompson sampling, regret lower bounds, contextual and adversarial bandits. Free PDF from the authors.
Finite-time Analysis of the Multiarmed Bandit Problem
Introduced UCB1 and proved that its regret grows only logarithmically with time.
UCL Course on Reinforcement Learning
Ten recorded lectures with slides by the lead researcher behind AlphaGo. Covers MDPs, dynamic programming, TD learning, function approximation, policy gradients and planning; follows Sutton & Barto closely.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/rl/bandits.md