Chapter 2

Multi-armed Bandits

Strip away states and delayed consequences, and what remains of reinforcement learning is a single question asked over and over: which action is best, when the only way to find out is to try them and see what they pay? That is the kk-armed bandit problem. It isolates the feature that most distinguishes reinforcement learning from supervised learning, evaluative feedback: a reward says how good the chosen action was, not which action would have been best (see Section 1.1.1). This chapter builds the estimators and the exploration rules that later chapters reuse everywhere: sample averages and their incremental form, constant step sizes and the bias–variance trade-off they imply, optimistic initial values, upper confidence bounds, and gradient ascent on action preferences, which is the first policy-gradient method of the book. A final section goes beyond Sutton and Barto to the theory of regret and optimal exploration.

2.1The k-armed Bandit Problem

You face, repeatedly, a choice among kk actions. After each choice you receive a numerical reward drawn from a stationary distribution that depends on the action chosen, and your goal is to maximize the expected total reward over some horizon, say 10001000 steps. The name comes from the slot machine, the “one-armed bandit”, here with kk levers; a doctor choosing among experimental treatments for successive patients faces the same problem.

Definition 2.1 (The k-armed Bandit). At each step t=1,2,…t = 1, 2, \dots the agent selects an action At∈{1,…,k}A_t \in \{1, \dots, k\} and receives a reward RtR_t. The value of action aa is its expected reward,

q∗(a)≐𝔼[Rt∣At=a], q_*(a) \doteq \mathbb{E}[R_t \mid A_t = a], (2.1)

unknown to the agent, which maintains estimates Qt(a)Q_t(a) of it. An action maximizing QtQ_t is greedy; choosing one is exploiting, choosing any other is exploring.

If the q∗(a)q_*(a) were known, the problem would be trivial. Since they are not, exploitation maximizes the expected reward of the next step, while exploration may give more total reward by revealing a better action that can then be exploited many times. A single choice cannot do both, which is the conflict of Section 1.1.2. Whether to explore depends in a complicated way on the estimates, their uncertainties and the remaining horizon; sophisticated methods exist for particular formulations (see Section 2.9), but their guarantees rest on assumptions (stationarity, known reward families, priors) that the full reinforcement learning problem violates. The chapter’s methods aim lower and more robustly: to balance exploration and exploitation at all.

The problem is nonassociative: there is a single situation, so the agent looks for one best action rather than a mapping from situations to actions. Section 2.8 adds situations, and Chapter 3 lets actions change them.

2.2Action-Value Methods

Since q∗(a)q_*(a) is a mean, the natural estimate is the average of the rewards received when aa was chosen,

Qt(a)≐∑i=1t−1Ri 𝟙Ai=a∑i=1t−1𝟙Ai=a, Q_t(a) \doteq \frac{\sum_{i=1}^{t-1} R_i \,\mathbb{1}_{A_i = a}}{\sum_{i=1}^{t-1} \mathbb{1}_{A_i = a}}, (2.2)

with a default value (say 00) when the denominator Nt(a)N_t(a) is zero. By the law of large numbers, Qt(a)→q∗(a)Q_t(a) \to q_*(a) whenever Nt(a)→∞N_t(a) \to \infty. Methods that estimate action values and select actions from the estimates are action-value methods. The simplest selection rule is greedy, At≐argmax⁡aQt(a)A_t \doteq \operatorname{argmax}_a Q_t(a) with ties broken at random; it never samples an action that currently looks inferior, and so it may never discover that it is not. The simplest repair is to behave greedily with probability 1−ε1 - \varepsilon and, with probability ε\varepsilon, to choose uniformly among all kk actions: ε\varepsilon-greedy selection. The greedy action is then chosen with probability 1−ε+ε/k1 - \varepsilon + \varepsilon/k, and every action infinitely often, so every estimate converges to its true value.

Proposition 2.2 (Long-Run Performance of ε-Greedy). With sample-average estimates and a fixed ε>0\varepsilon > 0, the probability of selecting an optimal action converges to 1−ε+ε/k1 - \varepsilon + \varepsilon/k (assuming a unique optimum), and the expected reward per step converges to

(1−ε)max⁡aq∗(a)+εk∑aq∗(a). (1 - \varepsilon)\max_a q_*(a) + \frac{\varepsilon}{k}\sum_a q_*(a). (2.3)

Proof. For each action aa, the events “step tt explores and picks aa” are independent, each of probability ε/k\varepsilon/k, so by the second Borel–Cantelli lemma infinitely many of them occur: every Nt(a)→∞N_t(a) \to \infty almost surely and every Qt(a)→q∗(a)Q_t(a) \to q_*(a). Hence the greedy action is eventually the optimal one, and from then on the selection probabilities are 1−ε+ε/k1 - \varepsilon + \varepsilon/k for it and ε/k\varepsilon/k for each other action. Averaging q∗q_* under these probabilities gives (2.3). □

Sutton and Barto’s 10-armed testbed draws 20002000 bandit problems with q∗(a)∼𝒩(0,1)q_*(a) \sim \mathcal{N}(0, 1) independently and rewards Rt∼𝒩(q∗(At),1)R_t \sim \mathcal{N}(q_*(A_t), 1), and averages the learning curves of each method over them. On it the greedy method improves fastest at first, then levels off near reward 11 per step: in about two thirds of the problems its first samples of the optimal action were disappointing and it never returned. The ε\varepsilon-greedy methods keep improving. The proposition predicts their limits: averaged over problems, max⁡aq∗(a)\max_a q_*(a) is the expected maximum of ten standard normals, and ∑aq∗(a)\sum_a q_*(a) has mean zero.

The best possible reward per step on the testbed, 𝔼[max⁡aq∗(a)]=∫x⋅10 ϕ(x)Φ(x)9 dx\mathbb{E}[\max_a q_*(a)] = \int x \cdot 10\,\phi(x)\Phi(x)^9\,dx, followed by the long-run reward and probability of the optimal action for ε=0.1\varepsilon = 0.1 and ε=0.01\varepsilon = 0.01.
const bestTestbed = await wl`NIntegrate[x 10 PDF[NormalDistribution[], x] CDF[NormalDistribution[], x]^9, {x, -Infinity, Infinity}]`
await show`{${bestTestbed}, Table[{(1 - e) ${bestTestbed}, 1 - e + e/10}, {e, {1/10, 1/100}}]}`
{1.53875,(1.38488911001.523379911000)} \left\{1.53875,\left( \begin{array}{cc} 1.38488 & \frac{91}{100} \\ 1.52337 & \frac{991}{1000} \\ \end{array} \right)\right\}

So ε=0.1\varepsilon = 0.1 never selects the optimal action more than 91%91\% of the time and earns at most about 1.381.38 per step, while ε=0.01\varepsilon = 0.01 eventually reaches 99.1%99.1\% and 1.521.52, but takes roughly ten times longer to get there. The advantage of exploration depends on the task: noisier rewards call for more of it; deterministic rewards in a stationary problem call for almost none. But nonstationarity, the normal condition in reinforcement learning (where the policy itself changes the values being estimated), always calls for some.

2.3Incremental Implementation

Averages need not be computed from stored rewards. Focus on one action, let RiR_i be the reward after its ii-th selection and QnQ_n the average of the first n−1n - 1 rewards. Then

Qn+1=1n∑i=1nRi=1n(Rn+(n−1)Qn)=Qn+1n[Rn−Qn], Q_{n+1} = \frac{1}{n}\sum_{i=1}^n R_i = \frac{1}{n}\bigl(R_n + (n-1)Q_n\bigr) = Q_n + \frac{1}{n}\bigl[R_n - Q_n\bigr], (2.4)

valid even for n=1n = 1, where it gives Q2=R1Q_2 = R_1 whatever Q1Q_1 was. Memory and time per step are constant. The update has the shape that recurs throughout the book,

NewEstimate←OldEstimate+StepSize [Target−OldEstimate], \textit{NewEstimate} \leftarrow \textit{OldEstimate} + \textit{StepSize}\,\bigl[\textit{Target} - \textit{OldEstimate}\bigr], (2.5)

