Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

Multi-Armed Bandits & Regret

Slot machines, regret, and why greedy play fails.

Greedy play can lose a fixed amount on every pull, forever; the best algorithms lose less and less. To tell them apart you need a precise model, a precise scoreboard, and one identity that turns regret into a question about how often each arm is pulled. This lesson builds all three and uses them to analyze greedy play, ε-greedy and explore-then-commit, with incremental estimates, optimistic initial values and drifting arms along the way.

What you’ll learn

  • Formalize the stochastic KK-armed bandit, define expected regret and pseudo-regret, and prove the decomposition RT=∑iΔi E[Ni(T)]R_T=\sum_i\Delta_i\,\E[N_i(T)].
  • Implement sample-average and incremental value estimates, and explain when a constant step size is the right choice.
  • Prove that greedy play and constant-ε exploration have linear regret, and state when a decaying ε achieves logarithmic regret.
  • Derive the regret bound of explore-then-commit, tune its exploration length, and explain what the tuning requires you to know.
  • Explain optimistic initial values and the limits of a one-time push to explore, including on nonstationary arms.

The stochastic bandit and its regret

A stochastic multi-armed bandit has KK arms. Arm ii has a reward distribution νi\nu_i, unknown to the learner, with mean μi\mu_i. Write μ⋆=max⁡iμi\mu^\star=\max_i\mu_i for the best mean and Δi=μ⋆−μi≥0\Delta_i=\mu^\star-\mu_i\ge0 for arm ii's suboptimality gap.

In rounds t=1,…,Tt=1,\dots,T the learner chooses an arm AtA_t, using only the history Ht−1=(A1,X1,…,At−1,Xt−1)H_{t-1}=(A_1,X_1,\dots,A_{t-1},X_{t-1}) and perhaps its own coin flips, and then receives a reward XtX_t drawn from νAt\nu_{A_t}, independently of everything before given AtA_t. The rule mapping histories to (distributions over) arms is the learner's policy. The count Ni(t)=∑s≤t1{As=i}N_i(t)=\sum_{s\le t}\mathbf 1\{A_s=i\} is how often arm ii was pulled in the first tt rounds.

DerivationThe regret decomposition
  1. E[Xt]=E[E[Xt∣Ht−1,At]]=E[μAt]\E[X_t]=\E\big[\E[X_t\mid H_{t-1},A_t]\big]=\E[\mu_{A_t}]

    Condition on the arm chosen. Given AtA_t (and the past), XtX_t is a fresh draw from νAt\nu_{A_t}, so its conditional mean is μAt\mu_{A_t}. The tower rule gives

  2. ∑t=1TμAt=∑i=1Kμi Ni(T)\sum_{t=1}^T\mu_{A_t}=\sum_{i=1}^K\mu_i\,N_i(T)

    Group the rounds by arm. Each round contributes the mean of the arm it used, so the sum of the chosen means counts every arm's mean once per pull:

  3. RT=Tμ⋆−∑i=1Kμi E[Ni(T)]=∑i=1KΔi E[Ni(T)]R_T=T\mu^\star-\sum_{i=1}^K\mu_i\,\E[N_i(T)]=\sum_{i=1}^K\Delta_i\,\E[N_i(T)]

    The counts add up to the horizon, ∑iNi(T)=T\sum_iN_i(T)=T, so Tμ⋆=∑iμ⋆Ni(T)T\mu^\star=\sum_i\mu^\star N_i(T). Subtract and take expectations:

  4. Every pull of arm ii costs Δi\Delta_i in expectation, whatever the policy. Bounding regret therefore means bounding how often each suboptimal arm is pulled, and every analysis in this topic starts here.

Check your understanding

Three arms have means 0.8, 0.6 and 0.3. Over 1,000 rounds a policy pulls them 900, 70 and 30 times in expectation. What is its regret?

  1. 100
  2. 29
  3. 51
  4. 0, because it pulled the best arm most of the time
Show the answer

B. 29

The gaps are 0, 0.2 and 0.5, so R1000=0.2×70+0.5×30=14+15=29R_{1000}=0.2\times70+0.5\times30=14+15=29. Equivalently, the policy earns 0.8⋅900+0.6⋅70+0.3⋅30=7710.8\cdot900+0.6\cdot70+0.3\cdot30=771 in expectation against 800800 for always pulling the best arm.

Estimating values: averages and step sizes

