Velamuvi AIAcademy

Lesson 5 of 12 · Classic Methods

Multi-Armed Bandits

Multi-armed bandits in Python: a k-armed testbed, incremental updates, ε-greedy vs UCB vs Thompson sampling, regret, and the link to A/B testing.

  • 15 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Describe the k-armed bandit problem, and measure a strategy by its regret
  • Update value estimates incrementally, with a 1/n or a constant step size
  • Implement Thompson sampling with Beta posteriors for click-or-not rewards
  • Compare ε-greedy, UCB and Thompson sampling on a k-armed testbed
  • Explain when a bandit beats a classic A/B test, and when it doesn't

The idea in plain words

A slot machine is nicknamed a "one-armed bandit". Picture a row of them, each paying out with its own unknown probability. Which arms do you pull, and how often, to win as much as possible? That's the multi-armed bandit problem. It is reinforcement learning with only one situation: every pull pays its reward at once, and nothing carries over to the next pull. There are no states, no transitions and no delayed rewards, only the exploration-exploitation dilemma from Exploration vs Exploitation in its purest form.

It's far from a toy. A website choosing which of five headlines to show, a shop choosing which discount to offer, and a medical trial comparing two treatments are all bandits: every visitor or patient is a pull, and every click or recovery is a reward. This lesson covers how to measure a bandit strategy, how to update estimates cheaply, and Thompson sampling, the method many real systems use.

The k-armed bandit problem

There are k arms. Each pull of arm a gives a random reward whose average, the arm's true value, is unknown:

q*(a)   the true value of arm a: its average reward, unknown to the agent
Q(a)    the agent's estimate of q*(a), from the rewards it has seen so far

regret after T pulls = Σ over the pulls t = 1 … T of ( q*(best arm) − q*(arm pulled at step t) )

Maximising the total reward and minimising regret are the same goal, but regret is easier to read, because 0 is perfect. It also shows how a strategy behaves over time: if a strategy keeps making mistakes at a fixed rate, its regret grows in a straight line, but if it gradually stops pulling poor arms, its regret flattens out.

Estimating values one reward at a time

The natural estimate of an arm's value is the sample average of its rewards so far. Storing every reward to recompute the average is wasteful, though, because the same average can be updated one reward at a time:

Qₙ₊₁ = Qₙ + (1 ÷ n) × (rₙ − Qₙ)

new estimate = old estimate + step size × (target − old estimate)

Each new reward rₙ nudges the estimate towards itself, by a fraction 1 ÷ n of the gap. The program checks that this gives exactly the average, then tries it on an arm whose value suddenly changes:

Try it yourselfPython
import numpy as np

rng = np.random.RandomState(0)
rewards = rng.normal(5.0, 2.0, size=1000)      # 1,000 rewards from one arm with true value 5

# Incremental update: keep only the estimate Q and the count n, never the list of rewards
Q = 0.0
for n, r in enumerate(rewards, start=1):
    Q = Q + (r - Q) / n                        # new = old + step size × (target − old)
print(f"incremental estimate {Q:.4f}   np.mean of all rewards {rewards.mean():.4f}")

# A changing arm: its true value jumps from 5 to 8 after 500 pulls
rewards = np.concatenate([rng.normal(5.0, 2.0, 500), rng.normal(8.0, 2.0, 500)])
Q_avg, Q_const = 0.0, 0.0
for n, r in enumerate(rewards, start=1):
    Q_avg += (r - Q_avg) / n                   # step size 1/n: every reward counts the same
    Q_const += 0.1 * (r - Q_const)             # constant step size 0.1: recent rewards count more
    if n in (500, 520, 550, 1000):
        print(f"after {n:>4} pulls: sample average {Q_avg:4.2f}   constant step 0.1 {Q_const:4.2f}")
Output
incremental estimate 4.9095   np.mean of all rewards 4.9095
after  500 pulls: sample average 5.06   constant step 0.1 4.76
after  520 pulls: sample average 5.16   constant step 0.1 7.47
after  550 pulls: sample average 5.33   constant step 0.1 8.05
after 1000 pulls: sample average 6.53   constant step 0.1 7.72

The incremental update matches np.mean exactly while storing just two numbers per arm. With a step size of 1 ÷ n, though, the 500th reward counts as much as the 1st, so when the arm's value jumped to 8, the sample average crawled: 500 pulls later it had only reached 6.53. A constant step size α (here 0.1) gives recent rewards more weight, so the estimate had almost caught up after just 20 more pulls, at the price of being noisier: it trusts the last few rewards, so it wobbles around the true value. Use 1 ÷ n when the world stays the same and a constant α when it drifts. Remember the shape of this update: Q-Learning uses exactly the same rule, with a different target.

Thompson sampling

