Simple Algorithm
Reinforcement Learning · Exploration · 17 min

Bandits & the Explore–Exploit Dilemma

One state, many arms: the simplest problem where learning has a price.

In 1933 William R. Thompson, writing from Yale, asked how to choose between two medical treatments while evidence about them is still coming in: every patient given the worse one pays for your ignorance, yet you cannot learn without trying both. The same dilemma now runs web pages, ad auctions and recommendation feeds. This lesson turns it into a row of slot machines, a scoreboard called regret, and three strategies that keep learning without losing too much.

What you’ll learn

  • Describe a multi-armed bandit: arms with unknown payout rates, and the price paid while learning which one is best.
  • Explain why always pulling the best-looking arm can lock onto a bad one forever, and what ε-greedy does about it.
  • Read a regret curve, and tell the linear regret of naive strategies from the logarithmic regret of good ones.
  • Explain optimism (UCB) and Thompson sampling in plain words, including how a Beta distribution captures a belief about an arm.
  • Recognize bandits in A/B tests, ads, recommendations and clinical trials, with their caveats, and see a bandit as reinforcement learning with a single state.

Five machines, one budget

A slot machine used to be nicknamed a one-armed bandit. Picture a row of five of them. Each pays out a point with its own fixed probability, the probabilities differ, and nobody will tell you what they are. You have a budget of pulls and want as many points as possible.

This is the multi-armed bandit: a set of arms, each paying a random reward whose average you do not know, and a learner that picks one arm per round. It is the simplest problem in which learning has a price. Every pull does two jobs at once: it earns a reward, and it tells you something about the arm you pulled, and only about that arm.

Think first Machine C has paid on both of its 2 pulls. Machine D has paid on 30 of its 50 pulls. Which would you pull next, and why is the answer not obvious?

Two pulls say little: even a machine paying 40% of the time wins twice in a row with probability 0.42=0.160.4^2=0.16, so C's true rate could be anything from mediocre to excellent. D's 30 of 50 pins its rate near 0.6, give or take about 0.07 (one standard error, 0.6⋅0.4/50\sqrt{0.6\cdot0.4/50}). Pulling D cashes in on what you know (exploitation); pulling C buys information (exploration). Making that choice well, pull after pull, is the exploration–exploitation dilemma.

Why greedy gets stuck

Greedy's failure is not bad luck you can ignore; it is built in. Greedy learns only about the arm it pulls, so an arm that disappoints early is never pulled again, and its unlucky estimate is never corrected. The best arm can be lost this way after a single bad pull.

Think first The best machine pays 75% of the time, and greedy pulls every machine once to start. How likely is greedy to lose the best machine right away, and why is the loss permanent?

The best machine's single opening pull pays nothing with probability 1−0.75=0.251-0.75=0.25. Its estimate is then 0, while any machine whose first pull paid has a positive average that can never fall back to exactly 0, so greedy never returns to the best machine. With the other four machines paying 0.3, 0.55, 0.2 and 0.45, at least one of them pays on its first pull with probability 1−0.7⋅0.45⋅0.8⋅0.55≈0.861-0.7\cdot0.45\cdot0.8\cdot0.55\approx0.86, so about 0.25×0.86≈0.220.25\times0.86\approx0.22 of all runs lose the best machine after one pull. Each later pull of a worse machine costs its gap, again and again: regret that grows in proportion to time.

The simplest cure is to stay a little curious. ε-greedy pulls the greedy action, the arm with the best average, most of the time, but with a small probability ε\varepsilon (say 0.1) it pulls an arm chosen uniformly at random. No arm is abandoned for good, so every estimate is eventually corrected. The cure has a cost, though.

Predict before you look

ε-greedy with ε=0.1\varepsilon=0.1 plays the five machines (rates 0.3, 0.55, 0.2, 0.75 and 0.45) and has already found the best one. On average, how much reward does it still lose per 1,000 pulls, just from its random pulls?

Show the answer

30

A random pull lands on each machine with probability 1/5 and loses 0.45, 0.2, 0.55, 0 or 0.3 compared with the best: 0.3 on average. Random pulls happen 10% of the time, so the loss is 0.1×0.3=0.030.1\times0.3=0.03 per pull, or 30 per 1,000, forever. ε-greedy keeps paying for exploration it no longer needs, so its regret also grows in proportion to time, only with a gentler slope than an unlucky greedy run.

Regret: keeping score

How do you compare strategies when luck plays such a large part? Measure each one against the reward it would have earned by always pulling the best arm. Write μi\mu_i for arm ii's average reward and μ⋆\mu^\star for the best of them. The regret after TT pulls is the expected shortfall:

RT  =  T μ⋆  −  E[total reward collected in T pulls]R_T \;=\; T\,\mu^\star \;-\; \E\Big[\text{total reward collected in } T \text{ pulls}\Big]
Regret is the price of not knowing. A player who knew the rates would have regret 0; a player who never learns has regret that grows in proportion to TT. The expectation averages over the luck of the draws, so regret describes a strategy, not a single run.

What separates strategies is the shape of the curve. A strategy that keeps making the same mistakes has regret that grows linearly, like 0.03 T0.03\,T for ε-greedy above. A strategy that explores less and less as it learns can have regret that grows like the logarithm of TT: every tenfold increase in time adds the same fixed amount. Lai and Robbins proved in 1985 that no strategy that works well on every bandit can do better than logarithmic growth, so the logarithm is the gold standard.

Predict before you look

A strategy's regret is 40 after 1,000 pulls and grows like the logarithm of time. About how large will it be after 1,000,000 pulls?

Show the answer

80

If RT=Cln⁡TR_T=C\ln T, then C=40/ln⁡1000≈5.8C=40/\ln1000\approx5.8 and R≈5.8×ln⁡106≈80R\approx5.8\times\ln10^6\approx80. A thousand times more pulls, only twice the regret, because ln⁡106=2ln⁡103\ln10^6=2\ln10^3. A strategy with linear regret and the same 40 after 1,000 pulls would reach 40,000.

Think first Strategy X has regret 30 after 1,000 pulls and 300 after 10,000. Strategy Y has regret 60 after 1,000 pulls and 80 after 10,000. Which would you rather run for a million pulls?

Y. X's regret grew tenfold when time grew tenfold: a fixed 0.03 per pull, linear. Y's grew by 20 per tenfold increase, which is logarithmic (RT≈8.7ln⁡TR_T\approx8.7\ln T fits both points). X leads early, but the curves cross at about 2,200 pulls, and at a million pulls X is near 30,000 while Y is near 120.

Optimism: the benefit of the doubt

Here is a principle that fixes greedy play without wasting pulls at random: be optimistic about what you do not know. Score each arm not by its average but by the best rate it could plausibly have, given the evidence so far, and pull the arm with the highest score.

A rarely tried arm has a wide range of plausible rates, so its optimistic score is high and it gets tried. Each pull narrows the range. An arm that really is poor sees its score sink below the best arm's and is left alone, and it is tried less and less often as the evidence piles up. Either the optimistic guess was right, and you earn, or it was wrong, and you learn exactly what you needed to learn. This is optimism in the face of uncertainty.

scorei  =  μ^i⏟average so far  +  2ln⁡tni⏟bonus, shrinks as ni grows\text{score}_i \;=\; \underbrace{\hat\mu_i}_{\text{average so far}} \;+\; \underbrace{\sqrt{\frac{2\ln t}{n_i}}}_{\text{bonus, shrinks as } n_i \text{ grows}}
The score of UCB1 (Auer, Cesa-Bianchi & Fischer, 2002), the best-known upper confidence bound strategy: tt is the number of pulls so far and nin_i the number of pulls of arm ii. The bonus is the half-width of a confidence interval, so the score is a plausible upper limit for the arm's rate. The slowly growing ln⁡t\ln t makes sure that no arm is written off for good.
Check your understanding

After 100 pulls, three arms have these records: A averages 0.62 over 60 pulls, B averages 0.55 over 30 pulls, C averages 0.40 over 10 pulls. Which arm does UCB1 pull next? (Use ln⁡100≈4.6\ln100\approx4.6.)

  1. A, the arm with the best average
  2. B, a compromise between average and evidence
  3. C, the arm with the least evidence
  4. None of them until all three have equal counts
Show the answer

C. C, the arm with the least evidence

The bonuses are 9.2/60≈0.39\sqrt{9.2/60}\approx0.39, 9.2/30≈0.55\sqrt{9.2/30}\approx0.55 and 9.2/10≈0.96\sqrt{9.2/10}\approx0.96, so the scores are about 1.01, 1.10 and 1.36. C has the worst average but by far the least evidence: 40% over 10 pulls is still consistent with a much better rate. If C really is poor, a few more pulls will show it and its bonus will shrink. That is why optimism corrects itself.

Optimism pays off in the long run: UCB1's regret provably grows only like ln⁡T\ln T. Its textbook bonus is cautious, though, and at short horizons it can explore more than it needs. On the five machines of the first step, UCB1's regret over 500 pulls averages about 57, against about 28 for ε-greedy and about 19 for the next strategy in this lesson. Theory guarantees the rate of growth, not the size of the constant in front of it.

Beliefs you can sample