Almost every bandit algorithm keeps an estimate QQ of each arm's mean. The sample average of an arm's first nn rewards needs no stored history: write Qn+1=1n∑k=1nRkQ_{n+1}=\frac1n\sum_{k=1}^nR_k and peel off the last term to get the incremental form Qn+1=Qn+1n(Rn−Qn)Q_{n+1}=Q_n+\frac1n(R_n-Q_n). It is the template of every learning rule in this course: new estimate = old estimate + step size × (target − old estimate). A constant step size α∈(0,1]\alpha\in(0,1] changes what the estimate means.

DerivationA constant step size forgets geometrically
  1. Qn+1=αRn+(1−α)αRn−1+(1−α)2Qn−1=⋯Q_{n+1}=\alpha R_n+(1-\alpha)\alpha R_{n-1}+(1-\alpha)^2Q_{n-1}=\cdots

    Unroll Qn+1=Qn+α(Rn−Qn)=αRn+(1−α)QnQ_{n+1}=Q_n+\alpha(R_n-Q_n)=\alpha R_n+(1-\alpha)Q_n one step at a time:

  2. Qn+1=(1−α)nQ1+∑k=1nα(1−α)n−kRkQ_{n+1}=(1-\alpha)^nQ_1+\sum_{k=1}^n\alpha(1-\alpha)^{n-k}R_k

    All the way back to the initial value Q1Q_1:

  3. The weights add up to (1−α)n+α∑j=0n−1(1−α)j=1(1-\alpha)^n+\alpha\sum_{j=0}^{n-1}(1-\alpha)^j=1, so this is a weighted average, but recent rewards weigh most and old ones fade geometrically: an exponential recency-weighted average with a memory of about 1/α1/\alpha rewards. The initial value's weight (1−α)n(1-\alpha)^n never vanishes in finite time, so the estimate is biased by Q1Q_1, less and less.

python
import numpy as np

class EpsilonGreedy:
    def __init__(self, k, eps=0.1, step=None, q0=0.0, seed=0):
        self.q = np.full(k, q0, dtype=float)   # value estimates
        self.n = np.zeros(k, dtype=int)        # pull counts
        self.eps, self.step = eps, step        # step=None: sample average
        self.rng = np.random.default_rng(seed)

    def act(self):
        if self.rng.random() < self.eps:       # explore
            return int(self.rng.integers(len(self.q)))
        best = np.flatnonzero(self.q == self.q.max())
        return int(self.rng.choice(best))      # exploit, break ties at random

    def update(self, arm, reward):
        self.n[arm] += 1
        alpha = 1.0 / self.n[arm] if self.step is None else self.step
        self.q[arm] += alpha * (reward - self.q[arm])

An ε-greedy agent with incremental updates: constant memory per arm and constant time per step. With eps=0 it is greedy; with q0 above every plausible reward it uses optimistic initial values (the last step of this lesson).

Predict before you look

With a constant step size α=0.1\alpha=0.1, what weight does the estimate give to the reward received 10 pulls before the most recent one?

Show the answer

0.035

The most recent reward has weight α=0.1\alpha=0.1, and each step back multiplies by 1−α=0.91-\alpha=0.9: 0.1×0.910≈0.0350.1\times0.9^{10}\approx0.035. The last 10 rewards together carry 1−0.910≈65%1-0.9^{10}\approx65\% of the total weight, so the estimate reacts within tens of pulls to a change in the arm.

Greedy and ε-greedy: linear regret, and the way out

The decomposition turns "this policy is bad" into a statement about pull counts. For greedy play the counts can be catastrophically wrong with constant probability, and for constant-ε exploration they are wrong by a constant fraction of TT.

DerivationBoth have linear regret
  1. Pr⁡(X1(1)=0, X1(2)=1)=(1−μ1) μ2\Pr\big(X^{(1)}_1=0,\ X^{(2)}_1=1\big)=(1-\mu_1)\,\mu_2

    Greedy. Take two Bernoulli arms with μ1>μ2>0\mu_1>\mu_2>0, and let greedy pull each arm once and then always pull the higher sample average (ties broken at random). With probability (1−μ1)μ2(1-\mu_1)\mu_2, arm 1's first reward is 0 and arm 2's is 1:

  2. RT ≥ (1−μ1) μ2 Δ (T−2)R_T\ \ge\ (1-\mu_1)\,\mu_2\,\Delta\,(T-2)

    On that event arm 1's estimate is 0 and stays 0, because arm 1 is never pulled again, while arm 2's average is at least 1/n>01/n>0 after nn pulls. So greedy pulls arm 2 in every remaining round:

  3. RT ≥ εK∑i=1KΔi  TR_T\ \ge\ \frac{\varepsilon}{K}\sum_{i=1}^K\Delta_i\;T

    For μ=(0.75,0.5)\mu=(0.75,0.5) that is at least 0.031 (T−2)0.031\,(T-2): linear. Constant ε. In every round each arm is chosen at random with probability at least ε/K\varepsilon/K, so E[Ni(T)]≥εT/K\E[N_i(T)]\ge\varepsilon T/K and