in which the bracket is an error and the estimate takes a step toward a target that indicates, perhaps noisily, a desirable direction. Here the target is the reward and the step size is 1/n1/n; in general we write α\alpha or αt(a)\alpha_t(a). In later chapters the target becomes a return (Monte Carlo), or a reward plus a discounted value estimate (TD), and the error becomes the TD error (6.2).

Algorithm 2.3 (A Simple Bandit Algorithm). Parameters: ε∈[0,1]\varepsilon \in [0, 1]. Initialization: for a=1,…,ka = 1, \dots, k: Q(a)←0Q(a) \leftarrow 0, N(a)←0N(a) \leftarrow 0.

Loop forever:

  1. A←argmax⁡aQ(a)A \leftarrow \operatorname{argmax}_a Q(a) with probability 1−ε1 - \varepsilon (ties broken at random), otherwise a uniformly random action.
  2. R←bandit(A)R \leftarrow \text{bandit}(A).
  3. N(A)←N(A)+1N(A) \leftarrow N(A) + 1.
  4. Q(A)←Q(A)+1N(A)[R−Q(A)]Q(A) \leftarrow Q(A) + \frac{1}{N(A)}\bigl[R - Q(A)\bigr].

2.4Constant Step Sizes and Nonstationary Problems

Sample averages weigh every reward equally, which is right when the reward distributions never change and wrong when they drift: a reward from long ago says little about the present. The standard remedy is a constant step size α∈(0,1]\alpha \in (0, 1],

Qn+1≐Qn+α[Rn−Qn]. Q_{n+1} \doteq Q_n + \alpha\bigl[R_n - Q_n\bigr]. (2.6)

Proposition 2.4 (Exponential Recency-Weighted Average). The constant-α\alpha estimate is a weighted average of the initial estimate and the past rewards,

Qn+1=(1−α)nQ1+∑i=1nα(1−α)n−iRi, Q_{n+1} = (1-\alpha)^n Q_1 + \sum_{i=1}^n \alpha(1-\alpha)^{n-i}R_i, (2.7)

with nonnegative weights summing to one. The weight of RiR_i decays geometrically with its age n−in - i.

Proof. Write (2.6) as Qn+1=αRn+(1−α)QnQ_{n+1} = \alpha R_n + (1-\alpha)Q_n and substitute the same expression for QnQ_n, then Qn−1Q_{n-1}, down to Q1Q_1; induction on nn gives (2.7). For α∈(0,1]\alpha \in (0, 1] the weights are nonnegative (with the convention 00=10^0 = 1, α=1\alpha = 1 puts all the weight on RnR_n). Their sum telescopes: with β=1−α\beta = 1 - \alpha,

βn+∑i=1n(1−β)βn−i=βn+∑j=0n−1(βj−βj+1)=βn+1−βn=1. \beta^n + \sum_{i=1}^n (1 - \beta)\beta^{n-i} = \beta^n + \sum_{j=0}^{n-1}\bigl(\beta^j - \beta^{j+1}\bigr) = \beta^n + 1 - \beta^n = 1.

□

The estimate is therefore called an exponential recency-weighted average; the same weights describe the tic-tac-toe update of Section 1.4.4. What does forgetting cost when the problem is in fact stationary? Suppose the rewards of the action are i.i.d. with mean qq and variance σ2\sigma^2.

Proposition 2.5 (Bias and Variance of the Constant-α Estimate). For i.i.d. rewards with mean qq and variance σ2\sigma^2, and a deterministic Q1Q_1,

𝔼[Qn+1]=q+(1−α)n(Q1−q),Var⁡[Qn+1]=α2−α(1−(1−α)2n)σ2  →n→∞  α σ22−α. \begin{aligned} \mathbb{E}[Q_{n+1}] &= q + (1-\alpha)^n(Q_1 - q), \\ \operatorname{Var}[Q_{n+1}] &= \frac{\alpha}{2 - \alpha}\bigl(1 - (1-\alpha)^{2n}\bigr)\sigma^2 \;\xrightarrow[n \to \infty]{}\; \frac{\alpha\,\sigma^2}{2 - \alpha}. \end{aligned} (2.8)

The sample average, by contrast, is unbiased from n=1n = 1 on, with variance σ2/n→0\sigma^2/n \to 0.

The proof is linearity of expectation and independence applied to (2.7); we let the kernel do the sums.

2.4.1In Wolfram Language

The weights of (2.7) sum to one for every nn and every α\alpha, symbolically.
await show`Simplify[(1 - \[Alpha])^n + Sum[\[Alpha] (1 - \[Alpha])^(n - i), {i, 1, n}]]`
(1−α)n+∑i=1nα(1−α)n−i=1 (1-\alpha)^n + \sum_{i=1}^n \alpha(1-\alpha)^{n-i} = 1 Mean and variance of Qn+1Q_{n+1}: the weights times qq plus (1−α)nQ1(1-\alpha)^n Q_1, and the squared weights times σ2\sigma^2.
const meanVar = await show`FullSimplify[{(1 - \[Alpha])^n Subscript[Q, 1] + Sum[\[Alpha] (1 - \[Alpha])^(n - i) q, {i, 1, n}], Sum[\[Alpha]^2 (1 - \[Alpha])^(2 (n - i)) \[Sigma]^2, {i, 1, n}]}]`
(𝔼[Qn+1], Var⁡[Qn+1])={q+(1−α)n(−q+Q1),(−1+(−1+α)2n)ασ2−2+α} \begin{aligned} &\bigl(\mathbb{E}[Q_{n+1}],\ \operatorname{Var}[Q_{n+1}]\bigr) \\ &= \left\{q+(1-\alpha )^n \left(-q+Q_1\right),\frac{\left(-1+(-1+\alpha )^{2 n}\right) \alpha \sigma ^2}{-2+\alpha }\right\} \end{aligned} As n→∞n \to \infty the bias vanishes but the variance does not: it settles at ασ2/(2−α)\alpha\sigma^2/(2-\alpha).
await show`Limit[${meanVar}, n -> Infinity, Assumptions -> 0 < \[Alpha] < 1]`
lim⁡n→∞(𝔼[Qn+1], Var⁡[Qn+1])={q,−ασ2−2+α} \lim_{n\to\infty}\bigl(\mathbb{E}[Q_{n+1}],\ \operatorname{Var}[Q_{n+1}]\bigr) = \left\{q,-\frac{\alpha \sigma ^2}{-2+\alpha }\right\}

The constant-α\alpha estimate never converges: it keeps fluctuating around qq with a standard deviation of about σα/2\sigma\sqrt{\alpha/2}. That residual noise is the price of being able to track a value that moves, and in reinforcement learning, where even a stationary task looks nonstationary to a learner whose policy keeps changing, the price is usually worth paying. Figure 2.1 shows the trade-off.

2.4.2Step-Size Conditions

Between 1/n1/n and a constant lie many step-size sequences αn\alpha_n (indexed by the number of times the action has been selected). The classical result of stochastic approximation (Theorem A.7) guarantees convergence with probability one if

∑n=1∞αn=∞and∑n=1∞αn2<∞. \sum_{n=1}^\infty \alpha_n = \infty \qquad\text{and}\qquad \sum_{n=1}^\infty \alpha_n^2 < \infty. (2.9)

The first condition makes the steps large enough to overcome any initial condition and any run of bad luck; the second makes them eventually small enough to average the noise away.Herbert Robbins and Sutton Monro. A Stochastic Approximation Method. The Annals of Mathematical Statistics, 22(3):400–407, Institute of Mathematical Statistics, 1951. doi: 10.1214/aoms/1177729586 For the family αn=n−p\alpha_n = n^{-p} the kernel decides when each series converges:

The two series of (2.9) for αn=n−p\alpha_n = n^{-p}: the first must diverge (p≤1p \le 1), the second converge (p>1/2p > 1/2).
await show`Assuming[p \[Element] Reals, {SumConvergence[n^-p, n], SumConvergence[n^(-2 p), n]}]`
(∑nn−p<∞, ∑nn−2p<∞)  ⟺  {p>1,2p>1} \Bigl(\textstyle\sum_n n^{-p} < \infty,\ \sum_n n^{-2p} < \infty\Bigr) \iff \{p>1,2 p>1\}