Another way to handle uncertainty is to keep track of it explicitly. Instead of a single estimate of each arm's rate, keep a whole distribution of plausible rates: a belief. For an arm that pays 0 or 1, a convenient belief is the Beta distribution.

Start from Beta(1, 1), which says that every rate between 0 and 1 is equally plausible. After ss successes and ff failures the belief is Beta(1+s1+s, 1+f1+f): it peaks near the observed success rate and narrows as the counts grow. This is Bayes' rule at work, turning a prior into a posterior one observation at a time.

Think first After 10 flips the belief peaks at 0.9, yet the coin's true rate is 0.7. Was the belief wrong?

No. A belief is a statement of uncertainty, not a single guess. Beta(10, 2) gives substantial probability to rates near 0.7, which lies inside its 95% interval (0.59 to 0.98). Exactly 9 heads in 10 flips is lucky for a 0.7 coin (probability about 12%) but not shocking, and the next 90 flips pull the belief toward the truth. What matters for decisions is that the belief's width says how far its peak can be trusted.

Thompson sampling: act on a plausible guess

Thompson sampling turns beliefs into actions with one rule. Every round, draw one random rate from each arm's belief, as if rolling dice weighted by your uncertainty, and pull the arm whose draw is highest. Then update that arm's belief with the result.

An arm you know well gives draws close to its average. An arm you know little about gives draws that swing widely, so it sometimes wins the comparison and gets explored. In effect, each arm is pulled with the probability that it is the best one, given everything seen so far. No bonus needs tuning: the beliefs themselves decide how much to explore.

Predict before you look

Two arms: A's belief is Beta(10, 2) (mean 0.83, wide) and B's is Beta(74, 28) (mean 0.73, narrow), the two beliefs you just met. In what fraction of rounds does Thompson sampling pull A?

Show the answer

0.83

About 0.83: the probability, under the two beliefs, that A's rate exceeds B's (it comes from integrating over both Beta distributions). A is favored but not with certainty: in roughly one round in six, the draw from A's wide belief falls below the draw from B's narrow one and B is pulled. As A collects evidence its belief narrows, and if A really is better its share rises toward 1.

Bandits at work, and the road to RL

Wherever a system repeatedly chooses among options and sees how each choice went, a bandit is hiding. The applications are real, and so are the ways they differ from the clean model.

SettingArmsRewardCaveat
A/B testingVersions of a web pageA click or a purchaseA fixed 50/50 split gives cleaner statistics. A bandit earns more during the test, but it learns less about the losing versions, and its estimates of versions dropped after an unlucky start are biased downward.
Online adsWhich ad to showA clickRewards arrive late (a purchase days after a click), and click rates drift with seasons and fashions: a nonstationary bandit.
RecommendationArticles, songs, productsEngagementThe best arm depends on who is asking, so the problem is a contextual bandit (below).
Clinical trialsTreatmentsRecoveryThompson's original motivation. Adaptive allocation gives more patients the better treatment, but it costs statistical power and raises regulatory and ethical questions; as of the mid-2020s, bandit-style designs remain uncommon in practice.
Two lessons recur in this topic. If all you need is to identify the best option at the end, the right objective is best-arm identification, not regret. And the best arm often depends on side information.

A contextual bandit sees a context, such as what is known about the current user, before it chooses, and learns a policy: a map from contexts to arms. News recommendation at Yahoo! was an early large-scale example (Li, Chu, Langford & Schapire, 2010).

A bandit is also reinforcement learning with the hardest parts removed. It is an MDP with a single state: your action earns a reward but never changes the situation you face next. Full RL adds states, so actions have consequences and useful information can be many steps away. Exploration then gets harder, because learning what lies at the end of a corridor means walking the whole corridor on purpose (deep exploration). Yet the bandit ideas carry over: optimism becomes confidence bounds on whole environments and exploration bonuses in deep RL, and Thompson sampling becomes posterior sampling over environments.

Check your understanding

Which of these is a bandit problem rather than a full reinforcement learning problem?

  1. A robot learning to walk, where each motor command changes its posture for the next step
  2. A news site choosing which of three headlines to show each visitor, where one visitor's click does not affect the next visitor
  3. A chess program learning from games against itself
  4. A thermostat learning when to heat a house whose temperature carries over from hour to hour
Show the answer

B. A news site choosing which of three headlines to show each visitor, where one visitor's click does not affect the next visitor

Each visitor is a fresh round: the headline earns a click or not and leaves the next round unchanged, which is a bandit (a contextual one, if the site uses what it knows about the visitor). In the other three, today's action changes tomorrow's situation, so the learner must reason about consequences: full RL.