ε-greedy and UCB keep one number per arm. Thompson sampling keeps a whole probability distribution: everything the data says the arm's value could plausibly be. For rewards that are 1 or 0 (a click or not, a sign-up or not), the natural choice is the Beta distribution. Starting from "any rate between 0 and 1 is equally likely", after s successes and f failures, Bayes' theorem gives Beta(1 + s, 1 + f). It is wide when there is little data and narrows as data piles up. The method itself is short:

for every pull:
    for each arm, draw one plausible value from its distribution, Beta(1 + successes, 1 + failures)
    pull the arm with the highest draw
    record the reward: a success or a failure for that arm

Here is one decision for three versions of a sign-up page, repeated 10,000 times to show how often each page wins:

Try it yourselfPython
import numpy as np

# Three versions of a sign-up page: sign-ups and visitors so far
names = ["A", "B", "C"]
signups = np.array([12, 18, 1])
visitors = np.array([100, 100, 10])

rng = np.random.RandomState(0)
a, b = 1 + signups, 1 + visitors - signups         # Beta posterior for each page's sign-up rate
samples = rng.beta(a, b, size=(10000, 3))          # 10,000 plausible rates for each page
chosen = samples.argmax(axis=1)                    # Thompson sampling: the page with the highest draw

for i, name in enumerate(names):
    low, high = np.percentile(samples[:, i], [5, 95])
    print(f"page {name}: {signups[i]:>2}/{visitors[i]:<3}  rate likely between {low:.2f} and {high:.2f}   "
          f"chosen {np.mean(chosen == i):5.1%} of the time")
Output
page A: 12/100  rate likely between 0.08 and 0.19   chosen  6.9% of the time
page B: 18/100  rate likely between 0.13 and 0.25   chosen 55.9% of the time
page C:  1/10   rate likely between 0.03 and 0.36   chosen 37.2% of the time

Page C has the lowest rate so far, 1 in 10, but it has had only 10 visitors, so its rate could plausibly be anywhere from 3% to 36%, and it wins the draw 37% of the time. Page A has had 100 visitors, and its range sits mostly below B's, so it rarely wins. That's how Thompson sampling explores: each page is shown with the probability that it is the best, given the data so far. As C gets more visitors, its range narrows, and it keeps being chosen only if it really is good. William R. Thompson proposed the idea in 1933, for clinical trials.

A k-armed testbed

One bandit problem proves little, because a strategy can be lucky. A testbed is a large set of randomly generated problems, and a strategy's score is its average over all of them. This testbed has 200 problems with k = 10 arms each, and every arm pays 1 with its own probability, drawn uniformly between 0 and 1. Every strategy faces the same 200 problems for 5,000 pulls. The contenders are ε-greedy and UCB from Exploration vs Exploitation, Thompson sampling, and a classic A/B test: show every arm 50 times in turn, then always show the winner.

Try it yourselfPython
import numpy as np

K, PROBLEMS, STEPS = 10, 200, 5000

def run(choose, seed=0):
    """Play 200 random 10-armed problems at once, one row each. Returns the regret curve."""
    rng = np.random.RandomState(seed)
    rates = rng.uniform(0, 1, size=(PROBLEMS, K))     # each arm pays 1 with its own probability
    best = rates.max(axis=1)                          # the same problems for every strategy
    pulls, wins = np.zeros((PROBLEMS, K)), np.zeros((PROBLEMS, K))
    rows, step_regret = np.arange(PROBLEMS), []
    for t in range(STEPS):
        a = choose(pulls, wins, t, rng)
        reward = rng.rand(PROBLEMS) < rates[rows, a]
        pulls[rows, a] += 1
        wins[rows, a] += reward
        step_regret.append(np.mean(best - rates[rows, a]))    # the expected reward this step lost
    found = np.mean(pulls.argmax(axis=1) == rates.argmax(axis=1))
    return np.cumsum(step_regret), found

def epsilon_greedy(pulls, wins, t, rng, eps=0.1):
    Q = np.where(pulls > 0, wins / np.maximum(pulls, 1), np.inf)      # untried arms go first
    explore = rng.rand(len(Q)) < eps
    return np.where(explore, rng.randint(K, size=len(Q)), Q.argmax(axis=1))

def ucb(pulls, wins, t, rng, c=1.0):
    score = wins / np.maximum(pulls, 1) + c * np.sqrt(np.log(t + 1) / np.maximum(pulls, 1))
    return np.where(pulls > 0, score, np.inf).argmax(axis=1)

def thompson(pulls, wins, t, rng):
    return rng.beta(1 + wins, 1 + pulls - wins).argmax(axis=1)       # the highest plausible rate

def ab_test(pulls, wins, t, rng, per_arm=50):
    if t < per_arm * K:
        return np.full(len(pulls), t % K)             # the test: 50 pulls for every arm, in turn
    return (wins / pulls).argmax(axis=1)              # then: always the winner of the test