So the conditions hold exactly for 1/2<p≤11/2 < p \le 1, which includes the sample average p=1p = 1, and fail for a constant step size (p=0p = 0), whose squares do not sum. The theory therefore says that constant-α\alpha estimates never converge, and the previous subsection says by how much. In practice, sequences satisfying (2.9) often converge slowly or need tuning, and are rarely used in applications.

2.5Initial Values: Bias and Optimism

All these methods depend on the initial estimates Q1(a)Q_1(a): in statistical language they are biased by them. For sample averages the bias disappears once the action has been selected; for constant α\alpha it decays as (1−α)n(1-\alpha)^n by (2.8) but never vanishes. The bias is a parameter to set (if only to zero), and also a way to inject prior knowledge about the level of rewards.

It is also a cheap way to explore. Set every Q1(a)=+5Q_1(a) = +5 on the testbed, where the q∗(a)q_*(a) are around 00, and act greedily. Whichever action is tried first disappoints, its estimate drops below the others, and the learner moves on; all actions get tried several times before the estimates settle. This trick of optimistic initial values makes a purely greedy method explore systematically at the start, and on the stationary testbed it eventually beats ε\varepsilon-greedy. But its drive to explore is temporary: the beginning of time occurs only once, and if the task changes later, nothing renews the exploration. The same objection applies, as Sutton and Barto note, to sample averages, which treat the beginning of time as special by weighing all later rewards equally.

Can we keep the recency weighting of a constant step size without its initial bias? Sutton and Barto’s Exercise 2.7 gives a neat construction. Process the nn-th reward with the step size

βn≐αo¯n,o¯n≐o¯n−1+α(1−o¯n−1),o¯0≐0, \beta_n \doteq \frac{\alpha}{\bar o_n}, \qquad \bar o_n \doteq \bar o_{n-1} + \alpha(1 - \bar o_{n-1}), \quad \bar o_0 \doteq 0, (2.10)

where o¯n\bar o_n is a “trace of one”: the constant-α\alpha average of a sequence of ones, started at zero.

Proposition 2.6 (Unbiased Constant-Step-Size Trick). With the step sizes (2.10), o¯n=1−(1−α)n\bar o_n = 1 - (1-\alpha)^n, and the estimate Qn+1Q_{n+1} does not depend on Q1Q_1:

Qn+1=∑i=1nα(1−α)n−iRi1−(1−α)n, Q_{n+1} = \frac{\sum_{i=1}^n \alpha(1-\alpha)^{n-i}R_i}{1 - (1-\alpha)^n}, (2.11)

an exponential recency-weighted average with weights renormalized to sum to one. Hence 𝔼[Qn+1]=q\mathbb{E}[Q_{n+1}] = q for i.i.d. rewards of mean qq, and βn→α\beta_n \to \alpha.

Proof. The recursion for o¯n\bar o_n is (2.6) applied to targets equal to 11 from o¯0=0\bar o_0 = 0, so (2.7) gives o¯n=∑i=1nα(1−α)n−i=1−(1−α)n\bar o_n = \sum_{i=1}^n \alpha(1-\alpha)^{n-i} = 1 - (1-\alpha)^n. In particular o¯1=α\bar o_1 = \alpha and β1=1\beta_1 = 1: the first update sets Q2=R1Q_2 = R_1 and erases Q1Q_1. Now let Sn=o¯nQn+1S_n = \bar o_n Q_{n+1}. From Qn+1=Qn+βn(Rn−Qn)Q_{n+1} = Q_n + \beta_n(R_n - Q_n) and o¯nβn=α\bar o_n \beta_n = \alpha,

Sn=o¯nQn+α(Rn−Qn)=(o¯n−α)Qn+αRn=(1−α)o¯n−1Qn+αRn=(1−α)Sn−1+αRn, \begin{aligned} S_n &= \bar o_n Q_n + \alpha(R_n - Q_n) = (\bar o_n - \alpha)Q_n + \alpha R_n \\ &= (1-\alpha)\bar o_{n-1}Q_n + \alpha R_n = (1-\alpha)S_{n-1} + \alpha R_n, \end{aligned}

using o¯n−α=(1−α)o¯n−1\bar o_n - \alpha = (1-\alpha)\bar o_{n-1}. With S0=o¯0Q1=0S_0 = \bar o_0 Q_1 = 0 this unrolls to Sn=∑i=1nα(1−α)n−iRiS_n = \sum_{i=1}^n \alpha(1-\alpha)^{n-i}R_i, which is (2.11). The weights sum to o¯n/o¯n=1\bar o_n / \bar o_n = 1, giving unbiasedness, and o¯n→1\bar o_n \to 1 gives βn→α\beta_n \to \alpha. □

The trick behaves like a sample average at first (β1=1\beta_1 = 1, β2=1/(2−α)≈1/2\beta_2 = 1/(2-\alpha) \approx 1/2) and like a constant step size later, which is exactly what one wants on a nonstationary problem whose initial values are unknown.

2.5.1In Wolfram Language

Solve the trace-of-one recursion exactly.
await show`RSolve[{o[n] == o[n - 1] + \[Alpha] (1 - o[n - 1]), o[0] == 0}, o[n], n]`
{{o(n)→1−(1−α)n}} \left\{\left\{o(n)\to 1-(1-\alpha )^n\right\}\right\} Run three updates with βn=α/(1−(1−α)n)\beta_n = \alpha / (1 - (1-\alpha)^n) from a symbolic Q1Q_1: its coefficient is zero, and the rewards carry the renormalized weights of (2.11).
await show`Collect[Simplify[Fold[Function[{qq, nr}, qq + \[Alpha]/(1 - (1 - \[Alpha])^nr[[1]]) (nr[[2]] - qq)], Subscript[Q, 1], Table[{i, Subscript[R, i]}, {i, 3}]]], {Subscript[Q, 1], Subscript[R, 1], Subscript[R, 2], Subscript[R, 3]}, Factor]`
Q4=(−1+α)2R13−3α+α2−(−1+α)R23−3α+α2+R33−3α+α2 Q_4 = \frac{(-1+\alpha )^2 R_1}{3-3 \alpha +\alpha ^2}-\frac{(-1+\alpha ) R_2}{3-3 \alpha +\alpha ^2}+\frac{R_3}{3-3 \alpha +\alpha ^2} Variance of the unbiased estimate for i.i.d. rewards: the sum of its squared weights times σ2\sigma^2. It equals σ2\sigma^2 at n=1n = 1 and tends to the constant-α\alpha floor ασ2/(2−α)\alpha\sigma^2/(2-\alpha).
const varUnbiased = await show`FullSimplify[Sum[(\[Alpha] (1 - \[Alpha])^(n - i)/(1 - (1 - \[Alpha])^n))^2 \[Sigma]^2, {i, 1, n}], Assumptions -> 0 < \[Alpha] < 1 && n >= 1]`
Var⁡[Qn+1]=(−1+(−1+α)2n)ασ2(−1+(1−α)n)2(−2+α) \operatorname{Var}[Q_{n+1}] = \frac{\left(-1+(-1+\alpha )^{2 n}\right) \alpha \sigma ^2}{\left(-1+(1-\alpha )^n\right)^2 (-2+\alpha )}
Figure 2.1: Exact mean squared error 𝔼[(Qn+1−q)2]\mathbb{E}[(Q_{n+1} - q)^2] of four estimators of a stationary action value, for rewards of variance σ2=1\sigma^2 = 1 and an initial estimate Q1=q+2Q_1 = q + 2. The sample average (black) and the unbiased trick of Proposition 2.6 (orange, α=0.1\alpha = 0.1) are free of the initial bias; the constant step sizes (blue, α=0.1\alpha = 0.1; gray, α=0.3\alpha = 0.3) pay for it early, and every recency-weighted estimate levels off at the variance floor ασ2/(2−α)\alpha\sigma^2/(2-\alpha), the price of being able to track change.Log-log plot of mean squared error against the number of rewards n from 1 to 300. The sample average falls as 1/n. Constant step size 0.1 with initial estimate 2 above the truth starts high, falls, and flattens at about 0.053. Constant step size 0.3 falls faster and flattens higher, near 0.18. The unbiased constant-step trick with alpha 0.1 starts at 1, follows the sample average for a while, and flattens at the same floor as constant step 0.1.