In the Bootstrapping lessons you'll make all of this precise. Multi-Armed Bandits & Regret defines regret formally, proves how it splits over the arms, and analyzes greedy play, ε-greedy and explore-then-commit. Optimism: Upper Confidence Bounds derives UCB1 from a concentration inequality and shows why its regret is logarithmic. Thompson Sampling & Bayesian Bandits builds Thompson sampling from Bayes' rule and compares it with UCB. Contextual Bandits adds side information, from LinUCB to learning from the logs of deployed systems. The Fixed Point lessons then prove what no algorithm can beat, and carry optimism and posterior sampling into whole MDPs.

Key takeaways

  • A multi-armed bandit is a sequence of choices among arms with unknown average rewards. Each pull earns and informs, which creates the exploration–exploitation dilemma.
  • Regret, the expected shortfall against always pulling the best arm, is the scoreboard. Greedy play and fixed-rate exploration lose a fixed amount per pull (linear regret); good strategies lose less and less (logarithmic regret), which is the best possible.
  • Optimism (UCB) scores each arm by a plausible upper limit of its rate, so uncertain arms are tried until the evidence rules them out.
  • Thompson sampling keeps a belief for each arm (a Beta distribution for 0/1 rewards) and pulls the arm whose random draw is highest, exploring each arm in proportion to its chance of being the best.
  • Bandits run A/B tests, ads and recommendations, with real caveats: delayed and drifting rewards, and biased estimates. A bandit is reinforcement learning with a single state, and its ideas carry over to full RL.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What does a strategy's regret after TT pulls measure?

  1. The number of times it pulled an arm that was not the best
  2. How much expected reward it lost compared with always pulling the best arm
  3. How much less it earned than the luckiest possible sequence of pulls
  4. How much its total reward varies from run to run
Show the answer

B. How much expected reward it lost compared with always pulling the best arm

Regret is Tμ⋆T\mu^\star minus the expected total reward: the price of having to learn. It is zero only for a player who knew the best arm from the start.

Question 2

Why can greedy play lock onto a worse arm forever?

  1. Its averages are computed incorrectly
  2. It explores too much
  3. It forgets old rewards
  4. An arm that disappoints early is never pulled again, so its low estimate is never corrected
Show the answer

D. An arm that disappoints early is never pulled again, so its low estimate is never corrected

Greedy only learns about the arms it pulls. If the best arm starts unluckily, its estimate stays low because greedy never gathers the data that would raise it. Exploration exists to break this loop.

Question 3

In Thompson sampling, how does a rarely tried arm get pulled?

  1. Its belief is wide, so its random draw sometimes exceeds the draws of better-known arms
  2. It receives a fixed bonus added to its average
  3. It is pulled on a fixed schedule, every tenth round
  4. It never is: Thompson sampling always pulls the arm with the highest average
Show the answer

A. Its belief is wide, so its random draw sometimes exceeds the draws of better-known arms

Each round draws one plausible rate from every arm's belief. A rarely tried arm has a wide belief, so its draws swing widely and sometimes win; as evidence accumulates its belief narrows and it wins only if it really looks best.

Question 4

Strategy A's regret doubles whenever the horizon doubles. Strategy B's regret rises by about 10 whenever the horizon doubles. Which statement is right?

  1. A is better, because doubling is a small change
  2. Both grow at the same rate
  3. B's regret grows logarithmically and A's linearly, so B wins at long enough horizons
  4. Neither can be compared without knowing the arms
Show the answer

C. B's regret grows logarithmically and A's linearly, so B wins at long enough horizons

Doubling with the horizon means regret proportional to TT. A fixed increase per doubling means regret proportional to log⁡T\log T: here about (10/ln⁡2)ln⁡T≈14.4ln⁡T(10/\ln2)\ln T\approx14.4\ln T. Whatever the constants, a logarithm eventually falls far below any straight line.

Question 5

A company must pick one of two checkout pages for good and wants a reliable estimate of how much better the winner is. Which design fits that goal best?

  1. Thompson sampling, because it maximizes revenue during the test
  2. A fixed split followed by a statistical comparison, or a best-arm identification method, because the goal is accurate identification rather than reward during the test
  3. Greedy, because it commits fastest
  4. Any bandit algorithm: the objective makes no difference
Show the answer

B. A fixed split followed by a statistical comparison, or a best-arm identification method, because the goal is accurate identification rather than reward during the test

Regret-minimizing bandits shift traffic to the leader quickly, which earns more during the test but leaves few samples of the loser, so the estimated difference is imprecise, and biased against versions dropped after an unlucky start. When the deliverable is a decision and an effect size, design for that objective.

Go deeper

Further reading

  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 2 (MIT Press, 2nd ed., 2018).
  • T. Lattimore & C. Szepesvári, Bandit Algorithms, ch. 1 (Cambridge University Press, 2020).