print("strategy          regret after:   100   1,000   5,000   during the last 1,000   best arm found")
for name, choose in [("epsilon-greedy 0.1", epsilon_greedy), ("UCB, c = 1", ucb),
                     ("Thompson sampling", thompson), ("A/B test, then winner", ab_test)]:
    regret, found = run(choose)
    print(f"{name:<22} {regret[99]:15.1f} {regret[999]:7.1f} {regret[-1]:7.1f} "
          f"{regret[-1] - regret[-1001]:23.1f} {found:16.0%}")
Output
strategy          regret after:   100   1,000   5,000   during the last 1,000   best arm found
epsilon-greedy 0.1                12.1    56.8   231.4                    42.9              88%
UCB, c = 1                        23.1    88.4   166.5                    12.4              96%
Thompson sampling                 13.6    26.8    38.2                     1.5              96%
A/B test, then winner             41.3   208.1   217.0                     2.2              86%

The column "during the last 1,000" shows how fast each regret is still growing:

  • ε-greedy starts cheaply, but it never stops exploring: it still loses about 43 per 1,000 pulls, and will forever. Its regret is a straight line.
  • UCB explores hard at first, so its early regret is the highest of the three adaptive methods, but its growth keeps slowing (12.4 in the last 1,000 pulls), and by 5,000 pulls it has overtaken ε-greedy.
  • Thompson sampling has the lowest regret from 1,000 pulls on, and has almost stopped losing: 1.5 in the last 1,000.
  • The A/B test loses heavily during its 500 test pulls, because every arm, however poor, gets the same share of them, then almost nothing. But in 14% of the problems its winner wasn't the best arm, because 50 pulls per arm can't separate close rivals.

Theory backs this up. No strategy that does well on every problem can make its regret grow more slowly than the logarithm of the number of pulls (Lai and Robbins proved this in 1985). UCB and Thompson sampling grow at that logarithmic rate, while ε-greedy with a fixed ε grows in a straight line.

Bandits and A/B testing

A classic A/B test is "explore, then exploit" with a hard switch: split the traffic evenly for a fixed period, run a significance test, then send everyone to the winner. A bandit blends the two phases and moves traffic towards the better versions as the evidence comes in. Neither is always right:

Classic A/B testBandit
Traffic during the testFixed, even splitShifts towards the better versions as results arrive
Cost while learningHigh: many visitors see poor versions until the endLow: poor versions are dropped quickly
What you learnA clean estimate of every version's effect, with a significance testWhich version is best; poor versions get only rough estimates
Good forDecisions you must explain and defend, and slow or long-term effectsMany versions, short-lived choices such as headlines and promotions, and continuous optimisation

Online recommendations go one step further. A contextual bandit chooses using features of the current user, such as their device, location or past behaviour, so different people can get different best arms. It sits between plain bandits and full RL: there is a situation to look at, but actions still don't change future situations.

Common mistakes

Practice

Practice exercise

Complete the heart of Thompson sampling for three versions of a sign-up page. For each of 2,000 visitors, the program draws a plausible sign-up rate for every page from its Beta posterior. Show the page with the highest draw, then update that page's counts. Which page ends up with most of the visitors?

Your solutionPython
import numpy as np

RATES = np.array([0.10, 0.15, 0.20])    # true sign-up rates of pages A, B and C: unknown to the agent
rng = np.random.RandomState(0)
signups, views = np.zeros(3), np.zeros(3)

for visitor in range(2000):
    draws = rng.beta(1 + signups, 1 + views - signups)   # one plausible rate for each page
    page = 0                       # 1. show the page whose draw is highest
    signed_up = rng.rand() < RATES[page]
    # 2. add 1 to that page's views, and add signed_up (True counts as 1) to its sign-ups

print("visitors per page:", views.astype(int).tolist())
print("total sign-ups:", int(signups.sum()))
Knowledge check

After 5,000 pulls, ε-greedy with ε = 0.1 was still losing about 43 per 1,000 pulls, while Thompson sampling lost 1.5. Why does ε-greedy's regret keep growing?

Summary

  • A multi-armed bandit is RL with a single situation: choose among k arms with unknown average rewards. Regret, the reward lost compared with always pulling the best arm, measures a strategy.
  • Incremental updates, new estimate = old + step size × (target − old), give the sample average with a step size of 1 ÷ n, and track a changing world with a constant step size α.
  • Thompson sampling keeps a Beta distribution per arm, draws a plausible value from each, and pulls the highest, so each arm is chosen with the probability that it is the best.
  • On the testbed, ε-greedy's regret grew in a straight line, UCB's slowed down, and Thompson sampling's almost stopped growing.
  • A classic A/B test explores, then exploits, and gives clean estimates for every version. A bandit loses less while learning, and contextual bandits personalise the choice for each user.

Next: Q-Learning.

Finished reading? Tick it off to track your progress.