2.6Upper-Confidence-Bound Action Selection

ε\varepsilon-greedy explores indiscriminately: a random action is as likely to be one known to be terrible as one that is nearly greedy and barely tried. It would be better to explore according to each action’s potential to be optimal, which depends both on how high its estimate is and on how uncertain. The upper-confidence-bound rule selects

At≐argmax⁡a[Qt(a)+cln⁡tNt(a) ], A_t \doteq \operatorname{argmax}_a \left[Q_t(a) + c\sqrt{\frac{\ln t}{N_t(a)}}\,\right], (2.12)

with c>0c > 0 and any action with Nt(a)=0N_t(a) = 0 treated as maximizing. The square root measures the uncertainty of Qt(a)Q_t(a), so the bracket is an optimistic but plausible value for the action: optimism in the face of uncertainty. Choosing aa increases Nt(a)N_t(a) and shrinks its bonus; not choosing it lets ln⁡t\ln t grow, slowly but without bound, so every action is eventually retried, and actions that look poor or are well known are retried ever more rarely.

Where does the formula come from? Suppose rewards lie in [0,1][0, 1]. Hoeffding’s inequality bounds the probability that the mean of NN independent rewards underestimates q∗(a)q_*(a) by more than uu: Pr⁡{q∗(a)≥Q+u}≤e−2Nu2\Pr\{q_*(a) \ge Q + u\} \le e^{-2Nu^2}. Choose uu so that this failure probability shrinks with time like t−4t^{-4}, small enough that summed over all steps and actions it stays bounded. Then the upper confidence bound is Q+uQ + u with u=2ln⁡t/Nu = \sqrt{2\ln t/N}, that is (2.12) with c=2c = \sqrt 2: the UCB1 rule of Auer, Cesa-Bianchi and Fischer.Peter Auer, Nicolò Cesa-Bianchi, and Paul Fischer. Finite-time Analysis of the Multiarmed Bandit Problem. Machine Learning, 47(2–3):235–256, 2002. doi: 10.1023/A:1013689704352 The same calculation tells how often a suboptimal action can still be chosen. If Δa=max⁡bq∗(b)−q∗(a)\Delta_a = \max_b q_*(b) - q_*(a) is its gap, then once its bonus drops below Δa/2\Delta_a/2 and both confidence intervals hold, its upper bound falls below the optimal action’s, so it can be chosen only while Nt(a)N_t(a) is below the threshold where the bonus equals Δa/2\Delta_a/2.

Solve the Hoeffding tail e−2Nu2=t−4e^{-2Nu^2} = t^{-4} for the confidence width uu, and the condition cln⁡t/N=Δ/2c\sqrt{\ln t/N} = \Delta/2 for the number of pulls after which a gap-Δ\Delta arm is no longer chosen.
await show`{u /. First[Solve[Exp[-2 n u^2] == t^-4 && u > 0, u, Assumptions -> n > 0 && t > 1]], n /. First[Solve[c^2 Log[t]/n == \[CapitalDelta]^2/4, n]] /. c -> Sqrt[2]}`
(u, NΔ)={2log⁡(t)n,8log⁡(t)Δ2} \bigl(u,\ N_{\Delta}\bigr) = \left\{\sqrt{2} \sqrt{\frac{\log (t)}{n}},\frac{8 \log (t)}{\Delta ^2}\right\}

A suboptimal action is thus selected about 8ln⁡t/Δa28\ln t/\Delta_a^2 times up to time tt, and each selection costs Δa\Delta_a in expected reward: the loss grows only logarithmically, against the linear loss εΔat/k\varepsilon\Delta_a t/k of ε\varepsilon-greedy. Section 2.9 turns this into a theorem and shows that logarithmic growth is the best possible.

Algorithm 2.7 (UCB Action Selection). Parameter: c>0c > 0 (UCB1: c=2c = \sqrt 2 for rewards in [0,1][0, 1]). Initialization: Q(a)←0Q(a) \leftarrow 0, N(a)←0N(a) \leftarrow 0 for all aa.

Loop for t=1,2,…t = 1, 2, \dots:

  1. If some action has N(a)=0N(a) = 0, let AA be such an action; otherwise A←argmax⁡a[Q(a)+cln⁡t/N(a)]A \leftarrow \operatorname{argmax}_a \bigl[Q(a) + c\sqrt{\ln t / N(a)}\bigr].
  2. R←bandit(A)R \leftarrow \text{bandit}(A); N(A)←N(A)+1N(A) \leftarrow N(A) + 1; Q(A)←Q(A)+1N(A)[R−Q(A)]Q(A) \leftarrow Q(A) + \frac{1}{N(A)}\bigl[R - Q(A)\bigr].

On the testbed UCB with c=2c = 2 beats ε\varepsilon-greedy after the first kk steps. It is harder to extend beyond bandits: nonstationarity requires more complex machinery than the constant step sizes of Section 2.4, and with large state spaces and function approximation the counts Nt(a)N_t(a) lose their meaning. The idea, an exploration bonus for what is uncertain, does survive: it reappears in the tree policy of Monte Carlo tree search (Section 8.9) and in count-based exploration bonuses for deep reinforcement learning.

2.7Gradient Bandit Algorithms

Instead of estimating values, an agent can learn a numerical preference Ht(a)H_t(a) for each action and select actions by the soft-max (Gibbs, Boltzmann) distribution

πt(a)≐Pr⁡{At=a}≐eHt(a)∑b=1keHt(b). \pi_t(a) \doteq \Pr\{A_t = a\} \doteq \frac{e^{H_t(a)}}{\sum_{b=1}^k e^{H_t(b)}}. (2.13)

Only differences of preferences matter: adding the same constant to all of them leaves πt\pi_t unchanged. Preferences have no interpretation as rewards. The learning rule is

Ht+1(a)≐Ht(a)+α(Rt−R¯t)(𝟙a=At−πt(a))for all a, H_{t+1}(a) \doteq H_t(a) + \alpha\bigl(R_t - \bar R_t\bigr)\bigl(\mathbb{1}_{a = A_t} - \pi_t(a)\bigr) \qquad \text{for all } a, (2.14)

where R¯t\bar R_t, the average of the rewards so far, serves as a baseline. If the reward beats the baseline, the chosen action’s preference rises and all others fall, in proportion to their probabilities; if it falls short, the reverse.

Algorithm 2.8 (Gradient Bandit). Parameters: step size α>0\alpha > 0. Initialization: H(a)←0H(a) \leftarrow 0 for all aa; R¯←0\bar R \leftarrow 0; t←0t \leftarrow 0.

Loop forever:

  1. Compute π(a)=eH(a)/∑beH(b)\pi(a) = e^{H(a)}/\sum_b e^{H(b)} and sample A∼πA \sim \pi.
  2. R←bandit(A)R \leftarrow \text{bandit}(A); t←t+1t \leftarrow t + 1; R¯←R¯+1t(R−R¯)\bar R \leftarrow \bar R + \frac{1}{t}(R - \bar R) (or a constant step size for nonstationary problems).
  3. For all aa: H(a)←H(a)+α(R−R¯)(𝟙a=A−π(a))H(a) \leftarrow H(a) + \alpha(R - \bar R)\bigl(\mathbb{1}_{a = A} - \pi(a)\bigr).

The rule looks ad hoc; it is in fact stochastic gradient ascent on the expected reward. Since πt\pi_t depends on all the preferences, gradient ascent on 𝔼[Rt]=∑xπt(x)q∗(x)\mathbb{E}[R_t] = \sum_x \pi_t(x)q_*(x) would update

Ht+1(a)=Ht(a)+α∂ 𝔼[Rt]∂Ht(a), H_{t+1}(a) = H_t(a) + \alpha\frac{\partial\,\mathbb{E}[R_t]}{\partial H_t(a)}, (2.15)

which is impossible because the q∗(x)q_*(x) are unknown. The theorem says that the update (2.14) equals (2.15) in expectation.

Lemma 2.9 (Soft-max Derivative). For the soft-max (2.13), ∂πt(x)∂Ht(a)=πt(x)(𝟙a=x−πt(a))\dfrac{\partial \pi_t(x)}{\partial H_t(a)} = \pi_t(x)\bigl(\mathbb{1}_{a = x} - \pi_t(a)\bigr). In particular ∑x∂πt(x)/∂Ht(a)=0\sum_x \partial\pi_t(x)/\partial H_t(a) = 0.

