◆ AI All-in-One

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
↗ Plan a path here

Read first

Reinforcement Learning: The Basics

This leads to

—
The full path from zero — 4 concepts before this one
  1. What Is AI?
  2. How Machines Learn
  3. Supervised, Unsupervised and Reinforcement Learning
  4. Reinforcement Learning: The Basics
  5. 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.

0 0.25 0.5 0.75 1 C A B win rate of the arm how plausible each win rate is after a few pulls of each arm (Beta posteriors) Arm A: 2 wins, 2 losses estimate 0.50, very unsure Arm B: 33 wins, 22 losses estimate 0.60, fairly sure Arm C: 1 win, 5 losses estimate 0.17, very unsure Exploit: pull B best estimate so far Explore: try A it might be better than B; only more pulls will tell Thompson sampling picks A about 1 time in 3
Fig. 1 What the agent believes after a few pulls. Arm B has the best estimate and the agent is fairly sure of it. Arm A's estimate is lower, but after only four pulls its true win rate could easily be higher than B's. Exploiting means pulling B; exploring means giving A another try.

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 kk actions (arms). Pulling arm aa gives a random reward whose average is q∗(a)q_*(a), the arm's true action value. The agent doesn't know q∗(a)q_*(a). At each step tt it picks an action AtA_t and receives a reward RtR_t. (Bandits have no next state, so here the reward simply shares the action's time index.)

The agent keeps an estimate Qt(a)Q_t(a) 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 QnQ_n is the average of the first n−1n-1 rewards from an arm and the nn-th reward is RnR_n, the new average is

Qn+1=Qn+1n(Rn−Qn)Q_{n+1} = Q_n + \frac{1}{n}\big(R_n - Q_n\big)

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 Q=0.5Q = 0.5. The fifth pull wins (R=1R = 1). The new estimate is 0.5+15(1−0.5)=0.60.5 + \frac{1}{5}(1 - 0.5) = 0.6, which is indeed 3 wins out of 5.

If the arms' payoffs drift over time, replace 1n\frac{1}{n} with a constant step size α\alpha 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 TT pulls,

regret(T)=∑t=1T(q∗(a∗)−q∗(At))\text{regret}(T) = \sum_{t=1}^{T} \big( q_*(a^*) - q_*(A_t) \big)

where a∗a^* 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 TT. The best possible strategies have regret that grows only like log⁡T\log T. 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: At=arg⁡max⁡aQt(a)A_t = \arg\max_a Q_t(a). (arg⁡max⁡\arg\max means "the aa 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 ε\varepsilon (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 ε=0.1\varepsilon = 0.1, the agent picks its current favourite with probability 0.9+0.1/5=0.920.9 + 0.1/5 = 0.92. 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 ε\varepsilon 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:

At=arg⁡max⁡a[Qt(a)+cln⁡tNt(a)]A_t = \arg\max_a \left[ Q_t(a) + c\sqrt{\frac{\ln t}{N_t(a)}} \right]

Here Nt(a)N_t(a) is how many times arm aa has been pulled, ln⁡t\ln t is the natural logarithm of the current step, and cc sets how much to explore (c=2c = \sqrt{2} in the original UCB1). The bonus shrinks as an arm is pulled more (Nt(a)N_t(a) grows). It slowly grows for arms that are neglected while tt 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 t=65t = 65, ln⁡65≈4.17\ln 65 \approx 4.17, so with c=2c = \sqrt 2 the bonus is 8.35/N\sqrt{8.35 / N}. Take the three arms in the picture:

Arm Pulls NN Estimate QQ Bonus QQ + 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 ww wins and ll losses the belief is Beta(1+w1 + w, 1+l1 + l). These are the curves in the figure above.

Each step:

  1. For each arm, draw one random sample from its belief distribution.
  2. Pull the arm whose sample is highest.
  3. 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:

0 100 200 300 0 1,000 2,000 3,000 4,000 5,000 greedy 325 ε-greedy (ε = 0.1) 134 UCB1 184 Thompson sampling 53 number of pulls cumulative regret reward lost vs always pulling the best arm
Fig. 2 Cumulative regret over 5,000 pulls, averaged over 200 runs of the five-armed problem. Greedy and ε-greedy keep losing reward at a steady rate (straight lines). UCB1 and Thompson sampling bend over as they become confident, and Thompson is best.

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.argmax returns 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 ε=0.1\varepsilon = 0.1 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 (1/n1/n 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 Q=1Q = 1 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

  1. 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?
  2. In the UCB1 line, replace 2 with 0.5 (less exploration). Does regret after 1,000 pulls go down? Try 8 too.
  3. 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.

Check your understanding

5 quick questions. Pick an answer to see whether you were right and why. Your best score is saved on this device.

  1. With 5 arms and ε = 0.1, how often does an ε-greedy agent pick its current favourite arm?

  2. An arm has won 2 of its 4 pulls (Q = 0.5). The fifth pull wins. Using the incremental update Q + (1/n)(R − Q), what is the new estimate?

  3. UCB picks arm A (4 pulls, estimate 0.50) over arm B (55 pulls, estimate 0.60). Why?

  4. Your website's best headline changes with the seasons. Which change keeps a bandit's estimates up to date?

  5. A greedy agent and an ε-greedy agent with fixed ε both show regret growing in a straight line over time. What does that tell you?

Finished this chapter?

Learn more

Hand-picked courses, books, videos and tutorials for going deeper. See all resources →

Paper

A Tutorial on Thompson Sampling

Russo, Van Roy, Kazerouni, Osband & Wen · 2017 · Intermediate · Free

A readable tutorial on Thompson sampling with worked examples, from Bernoulli bandits to shortest-path problems.

Book

Bandit Algorithms

Tor Lattimore & Csaba Szepesvári · 2020 · Advanced · Free

The modern reference on bandits: UCB, Thompson sampling, regret lower bounds, contextual and adversarial bandits. Free PDF from the authors.

Course

UCL Course on Reinforcement Learning

David Silver · 2015 · Intermediate · Free

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