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 -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 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 steps. The name comes from the slot machine, the “one-armed bandit”, here with levers; a doctor choosing among experimental treatments for successive patients faces the same problem.
Definition 2.1 (The k-armed Bandit). At each step the agent selects an action and receives a reward . The value of action is its expected reward,
(2.1)unknown to the agent, which maintains estimates of it. An action maximizing is greedy; choosing one is exploiting, choosing any other is exploring.
If the 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 is a mean, the natural estimate is the average of the rewards received when was chosen,
(2.2)with a default value (say ) when the denominator is zero. By the law of large numbers, whenever . Methods that estimate action values and select actions from the estimates are action-value methods. The simplest selection rule is greedy, 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 and, with probability , to choose uniformly among all actions: -greedy selection. The greedy action is then chosen with probability , 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 , the probability of selecting an optimal action converges to (assuming a unique optimum), and the expected reward per step converges to
(2.3)Proof. For each action , the events “step explores and picks ” are independent, each of probability , so by the second Borel–Cantelli lemma infinitely many of them occur: every almost surely and every . Hence the greedy action is eventually the optimal one, and from then on the selection probabilities are for it and for each other action. Averaging under these probabilities gives (2.3). □
Sutton and Barto’s 10-armed testbed draws bandit problems with independently and rewards , and averages the learning curves of each method over them. On it the greedy method improves fastest at first, then levels off near reward per step: in about two thirds of the problems its first samples of the optimal action were disappointing and it never returned. The -greedy methods keep improving. The proposition predicts their limits: averaged over problems, is the expected maximum of ten standard normals, and has mean zero.
The best possible reward per step on the testbed, , followed by the long-run reward and probability of the optimal action for and .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}}]}`So never selects the optimal action more than of the time and earns at most about per step, while eventually reaches and , 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 be the reward after its -th selection and the average of the first rewards. Then
(2.4)valid even for , where it gives whatever was. Memory and time per step are constant. The update has the shape that recurs throughout the book,
(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 ; in general we write or . 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: . Initialization: for : , .
Loop forever:
- with probability (ties broken at random), otherwise a uniformly random action.
- .
- .
- .
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 ,
(2.6)Proposition 2.4 (Exponential Recency-Weighted Average). The constant- estimate is a weighted average of the initial estimate and the past rewards,
(2.7)with nonnegative weights summing to one. The weight of decays geometrically with its age .
Proof. Write (2.6) as and substitute the same expression for , then , down to ; induction on gives (2.7). For the weights are nonnegative (with the convention , puts all the weight on ). Their sum telescopes: with ,
□
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 and variance .
Proposition 2.5 (Bias and Variance of the Constant-α Estimate). For i.i.d. rewards with mean and variance , and a deterministic ,
(2.8)The sample average, by contrast, is unbiased from on, with variance .
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 and every , symbolically.await show`Simplify[(1 - \[Alpha])^n + Sum[\[Alpha] (1 - \[Alpha])^(n - i), {i, 1, n}]]`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}]}]`await show`Limit[${meanVar}, n -> Infinity, Assumptions -> 0 < \[Alpha] < 1]`The constant- estimate never converges: it keeps fluctuating around with a standard deviation of about . 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 and a constant lie many step-size sequences (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
(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 the kernel decides when each series converges:
The two series of (2.9) for : the first must diverge (), the second converge ().await show`Assuming[p \[Element] Reals, {SumConvergence[n^-p, n], SumConvergence[n^(-2 p), n]}]`So the conditions hold exactly for , which includes the sample average , and fail for a constant step size (), whose squares do not sum. The theory therefore says that constant- 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 : in statistical language they are biased by them. For sample averages the bias disappears once the action has been selected; for constant it decays as 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 on the testbed, where the are around , 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 -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 -th reward with the step size
(2.10)where is a “trace of one”: the constant- average of a sequence of ones, started at zero.
Proposition 2.6 (Unbiased Constant-Step-Size Trick). With the step sizes (2.10), , and the estimate does not depend on :
(2.11)an exponential recency-weighted average with weights renormalized to sum to one. Hence for i.i.d. rewards of mean , and .
Proof. The recursion for is (2.6) applied to targets equal to from , so (2.7) gives . In particular and : the first update sets and erases . Now let . From and ,
using . With this unrolls to , which is (2.11). The weights sum to , giving unbiasedness, and gives . □
The trick behaves like a sample average at first (, ) 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]`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]`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]`2.6Upper-Confidence-Bound Action Selection#
-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
(2.12)with and any action with treated as maximizing. The square root measures the uncertainty of , so the bracket is an optimistic but plausible value for the action: optimism in the face of uncertainty. Choosing increases and shrinks its bonus; not choosing it lets 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 . Hoeffding’s inequality bounds the probability that the mean of independent rewards underestimates by more than : . Choose so that this failure probability shrinks with time like , small enough that summed over all steps and actions it stays bounded. Then the upper confidence bound is with , that is (2.12) with : 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 is its gap, then once its bonus drops below and both confidence intervals hold, its upper bound falls below the optimal action’s, so it can be chosen only while is below the threshold where the bonus equals .
Solve the Hoeffding tail for the confidence width , and the condition for the number of pulls after which a gap- 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]}`A suboptimal action is thus selected about times up to time , and each selection costs in expected reward: the loss grows only logarithmically, against the linear loss of -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: (UCB1: for rewards in ). Initialization: , for all .
Loop for :
- If some action has , let be such an action; otherwise .
- ; ; .
On the testbed UCB with beats -greedy after the first 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 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 for each action and select actions by the soft-max (Gibbs, Boltzmann) distribution
(2.13)Only differences of preferences matter: adding the same constant to all of them leaves unchanged. Preferences have no interpretation as rewards. The learning rule is
(2.14)where , 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 . Initialization: for all ; ; .
Loop forever:
- Compute and sample .
- ; ; (or a constant step size for nonstationary problems).
- For all : .
The rule looks ad hoc; it is in fact stochastic gradient ascent on the expected reward. Since depends on all the preferences, gradient ascent on would update
(2.15)which is impossible because the 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), . In particular .
Proof. Write , so that and . By the quotient rule,
Summing over gives , as it must, since the probabilities always sum to one. □
Theorem 2.10 (The Gradient Bandit Algorithm Is Stochastic Gradient Ascent). Let be any baseline that does not depend on (it may depend on the past). Then for every action ,
(2.16)so the expected update of (2.14) (with , the average of the rewards before step ) is times the gradient of the expected reward.
Proof. Condition throughout on the history up to the choice of , which fixes , and . Differentiate and subtract the zero sum of Lemma 2.9 multiplied by :
using the lemma in the last step. The right-hand side is an expectation over : it equals . Finally, by the tower property and , we may replace by , since the factor and are fixed once 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 including the current reward, which does depend on ; but since , we have , so their update is the one of the theorem with the step size , and it is still exactly stochastic gradient ascent. (The same holds for a constant-step baseline, with factor .) 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 , dropping the baseline degrades the gradient bandit badly, while with it, shifting all rewards by 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 , for : 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}]]`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}]]`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`The variance-minimizing baseline for two actions is , not the expected reward : the baseline matters most for the action that is rarely chosen, whose updates are large. The running average 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 , estimates by ridge regression, with and over the steps on which was chosen, and selects , the UCB rule with the standard deviation of a linear prediction in place of .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 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 steps, relative to always playing an optimal action. With , gaps and the number of selections of in the first steps,
(2.17)the second form following from . Regret decomposes into how often each suboptimal arm is tried, times how much each trial costs. Any fixed- 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: for every and every bandit in the family. Then for every suboptimal arm ,
(2.18)and hence, by (2.17),
where is the Kullback–Leibler divergence between the members of the family with means and .
The intuition: to be sure that arm is not optimal, a policy must collect enough samples to distinguish its reward distribution from one with mean just above , and the number of samples needed to tell two distributions apart with error probability is about 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, ; for small gaps it is quadratic in the gap.
The Bernoulli KL divergence between means and , to second order in : the Lai–Robbins constant for a nearly optimal arm is about .await show`SeriesCoefficient[p Log[p/(p + \[CapitalDelta])] + (1 - p) Log[(1 - p)/(1 - p - \[CapitalDelta])], {\[CapitalDelta], 0, 2}]`Since (Pinsker’s inequality), the bound is at most per unit of , attained when arms have means near ; arms with means near or 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 arms with rewards in , UCB1 (Algorithm 2.7 with ) has, for every ,
(2.19)The bound has the optimal rate, but its constant exceeds the Lai–Robbins constant by a factor of at least , 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
(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 ; the authors recommend in practice. Solving (2.20) needs a one-dimensional root search per arm, since the KL divergence is increasing in above .
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 priors, the posterior of an arm with successes and failures is , so the algorithm needs two counters per arm.
Algorithm 2.13 (Thompson Sampling for Bernoulli Bandits). Initialization: , for all .
Loop forever:
- For each , sample .
- ; .
- If then , else .
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 and :
The probability that Thompson sampling plays the first arm: for independent , .await show`Probability[x > y, {x \[Distributed] BetaDistribution[3, 2], y \[Distributed] BetaDistribution[2, 3]}]`So the arm that looks better is played 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 -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 are not constant, is still a weighted average of and the rewards. Find the weights, and check that they sum to one.
Solution
Unrolling gives
a reward is weighted by its step size times the product of the “forgetting factors” of all later steps. For this is (2.7); for the product telescopes to and every weight is . The sum is one by induction: if the weights of sum to one, those of sum to .
Three updates with symbolic step sizes , 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}])]`Exercise 2.15. (Exercise 2.8.) On the testbed, UCB with shows a distinct spike in average reward at step , followed by a drop. Explain both, and why the spike is smaller with .
Solution
In the first steps every action has and is maximizing, so UCB plays each of the ten arms once, in random order: the average reward is about . At step all arms have and the same bonus , 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 and a bonus , while every other arm still has . With the difference in bonuses, , exceeds the typical gap between the best and the other single-sample estimates, so on step and the following ones UCB switches to other, mostly worse, arms to equalize uncertainty: the average reward drops. With 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 gives , with 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]]]`Only matters. By (2.14), changes by and by , so : logistic regression of the event “action 1 was chosen” on a constant, weighted by the advantage , exactly the form of the policy-gradient updates of Chapter 13.
Exercise 2.17. (Exercise 2.10.) A two-armed bandit has success probabilities in case A and in case B, each case occurring with probability 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 and action 2 with . Every policy, even a randomized one, earns , 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 . To find this policy one runs a separate bandit learner in each context, which is the simplest associative search method; the gain of per step is the value of the information in the signal.
Exercise 2.18. Using (2.17), show that -greedy with a fixed has regret growing linearly in , and find the slope. Show that the decreasing schedule makes the expected number of exploratory steps grow only logarithmically.
Solution
Each step explores with probability and then picks every arm with probability , so for every suboptimal arm and ; by Proposition 2.2 the slope tends to exactly , the gap between and (2.3). With (for ) the expected number of exploratory steps up to is , and each costs at most the average gap: the exploration regret is logarithmic. Auer et al. showed that with of order the greedy steps are then also correct with high enough probability, giving logarithmic regret overall; the catch is that 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