Proof. Write Z=∑yeHt(y)Z = \sum_y e^{H_t(y)}, so that ∂Z/∂Ht(a)=eHt(a)\partial Z/\partial H_t(a) = e^{H_t(a)} and ∂eHt(x)/∂Ht(a)=𝟙a=xeHt(x)\partial e^{H_t(x)}/\partial H_t(a) = \mathbb{1}_{a=x}e^{H_t(x)}. By the quotient rule,

∂πt(x)∂Ht(a)=𝟙a=xeHt(x)Z−eHt(x)eHt(a)Z2=𝟙a=xπt(x)−πt(x)πt(a). \frac{\partial \pi_t(x)}{\partial H_t(a)} = \frac{\mathbb{1}_{a=x}e^{H_t(x)}Z - e^{H_t(x)}e^{H_t(a)}}{Z^2} = \mathbb{1}_{a=x}\pi_t(x) - \pi_t(x)\pi_t(a).

Summing over xx gives πt(a)−πt(a)∑xπt(x)=0\pi_t(a) - \pi_t(a)\sum_x\pi_t(x) = 0, as it must, since the probabilities always sum to one. □

Theorem 2.10 (The Gradient Bandit Algorithm Is Stochastic Gradient Ascent). Let BtB_t be any baseline that does not depend on AtA_t (it may depend on the past). Then for every action aa,

𝔼[(Rt−Bt)(𝟙a=At−πt(a)) ∣ Ht]=∂ 𝔼[Rt∣Ht]∂Ht(a), \mathbb{E}\bigl[(R_t - B_t)(\mathbb{1}_{a = A_t} - \pi_t(a)) \,\big|\, H_t\bigr] = \frac{\partial\,\mathbb{E}[R_t \mid H_t]}{\partial H_t(a)}, (2.16)

so the expected update of (2.14) (with Bt=R¯t−1B_t = \bar R_{t-1}, the average of the rewards before step tt) is α\alpha times the gradient of the expected reward.

Proof. Condition throughout on the history up to the choice of AtA_t, which fixes HtH_t, πt\pi_t and BtB_t. Differentiate 𝔼[Rt]=∑xπt(x)q∗(x)\mathbb{E}[R_t] = \sum_x \pi_t(x) q_*(x) and subtract the zero sum of Lemma 2.9 multiplied by BtB_t:

∂ 𝔼[Rt]∂Ht(a)=∑xq∗(x)∂πt(x)∂Ht(a)=∑x(q∗(x)−Bt)∂πt(x)∂Ht(a)=∑xπt(x)(q∗(x)−Bt)(𝟙a=x−πt(a)), \begin{aligned} \frac{\partial\,\mathbb{E}[R_t]}{\partial H_t(a)} &= \sum_x q_*(x)\frac{\partial\pi_t(x)}{\partial H_t(a)} = \sum_x \bigl(q_*(x) - B_t\bigr)\frac{\partial\pi_t(x)}{\partial H_t(a)} \\ &= \sum_x \pi_t(x)\bigl(q_*(x) - B_t\bigr)\bigl(\mathbb{1}_{a=x} - \pi_t(a)\bigr), \end{aligned}

using the lemma in the last step. The right-hand side is an expectation over x=At∼πtx = A_t \sim \pi_t: it equals 𝔼[(q∗(At)−Bt)(𝟙a=At−πt(a))]\mathbb{E}\bigl[(q_*(A_t) - B_t)(\mathbb{1}_{a=A_t} - \pi_t(a))\bigr]. Finally, by the tower property and 𝔼[Rt∣At]=q∗(At)\mathbb{E}[R_t \mid A_t] = q_*(A_t), we may replace q∗(At)q_*(A_t) by RtR_t, since the factor (𝟙a=At−πt(a))(\mathbb{1}_{a=A_t} - \pi_t(a)) and BtB_t are fixed once AtA_t is: this gives (2.16). □

Two remarks sharpen the theorem. First, the baseline is a free choice: it does not change the expected update, because the gradient of a total probability is zero. Sutton and Barto’s rule uses the average R¯t\bar R_t including the current reward, which does depend on AtA_t; but since R¯t=R¯t−1+1t(Rt−R¯t−1)\bar R_t = \bar R_{t-1} + \frac{1}{t}(R_t - \bar R_{t-1}), we have Rt−R¯t=(1−1t)(Rt−R¯t−1)R_t - \bar R_t = (1 - \frac1t)(R_t - \bar R_{t-1}), so their update is the one of the theorem with the step size α(1−1/t)\alpha(1 - 1/t), and it is still exactly stochastic gradient ascent. (The same holds for a constant-step baseline, with factor 1−β1 - \beta.) Second, though it does not affect the mean, the baseline strongly affects the variance of the update, and hence the speed of learning: on a testbed with q∗(a)∼𝒩(4,1)q_*(a) \sim \mathcal{N}(4, 1), dropping the baseline degrades the gradient bandit badly, while with it, shifting all rewards by 44 has no effect at all. Chapter 13 generalizes the theorem to the policy-gradient theorem (Theorem 13.2) and the update to REINFORCE with baseline (Algorithm 13.4); the gradient bandit is REINFORCE for a one-step episode.Ronald J. Williams. Simple Statistical Gradient-Following Algorithms for Connectionist Reinforcement Learning. Machine Learning, 8(3–4):229–256, Springer, 1992. doi: 10.1007/BF00992696

2.7.1In Wolfram Language

We verify the lemma and the theorem for three actions with symbolic preferences, values and baseline, and then ask which baseline minimizes the variance.

The Jacobian of the soft-max minus π(x)(𝟙a=x−π(a))\pi(x)(\mathbb{1}_{a=x} - \pi(a)), for k=3k = 3: identically zero.
const softmax = await wl`Function[h, Exp[h]/Total[Exp[h]]]`
const hVec = await wl`{Subscript[H, 1], Subscript[H, 2], Subscript[H, 3]}`
await show`Simplify[Table[D[${softmax}[${hVec}][[x]], ${hVec}[[a]]] - ${softmax}[${hVec}][[x]] (KroneckerDelta[a, x] - ${softmax}[${hVec}][[a]]), {x, 3}, {a, 3}]]`
(∂π(x)∂H(a)−π(x)(𝟙a=x−π(a)))x,a=(000000000) \Bigl(\frac{\partial \pi(x)}{\partial H(a)} - \pi(x)\bigl(\mathbb{1}_{a=x} - \pi(a)\bigr)\Bigr)_{x,a} = \left( \begin{array}{ccc} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 0 & 0 \\ \end{array} \right) Expected gradient-bandit update minus the exact gradient of ∑xπ(x)q∗(x)\sum_x \pi(x) q_*(x), for each of the three preferences and an arbitrary baseline BB: zero.
const qVec = await wl`{Subscript[q, 1], Subscript[q, 2], Subscript[q, 3]}`
await show`Simplify[Table[Sum[${softmax}[${hVec}][[x]] (${qVec}[[x]] - B) (KroneckerDelta[a, x] - ${softmax}[${hVec}][[a]]), {x, 3}] - D[${softmax}[${hVec}] . ${qVec}, ${hVec}[[a]]], {a, 3}]]`
(𝔼[(R−B)(𝟙a=A−π(a))]−∂ 𝔼[R]∂H(a))a=1,2,3={0,0,0} \Bigl(\mathbb{E}\bigl[(R - B)(\mathbb{1}_{a=A} - \pi(a))\bigr] - \frac{\partial\,\mathbb{E}[R]}{\partial H(a)}\Bigr)_{a=1,2,3} = \{0,0,0\} For k=2k = 2 with π(1)=p\pi(1) = p and noise-free rewards, minimize the second moment of the update of H(1)H(1) over the baseline BB: the optimum weighs each action’s value by the other action’s probability.
await show`Solve[D[p (Subscript[q, 1] - B)^2 (1 - p)^2 + (1 - p) (Subscript[q, 2] - B)^2 p^2, B] == 0, B] // Simplify`
{{B→−((−1+p)q1)+pq2}} \left\{\left\{B\to -\left((-1+p) q_1\right)+p q_2\right\}\right\}