The schedule must shrink like 1/t1/t, but with the right constant. By round tt each arm has had about (cK/d2)ln⁡t/K(cK/d^2)\ln t/K random pulls, enough that confusing two arms a gap dd apart has probability polynomially small in tt, with an exponent above 1 when cc is large enough. A schedule like εt=1/t\varepsilon_t=1/t still explores forever, since ∑t1/t=∞\sum_t1/t=\infty, and is greedy in the limit (GLIE), but each arm then gets only about ln⁡t/K\ln t/K random pulls: misidentification probabilities can decay too slowly to sum, leaving regret that grows polynomially in TT.

The catch is dd: the theorem needs a lower bound on the smallest gap, which is exactly what you do not know. In Auer et al.'s experiments a well-tuned schedule was often the best policy they tried, but its performance degraded rapidly when the constant was off.

Explore-then-commit

The cleanest way to separate learning from earning is to do one and then the other. Explore-then-commit (ETC) pulls every arm mm times in turn, then commits to the arm with the best sample average for the remaining T−mKT-mK rounds. Its analysis needs one more ingredient: a random variable YY is σ\sigma-subgaussian if E[eλ(Y−EY)]≤eλ2σ2/2\E[e^{\lambda(Y-\E Y)}]\le e^{\lambda^2\sigma^2/2} for all λ\lambda, which gives the tail bound Pr⁡(Y−EY≥ε)≤e−ε2/(2σ2)\Pr(Y-\E Y\ge\varepsilon)\le e^{-\varepsilon^2/(2\sigma^2)}. Rewards in [0,1][0,1] are 12\tfrac12-subgaussian (Hoeffding's lemma), hence also 1-subgaussian.

DerivationProof
  1. E[Ni(T)]=m+(T−mK)Pr⁡(commit to i) ≤ m+(T−mK)Pr⁡(μ^i≥μ^1)\E[N_i(T)]=m+(T-mK)\Pr\big(\text{commit to }i\big)\ \le\ m+(T-mK)\Pr\big(\hat\mu_i\ge\hat\mu_1\big)

    Let arm 1 be optimal. Exploration is deterministic (each arm exactly mm times), and arm ii gets all remaining rounds if it wins the comparison:

  2. Pr⁡(μ^i≥μ^1)=Pr⁡((μ^i−μi)−(μ^1−μ1)≥Δi)\Pr\big(\hat\mu_i\ge\hat\mu_1\big)=\Pr\Big(\big(\hat\mu_i-\mu_i\big)-\big(\hat\mu_1-\mu_1\big)\ge\Delta_i\Big)

    Rewrite the event around the gap, with μ^i\hat\mu_i the average of arm ii's mm exploration rewards:

  3. Pr⁡(μ^i≥μ^1) ≤ exp⁡ ⁣(−Δi22⋅2/m)=exp⁡ ⁣(−mΔi24)\Pr\big(\hat\mu_i\ge\hat\mu_1\big)\ \le\ \exp\!\Big(-\frac{\Delta_i^2}{2\cdot2/m}\Big)=\exp\!\Big(-\frac{m\Delta_i^2}{4}\Big)

    An average of mm independent 1-subgaussian variables is 1/m1/\sqrt m-subgaussian, and the difference of two independent ones is 2/m\sqrt{2/m}-subgaussian (variance proxies add). The tail bound with σ2=2/m\sigma^2=2/m gives

  4. m=max⁡{1,⌈4Δ2ln⁡TΔ24⌉},RT ≤ min⁡{TΔ, Δ+4Δ(1+max⁡{0,ln⁡TΔ24})}m=\max\Big\{1,\Big\lceil\frac{4}{\Delta^2}\ln\frac{T\Delta^2}{4}\Big\rceil\Big\},\qquad R_T\ \le\ \min\Big\{T\Delta,\ \Delta+\frac4\Delta\Big(1+\max\Big\{0,\ln\frac{T\Delta^2}{4}\Big\}\Big)\Big\}

    Multiply by Δi\Delta_i and sum over arms, using the regret decomposition. For two arms with gap Δ\Delta the bound is mΔ+TΔe−mΔ2/4m\Delta+T\Delta e^{-m\Delta^2/4}; setting its derivative in mm to zero gives the tuned length and the resulting bound:

Predict before you look

Two arms with gap Δ=0.1\Delta=0.1 and horizon T=10,000T=10{,}000. How many pulls per arm does the tuned explore-then-commit use before committing?

Show the answer

1288

m=⌈(4/0.01)ln⁡(10,000×0.01/4)⌉=⌈400ln⁡25⌉=⌈1287.6⌉=1288m=\lceil(4/0.01)\ln(10{,}000\times0.01/4)\rceil=\lceil400\ln25\rceil=\lceil1287.6\rceil=1288, so about a quarter of the horizon goes to exploration. The bound is 0.1+40 (1+ln⁡25)≈1690.1+40\,(1+\ln25)\approx169, against 500500 for splitting the pulls evenly forever.

The tuned mm needs the gap Δ\Delta, which is unknown, and the horizon TT. If mm may depend only on TT, the best worst-case guarantee falls to order T2/3T^{2/3}, against order T\sqrt T when Δ\Delta is known (Lattimore & Szepesvári, ch. 6). ETC is also wasteful on easy instances: with a large gap a few pulls would settle the question, yet the schedule keeps exploring.

Both problems have the same fix: decide from the data when to stop exploring an arm. Eliminating an arm once a confidence interval separates it from the leader adapts to the unknown gaps (Best-Arm Identification), and UCB never commits at all but keeps every arm's exploration proportional to how plausible it still is (Optimism: Upper Confidence Bounds).

Optimistic initial values and drifting arms

A cheap way to make a greedy learner explore is to start every estimate far above any plausible reward, an optimistic initialization. Every arm then disappoints when pulled, its estimate drops below the untried ones, and greedy play works through all the arms before settling. In Sutton and Barto's 10-armed testbed (true values drawn from a standard normal), greedy play with Q1=+5Q_1=+5 and α=0.1\alpha=0.1 eventually beats ε-greedy with ε=0.1\varepsilon=0.1 started at Q1=0Q_1=0, after a slow start.

The push is temporary. With sample averages it lasts exactly one pull per arm, since Q2=Q1+1⋅(R1−Q1)=R1Q_2=Q_1+1\cdot(R_1-Q_1)=R_1 erases the initial value. With a constant step size it fades geometrically. After that the learner is plain greedy, with all its failure modes. Optimism that is renewed by uncertainty, rather than spent once, is the idea behind UCB.

Check your understanding

A greedy learner starts every estimate at Q1=10Q_1=10 for rewards in [0,1][0,1] and updates by sample averages (αn=1/n\alpha_n=1/n). What does the optimism buy it?

  1. Logarithmic regret on every instance
  2. Exactly one pull of each arm, after which it behaves like ordinary greedy play
  3. Exploration that continues forever at a slowly decreasing rate
  4. Nothing: greedy ignores initial values
Show the answer

B. Exactly one pull of each arm, after which it behaves like ordinary greedy play

The first update of an arm replaces its estimate by its first reward, Q2=R1Q_2=R_1, so the optimism forces each arm to be tried once and is then gone. From there the learner can lock onto a worse arm exactly as greedy play does. With a constant step size the optimism decays over several pulls instead, but it still runs out.

Real arms drift: click rates change with seasons, prices and fashion. In a nonstationary bandit the sample average reacts ever more slowly, since the nn-th reward has weight 1/n1/n, while a constant step size keeps tracking. UCB has forgetful versions too: discounted UCB and sliding-window UCB compute their indices from discounted or recent data only (Garivier & Moulines, 2011).

There is a genuine tension, not just a tuning problem. Lattimore and Szepesvári (Theorem 31.2) show that, already with two arms, a policy with regret RR on a stationary bandit with gap Δ\Delta has regret at least T/(22R)T/(22R) on some bandit whose means switch at most twice while keeping a gap of at least Δ\Delta, as soon as TT is large enough. A policy with logarithmic regret on fixed arms must therefore suffer regret of order T/log⁡TT/\log T on some switching problem. Being ready for change means checking the apparently worse arms often, and that costs regret when nothing changes.

Key takeaways

  • A stochastic bandit has KK arms with unknown means; regret is Tμ⋆T\mu^\star minus the expected reward, and it decomposes as RT=∑iΔi E[Ni(T)]R_T=\sum_i\Delta_i\,\E[N_i(T)] for every policy.
  • Incremental updates Q←Q+α(R−Q)Q\leftarrow Q+\alpha(R-Q) with α=1/n\alpha=1/n give sample averages; a constant α\alpha gives an exponential recency-weighted average that tracks drifting arms but never settles.
  • Greedy play locks onto a worse arm with constant probability and constant-ε exploration pays ε/K\varepsilon/K per arm per round: both have linear regret. A decaying εt∝K/(d2t)\varepsilon_t\propto K/(d^2t) achieves logarithmic regret, but only with a lower bound dd on the gap.
  • Explore-then-commit has regret at most m∑iΔi+(T−mK)∑iΔie−mΔi2/4m\sum_i\Delta_i+(T-mK)\sum_i\Delta_ie^{-m\Delta_i^2/4}; tuned with the gap it is O(log⁡T/Δ)\order{\log T/\Delta}, but the tuning needs Δ\Delta, and without it the worst case is of order T2/3T^{2/3}.
  • Optimistic initial values force early exploration and then run out. Drifting arms call for forgetting, and a policy with logarithmic regret on fixed arms must pay heavily on some switching ones.

Check yourself

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

Question 1

Why can the regret of any policy be written as ∑iΔi E[Ni(T)]\sum_i\Delta_i\,\E[N_i(T)]?

  1. Because the policy pulls each arm equally often in expectation
  2. Because given the arm chosen in a round, that round's reward has the arm's mean as its conditional expectation, so each pull of arm ii costs Δi\Delta_i in expectation
  3. Because rewards are bounded in [0,1][0,1]
  4. Because the policy is deterministic
Show the answer

B. Because given the arm chosen in a round, that round's reward has the arm's mean as its conditional expectation, so each pull of arm ii costs Δi\Delta_i in expectation

E[Xt]=E[μAt]\E[X_t]=\E[\mu_{A_t}] by the tower rule, since the reward is drawn from the chosen arm independently of the past. Grouping rounds by arm and using ∑iNi(T)=T\sum_iN_i(T)=T gives the identity, for any policy, randomized or not, adaptive or not.

Question 2

ε-greedy with ε=0.05\varepsilon=0.05 plays 4 arms with gaps 0, 0.1, 0.2 and 0.3 for 10,000 rounds. What is the guaranteed lower bound on its regret from random exploration alone?

  1. 75
  2. 7.5
  3. 300
  4. 0, because the estimates converge
Show the answer

A. 75

Each arm is pulled at random with probability at least ε/K=0.0125\varepsilon/K=0.0125 per round, so RT≥0.0125×(0+0.1+0.2+0.3)×10,000=75R_T\ge0.0125\times(0+0.1+0.2+0.3)\times10{,}000=75, and the bound keeps growing linearly with TT.

Question 3

In tuned explore-then-commit, m≈(4/Δ2)ln⁡(TΔ2/4)m\approx(4/\Delta^2)\ln(T\Delta^2/4). Ignoring the logarithm, what happens to the exploration length if the gap is halved?

  1. It halves
  2. It doubles
  3. It stays the same
  4. It grows about fourfold
Show the answer

D. It grows about fourfold

mm scales like 1/Δ21/\Delta^2: telling apart two arms that are half as far apart takes four times the samples, because a sample average's error shrinks like 1/m1/\sqrt m. The regret bound scales like log⁡T/Δ\log T/\Delta, since each of those pulls costs only Δ\Delta.

Question 4

Which step-size sequence makes the incremental estimate of a stationary arm converge with probability 1, by the Robbins–Monro conditions?

  1. αn=0.1\alpha_n=0.1
  2. αn=1/n\alpha_n=1/\sqrt n
  3. αn=1/n\alpha_n=1/n
  4. αn=1/n2\alpha_n=1/n^2
Show the answer

C. αn=1/n\alpha_n=1/n

The conditions are ∑αn=∞\sum\alpha_n=\infty and ∑αn2<∞\sum\alpha_n^2<\infty. For 1/n1/n: the harmonic series diverges and ∑1/n2=π2/6\sum1/n^2=\pi^2/6. That is the sample average.

Go deeper

Further reading

  • T. Lattimore & C. Szepesvári, Bandit Algorithms, ch. 4 and 6 (Cambridge University Press, 2020).
  • P. Auer, N. Cesa-Bianchi & P. Fischer, "Finite-time analysis of the multiarmed bandit problem," Machine Learning 47, 235–256 (2002).
  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 2 (MIT Press, 2nd ed., 2018).