The variance-minimizing baseline for two actions is (1−p)q∗(1)+p q∗(2)(1-p)q_*(1) + p\,q_*(2), not the expected reward p q∗(1)+(1−p)q∗(2)p\,q_*(1) + (1-p)q_*(2): the baseline matters most for the action that is rarely chosen, whose updates are large. The running average R¯t\bar R_t is a simple, good, but not optimal choice; Chapter 13 returns to the question.

2.8Associative Search (Contextual Bandits)

Suppose that at each step you face one of several bandit problems, chosen at random, and that you are told which one (say, the slot machine changes the color of its display) but not its action values. Ignoring the signal, you face a single bandit whose values jump around from step to step, and the methods above will do poorly unless the jumps are slow. Using the signal, you can learn a policy: in red, pull arm 1; in green, arm 2. This is associative search, now usually called the contextual bandit problem: like the full reinforcement learning problem it requires learning a policy, a mapping from situations to actions, but like the bandit each action affects only the immediate reward. When actions may also affect the next situation, we have the full problem of Chapter 3. Thorndike’s Law of Effect, with its bonds between situations and responses, already described associative search.

In the tabular case one simply runs a separate bandit algorithm per context. When contexts are many or continuous they must be generalized over, and the classical solution is to make the expected reward a linear function of a feature vector. The LinUCB algorithm of Li, Chu, Langford and Schapire models 𝔼[Rt∣𝐱t,a]=𝜽a⊤𝐱t,a\mathbb{E}[R_t \mid \mathbf{x}_{t,a}] = \boldsymbol{\theta}_a^\top\mathbf{x}_{t,a}, estimates 𝜽a\boldsymbol{\theta}_a by ridge regression, 𝜽^a=𝐀a−1𝐛a\hat{\boldsymbol{\theta}}_a = \mathbf{A}_a^{-1}\mathbf{b}_a with 𝐀a=𝐈+∑𝐱𝐱⊤\mathbf{A}_a = \mathbf{I} + \sum \mathbf{x}\mathbf{x}^\top and 𝐛a=∑R 𝐱\mathbf{b}_a = \sum R\,\mathbf{x} over the steps on which aa was chosen, and selects argmax⁡a𝜽^a⊤𝐱t,a+c𝐱t,a⊤𝐀a−1𝐱t,a\operatorname{argmax}_a \hat{\boldsymbol{\theta}}_a^\top\mathbf{x}_{t,a} + c\sqrt{\mathbf{x}_{t,a}^\top\mathbf{A}_a^{-1}\mathbf{x}_{t,a}}, the UCB rule with the standard deviation of a linear prediction in place of 1/N1/\sqrt{N}.Lihong Li, Wei Chu, John Langford, and Robert E. Schapire. A Contextual-Bandit Approach to Personalized News Article Recommendation. In Proceedings of the 19th International Conference on World Wide Web (WWW 2010), pages 661–670. ACM, 2010. doi: 10.1145/1772690.1772758Beyond Sutton and Barto (2018). The book mentions contextual bandits only by name. Li et al. (WWW 2010) applied LinUCB to news recommendation on the Yahoo! front page, with more than 33 million logged events, and reported a 12.5%12.5\% click lift over a context-free bandit. Contextual bandits are now a standard tool for recommendation, advertising and adaptive clinical trials; Lattimore and Szepesvári’s book covers their theory.Tor Lattimore and Csaba Szepesvári. Bandit Algorithms. Cambridge University Press, Cambridge, 2020. doi: 10.1017/9781108571401

2.9Beyond the Book: Regret and Optimal Exploration

Sutton and Barto judge bandit methods by learning curves and by a parameter study on the testbed, where UCB comes out best. The bandit literature in statistics and machine learning judges them by regret: the expected reward lost, over TT steps, relative to always playing an optimal action. With q⋆=max⁡aq∗(a)q_\star = \max_a q_*(a), gaps Δa=q⋆−q∗(a)\Delta_a = q_\star - q_*(a) and NT(a)N_T(a) the number of selections of aa in the first TT steps,

ℒT≐Tq⋆−𝔼[∑t=1TRt]=∑aΔa 𝔼[NT(a)], \mathcal{L}_T \doteq T q_\star - \mathbb{E}\Bigl[\sum_{t=1}^T R_t\Bigr] = \sum_a \Delta_a\,\mathbb{E}[N_T(a)], (2.17)

the second form following from 𝔼[Rt∣At]=q∗(At)\mathbb{E}[R_t \mid A_t] = q_*(A_t). Regret decomposes into how often each suboptimal arm is tried, times how much each trial costs. Any fixed-ε\varepsilon method has linear regret; a greedy method too, with positive probability of locking onto a wrong arm.Beyond Sutton and Barto (2018). The book’s bibliographical remarks mention Lai and Robbins (1985), UCB1 (Auer et al., 2002) and Thompson sampling, but do not develop the theory of regret. This section summarizes its main results; for a full treatment see Lattimore and Szepesvári (2020) and, for Thompson sampling, the tutorial of Russo et al. (2018).Tor Lattimore and Csaba Szepesvári. Bandit Algorithms. Cambridge University Press, Cambridge, 2020. doi: 10.1017/9781108571401; and Daniel J. Russo, Benjamin Van Roy, Abbas Kazerouni, Ian Osband, and Zheng Wen. A Tutorial on Thompson Sampling. Foundations and Trends in Machine Learning, 11(1):1–96, 2018. doi: 10.1561/2200000070

2.9.1The Lai–Robbins Lower Bound

How small can regret be? Lai and Robbins answered for rewards from a one-parameter family (Bernoulli, for instance).Tze Leung Lai and Herbert Robbins. Asymptotically Efficient Adaptive Allocation Rules. Advances in Applied Mathematics, 6(1):4–22, 1985. doi: 10.1016/0196-8858(85)90002-8

Theorem 2.11 (Lai–Robbins Lower Bound). Let the reward distribution of each arm belong to a regular one-parameter family, and let a policy be consistent: ℒT=o(Tp)\mathcal{L}_T = o(T^p) for every p>0p > 0 and every bandit in the family. Then for every suboptimal arm aa,

lim inf⁡T→∞𝔼[NT(a)]ln⁡T≥1KL(q∗(a),q⋆), \liminf_{T \to \infty}\frac{\mathbb{E}[N_T(a)]}{\ln T} \ge \frac{1}{\mathrm{KL}\bigl(q_*(a), q_\star\bigr)}, (2.18)

and hence, by (2.17),

lim inf⁡T→∞ℒTln⁡T≥∑a:Δa>0ΔaKL(q∗(a),q⋆), \liminf_{T \to \infty}\frac{\mathcal{L}_T}{\ln T} \ge \sum_{a : \Delta_a > 0}\frac{\Delta_a}{\mathrm{KL}\bigl(q_*(a), q_\star\bigr)},

where KL(μ,μ′)\mathrm{KL}(\mu, \mu') is the Kullback–Leibler divergence between the members of the family with means μ\mu and μ′\mu'.

The intuition: to be sure that arm aa is not optimal, a policy must collect enough samples to distinguish its reward distribution from one with mean just above q⋆q_\star, and the number of samples needed to tell two distributions apart with error probability 1/T1/T is about ln⁡T\ln T divided by their KL divergence. Logarithmic regret is thus unavoidable, and the constant is set by information, not by the gap alone. For Bernoulli arms, KL(μ,μ′)=μln⁡μμ′+(1−μ)ln⁡1−μ1−μ′\mathrm{KL}(\mu, \mu') = \mu\ln\frac{\mu}{\mu'} + (1-\mu)\ln\frac{1-\mu}{1-\mu'}; for small gaps it is quadratic in the gap.

The Bernoulli KL divergence between means pp and p+Δp + \Delta, to second order in Δ\Delta: the Lai–Robbins constant for a nearly optimal arm is about 2p(1−p)/Δ2p(1-p)/\Delta.
await show`SeriesCoefficient[p Log[p/(p + \[CapitalDelta])] + (1 - p) Log[(1 - p)/(1 - p - \[CapitalDelta])], {\[CapitalDelta], 0, 2}]`
[Δ2] KL(p,p+Δ)=12p−2p2 [\Delta^2]\ \mathrm{KL}(p, p + \Delta) = \frac{1}{2 p-2 p^2}

Since KL≥2Δ2\mathrm{KL} \ge 2\Delta^2 (Pinsker’s inequality), the bound is at most ∑a1/(2Δa)\sum_a 1/(2\Delta_a) per unit of ln⁡T\ln T, attained when arms have means near 1/21/2; arms with means near 00 or 11 have smaller variance, are easier to distinguish, and cost less.

2.9.2UCB1 and KL-UCB

The heuristic count of Section 2.6 is made rigorous by the first finite-time analysis of an index policy.

Theorem 2.12 (Auer, Cesa-Bianchi and Fischer (2002)). For kk arms with rewards in [0,1][0, 1], UCB1 (Algorithm 2.7 with c=2c = \sqrt 2) has, for every TT,

ℒT≤8∑a:Δa>0ln⁡TΔa+(1+π23)∑aΔa. \mathcal{L}_T \le 8\sum_{a : \Delta_a > 0}\frac{\ln T}{\Delta_a} + \Bigl(1 + \frac{\pi^2}{3}\Bigr)\sum_a \Delta_a. (2.19)

The bound has the optimal ln⁡T\ln T rate, but its constant 8/Δa8/\Delta_a exceeds the Lai–Robbins constant Δa/KL≤1/(2Δa)\Delta_a/\mathrm{KL} \le 1/(2\Delta_a) by a factor of at least 1616, because Hoeffding’s inequality uses only the range of the rewards, not their actual distribution.Peter Auer, Nicolò Cesa-Bianchi, and Paul Fischer. Finite-time Analysis of the Multiarmed Bandit Problem. Machine Learning, 47(2–3):235–256, 2002. doi: 10.1023/A:1013689704352 KL-UCB closes the gap by building the confidence bound from the divergence itself: it selects the arm maximizing

Ut(a)=max⁡{μ∈[0,1]:Nt(a) KL(Qt(a),μ)≤ln⁡t+cln⁡ln⁡t}, U_t(a) = \max\bigl\{\mu \in [0, 1] : N_t(a)\,\mathrm{KL}\bigl(Q_t(a), \mu\bigr) \le \ln t + c\ln\ln t\bigr\}, (2.20)

the largest mean still statistically compatible with the data. Garivier and Cappé proved that for Bernoulli rewards KL-UCB attains the Lai–Robbins constant, so it is asymptotically optimal, and that for general bounded rewards its regret bound is uniformly better than UCB1’s.Aurélien Garivier and Olivier Cappé. The KL-UCB Algorithm for Bounded Stochastic Bandits and Beyond. In Proceedings of the 24th Annual Conference on Learning Theory (COLT 2011), volume 19 of Proceedings of Machine Learning Research, pages 359–376, 2011Beyond Sutton and Barto (2018). KL-UCB (COLT 2011) is not in the book. Its analysis uses c=3c = 3; the authors recommend c=0c = 0 in practice. Solving (2.20) needs a one-dimensional root search per arm, since the KL divergence is increasing in μ\mu above Qt(a)Q_t(a).

2.9.3Thompson Sampling

The oldest bandit algorithm is Bayesian. Thompson (1933), thinking of clinical trials, asked for the probability that one unknown success rate exceeds another given the evidence, and proposed to allocate each new patient to a treatment with that probability.William R. Thompson. On the Likelihood That One Unknown Probability Exceeds Another in View of the Evidence of Two Samples. Biometrika, 25(3–4):285–294, 1933. doi: 10.1093/biomet/25.3-4.285 Thompson sampling (or posterior sampling) does exactly this: sample one value from the posterior of each arm and play the arm whose sample is largest. Each arm is then chosen with its posterior probability of being optimal. For Bernoulli rewards with Beta⁡(1,1)\operatorname{Beta}(1, 1) priors, the posterior of an arm with ss successes and ff failures is Beta⁡(1+s,1+f)\operatorname{Beta}(1 + s, 1 + f), so the algorithm needs two counters per arm.

Algorithm 2.13 (Thompson Sampling for Bernoulli Bandits). Initialization: S(a)←0S(a) \leftarrow 0, F(a)←0F(a) \leftarrow 0 for all aa.

Loop forever:

  1. For each aa, sample θa∼Beta⁡(1+S(a), 1+F(a))\theta_a \sim \operatorname{Beta}\bigl(1 + S(a),\, 1 + F(a)\bigr).
  2. A←argmax⁡aθaA \leftarrow \operatorname{argmax}_a \theta_a; R←bandit(A)∈{0,1}R \leftarrow \text{bandit}(A) \in \{0, 1\}.
  3. If R=1R = 1 then S(A)←S(A)+1S(A) \leftarrow S(A) + 1, else F(A)←F(A)+1F(A) \leftarrow F(A) + 1.

Thompson’s own question can be answered exactly. With uniform priors, an arm with two successes and one failure and an arm with one success and two failures have posteriors Beta⁡(3,2)\operatorname{Beta}(3, 2) and Beta⁡(2,3)\operatorname{Beta}(2, 3):

The probability that Thompson sampling plays the first arm: Pr⁡{θ1>θ2}\Pr\{\theta_1 > \theta_2\} for independent θ1∼Beta⁡(3,2)\theta_1 \sim \operatorname{Beta}(3, 2), θ2∼Beta⁡(2,3)\theta_2 \sim \operatorname{Beta}(2, 3).
await show`Probability[x > y, {x \[Distributed] BetaDistribution[3, 2], y \[Distributed] BetaDistribution[2, 3]}]`
Pr⁡{θ1>θ2}=5370 \Pr\{\theta_1 > \theta_2\} = \frac{53}{70}

So the arm that looks better is played 53/70≈76%53/70 \approx 76\% of the time, not always: the posterior spread is the exploration, and it shrinks automatically as evidence accumulates. For decades the method had no regret guarantee. Agrawal and Goyal (COLT 2012) gave the first logarithmic bound,Shipra Agrawal and Navin Goyal. Analysis of Thompson Sampling for the Multi-armed Bandit Problem. In Shie Mannor, Nathan Srebro, and Robert C. Williamson, editors, Proceedings of the 25th Annual Conference on Learning Theory (COLT 2012), volume 23 of Proceedings of Machine Learning Research, pages 39.1–39.26, 2012 and Kaufmann, Korda and Munos (ALT 2012) proved that for Bernoulli rewards Thompson sampling attains the Lai–Robbins constant, settling a question open since 1933.Emilie Kaufmann, Nathaniel Korda, and Rémi Munos. Thompson Sampling: An Asymptotically Optimal Finite-Time Analysis. In Nader H. Bshouty, Gilles Stoltz, Nicolas Vayatis, and Thomas Zeugmann, editors, Algorithmic Learning Theory (ALT 2012), volume 7568 of Lecture Notes in Computer Science, pages 199–213. Springer, 2012. doi: 10.1007/978-3-642-34106-9_18Beyond Sutton and Barto (2018). The book mentions Thompson sampling in its summary as performing similarly to the best distribution-free methods. The optimality results (Agrawal and Goyal 2012; Kaufmann et al. 2012) predate the second edition but are not discussed there; since then, posterior sampling has been extended to linear and contextual bandits and to full MDPs, and is widely used in online experimentation. In practice it is often the best performer, needs no tuning constant, and extends naturally to structured problems wherever a posterior can be sampled.

The Bayesian view also reaches the exactly optimal policy that the book alludes to: with a known prior and discounting, Gittins showed that the optimal policy plays the arm with the largest Gittins index, computed separately for each arm.John C. Gittins. Bandit Processes and Dynamic Allocation Indices. Journal of the Royal Statistical Society: Series B (Methodological), 41(2):148–164, 1979. doi: 10.1111/j.2517-6161.1979.tb01068.x It needs the prior, does not extend to the full reinforcement learning problem, and is costly to compute; the frequentist index policies above approximate its behavior without those requirements. Everything in this chapter, however, lives in a single situation. Chapter 3 lets actions change the situation and so delay their consequences, which is the full reinforcement learning problem; the incremental estimates, step sizes and ε\varepsilon-greedy exploration built here reappear in almost every method that follows.

2.10Exercises

Exercise 2.14. (Sutton and Barto, Exercise 2.4.) If the step sizes αn\alpha_n are not constant, Qn+1Q_{n+1} is still a weighted average of Q1Q_1 and the rewards. Find the weights, and check that they sum to one.

Solution

Unrolling Qn+1=(1−αn)Qn+αnRnQ_{n+1} = (1 - \alpha_n)Q_n + \alpha_n R_n gives

Qn+1=∏j=1n(1−αj) Q1+∑i=1nαi∏j=i+1n(1−αj) Ri: Q_{n+1} = \prod_{j=1}^n (1 - \alpha_j)\,Q_1 + \sum_{i=1}^n \alpha_i\prod_{j=i+1}^n(1 - \alpha_j)\,R_i :

a reward is weighted by its step size times the product of the “forgetting factors” of all later steps. For αj=α\alpha_j = \alpha this is (2.7); for αj=1/j\alpha_j = 1/j the product telescopes to i/ni/n and every weight is 1/n1/n. The sum is one by induction: if the weights of QnQ_n sum to one, those of Qn+1Q_{n+1} sum to (1−αn)⋅1+αn=1(1-\alpha_n)\cdot 1 + \alpha_n = 1.

Three updates with symbolic step sizes α1,α2,α3\alpha_1, \alpha_2, \alpha_3, minus the weighted average with the product weights above: identically zero.
await show`Simplify[Fold[Function[{qq, ar}, qq + ar[[1]] (ar[[2]] - qq)], Subscript[Q, 1], Table[{Subscript[\[Alpha], i], Subscript[R, i]}, {i, 3}]] - (Product[1 - Subscript[\[Alpha], j], {j, 3}] Subscript[Q, 1] + Sum[Subscript[\[Alpha], i] Product[1 - Subscript[\[Alpha], j], {j, i + 1, 3}] Subscript[R, i], {i, 3}])]`
Q4−(∏j=13(1−αj) Q1+∑i=13αi∏j=i+13(1−αj) Ri)=0 Q_4 - \Bigl(\prod_{j=1}^{3}(1 - \alpha_j)\,Q_1 + \sum_{i=1}^{3}\alpha_i\prod_{j=i+1}^{3}(1 - \alpha_j)\,R_i\Bigr) = 0

Exercise 2.15. (Exercise 2.8.) On the testbed, UCB with c=2c = 2 shows a distinct spike in average reward at step 1111, followed by a drop. Explain both, and why the spike is smaller with c=1c = 1.

Solution

In the first 1010 steps every action has Nt(a)=0N_t(a) = 0 and is maximizing, so UCB plays each of the ten arms once, in random order: the average reward is about 00. At step 1111 all arms have N=1N = 1 and the same bonus cln⁡11c\sqrt{\ln 11}, so the choice is the greedy one on single samples, which picks the optimal arm, or a very good one, far more often than chance: the reward jumps. Now that arm has N=2N = 2 and a bonus cln⁡12/2c\sqrt{\ln 12/2}, while every other arm still has cln⁡12≈1.58 cc\sqrt{\ln 12} \approx 1.58\,c. With c=2c = 2 the difference in bonuses, 2(1.58−1.11)≈0.932(1.58 - 1.11) \approx 0.93, exceeds the typical gap between the best and the other single-sample estimates, so on step 1212 and the following ones UCB switches to other, mostly worse, arms to equalize uncertainty: the average reward drops. With c=1c = 1 the bonus difference is half as large, fewer arms overcome the value gap, and both the jump and the drop are smaller.

Exercise 2.16. (Exercise 2.9.) Show that for two actions the soft-max distribution is the logistic (sigmoid) function of the difference of preferences, and write the gradient bandit update for that difference.

Solution

Dividing numerator and denominator by eH(1)e^{H(1)} gives π(1)=1/(1+e−(H(1)−H(2)))=σ(H(1)−H(2))\pi(1) = 1/(1 + e^{-(H(1) - H(2))}) = \sigma(H(1) - H(2)), with σ\sigma the logistic function.

The two-action soft-max minus the logistic function of the preference difference.
await show`FullSimplify[Exp[Subscript[H, 1]]/(Exp[Subscript[H, 1]] + Exp[Subscript[H, 2]]) - LogisticSigmoid[Subscript[H, 1] - Subscript[H, 2]]]`
eH1eH1+eH2−σ(H1−H2)=0 \frac{e^{H_1}}{e^{H_1}+e^{H_2}} - \sigma(H_1 - H_2) = 0

Only D=H(1)−H(2)D = H(1) - H(2) matters. By (2.14), H(1)H(1) changes by α(R−R¯)(𝟙A=1−π(1))\alpha(R - \bar R)(\mathbb{1}_{A=1} - \pi(1)) and H(2)H(2) by α(R−R¯)(𝟙A=2−π(2))=−α(R−R¯)(𝟙A=1−π(1))\alpha(R - \bar R)(\mathbb{1}_{A=2} - \pi(2)) = -\alpha(R - \bar R)(\mathbb{1}_{A=1} - \pi(1)), so D←D+2α(R−R¯)(𝟙A=1−σ(D))D \leftarrow D + 2\alpha(R - \bar R)(\mathbb{1}_{A=1} - \sigma(D)): logistic regression of the event “action 1 was chosen” on a constant, weighted by the advantage R−R¯R - \bar R, exactly the form of the policy-gradient updates of Chapter 13.

Exercise 2.17. (Exercise 2.10.) A two-armed bandit has success probabilities (0.1,0.2)(0.1, 0.2) in case A and (0.9,0.8)(0.9, 0.8) in case B, each case occurring with probability 1/21/2 independently at each step. What is the best expected success if you cannot tell the cases apart, and how should you behave? What if you are told the case at each step (but not the values)?

Solution

Without the signal, action 1 succeeds with probability 12(0.1+0.9)=0.5\frac12(0.1 + 0.9) = 0.5 and action 2 with 12(0.2+0.8)=0.5\frac12(0.2 + 0.8) = 0.5. Every policy, even a randomized one, earns 0.50.5, so nothing can be learned: any behavior is optimal. With the signal, the task is a contextual bandit with two contexts; the best policy plays action 2 in case A and action 1 in case B, earning 12(0.2+0.9)=0.55\frac12(0.2 + 0.9) = 0.55. To find this policy one runs a separate bandit learner in each context, which is the simplest associative search method; the gain of 0.050.05 per step is the value of the information in the signal.

Exercise 2.18. Using (2.17), show that ε\varepsilon-greedy with a fixed ε>0\varepsilon > 0 has regret growing linearly in TT, and find the slope. Show that the decreasing schedule εt=min⁡{1,C/t}\varepsilon_t = \min\{1, C/t\} makes the expected number of exploratory steps grow only logarithmically.

Solution

Each step explores with probability ε\varepsilon and then picks every arm with probability 1/k1/k, so 𝔼[NT(a)]≥εT/k\mathbb{E}[N_T(a)] \ge \varepsilon T/k for every suboptimal arm and ℒT≥εTk∑aΔa\mathcal{L}_T \ge \frac{\varepsilon T}{k}\sum_a \Delta_a; by Proposition 2.2 the slope tends to exactly εk∑aΔa\frac{\varepsilon}{k}\sum_a\Delta_a, the gap between q⋆q_\star and (2.3). With εt=C/t\varepsilon_t = C/t (for t≥Ct \ge C) the expected number of exploratory steps up to TT is ∑tεt≈Cln⁡T\sum_t \varepsilon_t \approx C\ln T, and each costs at most the average gap: the exploration regret is logarithmic. Auer et al. showed that with CC of order k/Δmin⁡2k/\Delta_{\min}^2 the greedy steps are then also correct with high enough probability, giving logarithmic regret overall; the catch is that CC must be tuned to the unknown smallest gap, which UCB and Thompson sampling do not need.Peter Auer, Nicolò Cesa-Bianchi, and Paul Fischer. Finite-time Analysis of the Multiarmed Bandit Problem. Machine Learning, 47(2–3):235–256, 2002. doi: 10.1023/A:1013689704352