Chapter 03 · Part 1: Estimating from experience
Thompson sampling as posterior inference
Thompson sampling is Bayesian updating plus one extra step, acting on a single posterior draw, and this chapter shows why that matches the best arm's posterior probability and how its regret behaves.
Chapter 2 treated a bandit as a sequential experiment and turned a confidence bound into a decision rule: UCB pulls the arm whose upper confidence limit is highest. That is a frequentist construction. It takes an interval, picks its upper end, and acts as if the arm were that good.
A Bayesian reader asks a different question. If the data produce a whole distribution over what each arm's mean could be, why not use that distribution directly? Thompson (1933), a pathologist, proposed this almost a century ago, in a Biometrika paper on comparing two unknown probabilities from two samples. The idea is to sample a plausible world from the posterior and act as though it were true. The method sat in the literature for decades, was shown to work well in practice by Chapelle and Li (2011), and received its first logarithmic-regret proof from Agrawal and Goyal (2012).
This chapter uses the notation of the notation page: arms, mean rewards , , gaps , and regret . Rewards here are Bernoulli unless stated, and the arms are independent.
What does Thompson sampling do?
A Bayesian model has two parts. A prior says what we believe about the arm means before seeing data. A likelihood says how rewards are generated given the means; for a Bernoulli bandit, a pull of arm gives . Bayes' rule combines them into the posterior given the history of arms pulled and rewards seen through round .
Thompson sampling, in each round :
- Compute (or update) the posterior of every arm given the history.
- Draw one sample from each arm's posterior.
- Pull .
- Observe and update the posterior of arm .
There is no confidence level to tune and no exploration bonus. Exploration comes from the spread of the posterior: an arm we know little about has a wide posterior, so its draw is occasionally very high and it gets pulled. As data accumulate, the posterior narrows around the true mean and the draws stop beating the best arm.
Arms are independent under the prior, so only the pulled arm's posterior changes. And for the likelihoods we use, the posterior stays in the same family as the prior, which is worth a section.
Why is the beta distribution the right prior for Bernoulli rewards?
Take one arm with unknown mean (we drop the arm subscript). A prior has density proportional to
Suppose we see pulls with successes and failures. The likelihood is . Multiply:
That is the kernel of . A prior family that the likelihood maps to itself is called conjugate. The practical consequence is that the update is arithmetic on two counters: a success adds one to , a failure adds one to . The order of the observations does not matter, and updating one observation at a time gives the same answer as updating on all of them at once, because is a sufficient statistic.
The posterior mean is
It is a weighted average of the prior mean and the sample mean , with weights proportional to and . So acts as the prior sample size, the number of pseudo-observations the prior is worth. is the uniform distribution and is worth two pseudo-observations. is worth fifty, and it believes the mean is . The posterior variance shrinks like .
A worked example by hand
Two arms, both with a prior. Arm A is pulled once and pays . Arm B has not been pulled.
- Arm A posterior: , , so , with density on and mean .
- Arm B posterior: still , uniform, mean .
Thompson sampling plays A when . This is Thompson's original quantity, "the probability that one unknown probability exceeds another". Condition on the draw ; then B's uniform draw is below with probability :
So A is played with probability and B with probability . A greedy rule that plays the larger posterior mean would play A with probability one, forever, if A keeps winning. Thompson sampling still gives B a one-in-three chance now, and this chance falls as evidence accumulates against B.
Now suppose B is played and fails. Its posterior becomes with density and mean . The new play probability is with , so
One failure moved the probability of exploring B from to .
Why is this "probability matching"?
Let be the optimal arm. Under the Bayesian model is a random variable, a function of the unknown . Write for the posterior given the history before round . Thompson sampling draws from the posterior and plays . The true and the draw have the same distribution given , so and do too:
The algorithm plays each arm with the probability that the arm is best. That is why Chapelle and Li call it probability matching.
Two caveats a statistician should hold on to.
First, the identity is about the model's posterior. It is calibrated if the true was in fact drawn from the prior. Under a fixed (the frequentist view) the posterior probability that arm 1 is best can be early on, while arm 1 is the best arm in every run. Matching is a statement about the algorithm's relationship to its own posterior, not a statement that the posterior is right.
Second, adaptive sampling does not break Bayesian updating. In chapter 2 we saw that the sample mean of an adaptively sampled arm is biased. The posterior is unaffected, because the rule for choosing arms depends only on observed data, and so it factors out of the likelihood. The posterior after pulls of an arm is the same regardless of how those pulls were scheduled. This is the likelihood principle at work, and it is one reason Bayesian bandit algorithms are comfortable with adaptive data.
What changes with Gaussian rewards?
Take rewards with known, and a prior . After pulls with sample mean , the posterior is again normal. Multiplying the prior density by the likelihood and completing the square in gives
Precisions (inverse variances) add, and the posterior mean is a precision-weighted average of and . For large , , the standard error of the sample mean.
A Thompson draw for arm is then
Compare UCB1 from chapter 2, which plays the arm maximising . Both are "estimate plus a multiple of the standard error". UCB uses a fixed, deliberately large multiple, chosen so that the bound holds with high probability for every arm and time. Thompson uses a random multiple that is usually between and , centred at zero. UCB is optimistic on purpose; Thompson is optimistic about half the time.
What is Bayesian regret, and how does it differ from the regret you know?
Fix a . The frequentist regret of an algorithm on that instance is
the expectation taken over the rewards and the algorithm's own randomness, with held fixed. This is what chapter 2's Lai–Robbins bound and UCB1's guarantee are about. The Bayesian regret averages that over the prior:
The two views give two separate bodies of theory for Thompson sampling.
The Bayesian bound. Russo and Van Roy (2014) analyse Thompson sampling through information theory. Let be the mutual information, under the posterior at round , between the optimal arm and the pair (arm played, reward seen), and let be the expected instantaneous regret given the history. The information ratio is
It is small when a round either has little regret or teaches a lot about which arm is best. If always, then by Cauchy–Schwarz
The last step uses the chain rule: the information gained about over all rounds cannot exceed the prior entropy of the optimal arm. For Thompson sampling with rewards in , they prove for any prior (their Proposition 3), which gives
The bound scales with the entropy of the prior over the best arm. A prior that is already confident about which arm is best has small and a small bound. The tutorial by Russo, Van Roy, Kazerouni, Osband and Wen (2018) surveys this analysis alongside many extensions and applications, and is the best single reference for the method; it works through Bernoulli bandits, shortest-path problems, recommendation, and reinforcement learning in Markov decision processes.
The frequentist bound. Fix a Bernoulli instance and run Thompson sampling with priors. Agrawal and Goyal (2012) proved logarithmic expected regret, with a bound of order for arms, and for two arms. A sharper analysis by Kaufmann, Korda and Munos (2012) showed that the regret matches the Lai–Robbins lower bound asymptotically for Bernoulli rewards, so Thompson sampling is asymptotically optimal and not merely logarithmic. Agrawal and Goyal (2012, follow-up) gave a -optimal problem-dependent bound and an problem-independent bound. Note the conditions: these are statements for Bernoulli rewards with a uniform prior, and they hold on every instance, whether or not the prior "describes" it.
Frequentist guarantees survive a wrong prior as long as the prior puts positive mass near the truth; this is the same reason Bayesian estimators are consistent under mild conditions. What the prior changes is the constant. The next section looks at how much.
What does a wrong prior cost?
The prior is worth pseudo-observations. If the data are informative, a prior that is wrong but weak is overruled quickly. A prior that is wrong and strong is not: you need roughly as many real observations as pseudo-observations before the data win.
Take an arm whose true mean is and a prior shared by all arms, so every arm is believed to pay about and the prior is worth observations. After pulls of that arm the posterior mean is about . This falls below the best arm's true mean when , that is, at about . Every inferior arm must be pulled around forty times before the sampler stops being fooled, and each of those pulls costs regret. The posterior is also narrow ( standard deviation at the start), so the sampling noise that normally drives exploration is small and the fix is slow.
The experiment below also tries a prior with the wrong ordering: it believes the worst arm is best and the best arm is worst, each prior worth 20 observations.
Experiment: Thompson sampling against UCB1 and greedy
The code in ch03_thompson.py runs a five-arm Bernoulli bandit with means , over independent runs and rounds. UCB1 is the index of Auer, Cesa-Bianchi and Fischer (2002). Greedy pulls each arm once and then plays the highest sample mean. We report pseudo-regret, which sums the gaps of the arms played, so there is no reward noise in the regret itself; the only randomness is in which arms were played. Standard errors are across runs. A second experiment checks probability matching, and a third averages over instances drawn from the prior to estimate Bayesian regret.
Experiment 1: fixed instance mu = [0.6, 0.5, 0.45, 0.4, 0.35], 400 runs, T = 3000
Cumulative pseudo-regret, mean (standard error) over runs
algorithm T=100 T=500 T=1000 T=3000 locked-on-opt
greedy 9.3 ( 0.4) 40.8 ( 2.1) 79.5 ( 4.2) 232.7 (12.6) 49.2%
UCB1 11.9 ( 0.1) 47.7 ( 0.3) 80.0 ( 0.5) 158.0 ( 0.9) 38.0%
Thompson, Beta(1,1) 9.8 ( 0.2) 26.8 ( 0.6) 34.9 ( 0.9) 45.5 ( 1.3) 98.0%
Thompson, optimistic Beta(40,10) 12.4 ( 0.1) 48.2 ( 0.3) 73.3 ( 0.6) 106.5 ( 0.8) 85.8%
Thompson, reversed prior (n0=20) 17.2 ( 0.1) 44.9 ( 0.8) 53.9 ( 1.3) 62.2 ( 2.0) 98.5%
Lai-Robbins asymptotic lower-bound scale, sum(gap/KL) * ln T at T=3000: 101.0
locked-on-opt = share of runs pulling the best arm in >90% of the last 100 rounds
Experiment 2: probability matching, Thompson Beta(1,1), same 400 runs
selection frequency of each arm at round t vs mean posterior P(optimal)
t arm0 arm1 arm2 arm3 arm4
10 chosen 0.268 0.223 0.188 0.155 0.168
P(opt) 0.269 0.213 0.199 0.164 0.156
50 chosen 0.430 0.212 0.160 0.102 0.095
P(opt) 0.409 0.207 0.171 0.119 0.094
200 chosen 0.635 0.177 0.102 0.050 0.035
P(opt) 0.635 0.173 0.094 0.061 0.037
1000 chosen 0.910 0.050 0.028 0.005 0.007
P(opt) 0.919 0.045 0.021 0.010 0.006
Calibration: pool (run, arm, checkpoint); bin by posterior P(optimal)
bin count mean P(opt) chosen freq se
[0.00,0.05) 3171 0.016 0.016 0.002
[0.05,0.20) 2346 0.106 0.104 0.006
[0.20,0.40) 1075 0.284 0.281 0.014
[0.40,0.60) 517 0.487 0.491 0.022
[0.60,0.80) 345 0.697 0.719 0.024
[0.80,1.00) 546 0.920 0.919 0.012
Experiment 3: Bayesian regret, mu_a ~ U(0,1) iid, K=5, 1000 draws of mu, T=1000
algorithm Bayes regret max over runs
greedy 40.1 ( 2.9) 576.9
UCB1 68.2 ( 0.4) 119.2
Thompson, Beta(1,1) 17.2 ( 0.3) 94.4
Russo-Van Roy bound sqrt(0.5 * K * ln K * T) = 63.4Regret
At , Thompson sampling with the uniform prior has regret , UCB1 has , and greedy has . Three things stand out.
Thompson sampling beats UCB1 by a wide margin here, mostly by exploring less. UCB1 at is still worse than Thompson sampling and the gap widens. UCB1's index uses a confidence level calibrated for a worst-case guarantee, so its exploration bonus is larger than this instance needs; the share of runs "locked on" the best arm is only for UCB1 after 3000 rounds. The constant in the bonus is chosen for a worst-case guarantee, and a tuned bonus would do better. The comparison shows what an untuned textbook UCB costs on this instance, not a law that Bayesian methods always win. Chapelle and Li also report, in simulations of delayed feedback, that Thompson sampling is more robust than UCB when feedback arrives in batches, because randomising over arms keeps a batch from repeating one choice.
Greedy has the largest and the least stable regret. Its standard error is more than ten times UCB1's. Greedy locks onto the best arm in of runs; in the others early noise ranked a bad arm first and the best arm was starved of samples. Its mean regret hides a bimodal distribution. In the Bayesian experiment the worst single run has regret against for Thompson sampling. This is the same adaptive-sampling trap as chapter 2: an arm that looks bad stops being sampled, so its estimate is never corrected.
The Lai–Robbins line is a scale, not a ceiling. The quantity , with the Bernoulli Kullback–Leibler divergence, is at . Thompson sampling's is below it. That is not a contradiction: the lower bound is an asymptotic statement about for algorithms that are consistent on every instance, and says nothing about the value at a particular finite , where lower-order terms are negative or not yet visible.
Misspecified priors
The two bad priors cost real regret. The optimistic prior roughly doubles Thompson sampling's regret at ( against ), and of runs have locked on the best arm against for the uniform prior. This is the same order of magnitude as the back-of-envelope count above: forced pulls on each of four inferior arms, at an average gap of , is about units of regret, and the observed excess is . The rest comes from the slower resolution of near-ties when the posteriors are narrow. The reversed prior is worse early ( at against ) and then recovers, ending at with of runs locked on the best arm. Both effects come from the same place: prior pseudo-observations are real evidence until enough data outweighs them. Both priors have positive density everywhere on , so the frequentist guarantees still apply and regret is still growing slowly, but the constant is paid in full.
Probability matching
The top block of experiment 2 compares, over the runs, the fraction of runs that pulled each arm at round with the average of that run's posterior probability of the arm being optimal. They agree to within the sampling noise of runs (a standard error of about on a frequency near ). At , arm is chosen of the time and has mean posterior probability .
The calibration table is a sharper test. It pools every (run, arm, checkpoint) triple, bins it by that run's posterior , and compares the bin's mean posterior probability with how often the arm was actually chosen. The two columns agree in every bin to within about one standard error, from bins with probability around to bins around .
Note what the table does not say. In these runs arm is the best arm every time, yet at its mean posterior probability of being best is only . The posterior is honest about the data seen so far; it is not told the truth about .
Bayesian regret
When is drawn from the uniform prior, Thompson sampling's Bayesian regret at is , UCB1's is , and greedy's is . The Russo–Van Roy bound for Thompson sampling is , loose by a factor of about . It is a worst-case guarantee over all priors with that entropy and all reward distributions in , so it is not expected to be tight. Here the Bayesian setting favours Thompson sampling more than the fixed-instance one, which makes sense: the prior used for the draw is exactly the prior the algorithm assumes, so there is no misspecification to pay for.
Where does this leave us?
Thompson sampling treats exploration as uncertainty and uses the statistician's native object for uncertainty, the posterior. The cost is that you need a prior and a conjugate (or at least samplable) posterior. That is easy for Bernoulli and Gaussian arms and harder for arbitrary models; the tutorial by Russo et al. (2018) discusses approximate posterior sampling for models that lack a conjugate posterior. We come back to posterior sampling at full scale in chapter 9, where it is applied to whole Markov decision processes.
The next chapter drops the decision part and keeps the estimation part. Given a fixed policy, how do you estimate the expected return of a state from episodes of experience? It turns out to be the sample mean again, with two ways to define the sample. See chapter 4.
Exercises
- Pen and paper. Two arms each have a prior. Arm A is pulled twice and succeeds both times. Arm B is pulled once and fails. Write both posteriors and compute the probability that Thompson sampling plays A.
- Pen and paper. Arm A has one success and no failures; arm B has no data; both started from . Which arm does a greedy-on-posterior-mean rule play, and with what probability does Thompson sampling play the other one? What does this say about why greedy can get stuck?
- Pen and paper. Show that the Beta posterior mean is a weighted average of prior mean and sample mean, with weights and . For the prior and an arm with true mean , find the at which the expected posterior mean falls to . (Use the sample mean .)
- Change the code and predict. In
ch03_thompson.py, change the reversed prior's strength from to and then to . Predict the order of the three regret values at (uniform prior, , ) before you run it. Does the damage grow roughly linearly in the prior sample size? - Change the code and predict. Replace the means with . Which method's regret grows fastest early? Does Thompson sampling still lock onto the best arm in of runs by ? Think in terms of how many pulls are needed to separate arms with a gap of .
Sources
- Thompson, W. R. (1933). On the likelihood that one unknown probability exceeds another in view of the evidence of two samples. Biometrika 25(3–4), 285–294.
- Agrawal, S. and Goyal, N. (2012). Analysis of Thompson sampling for the multi-armed bandit problem. COLT 2012 (arXiv:1111.1797).
- Agrawal, S. and Goyal, N. (2012). Further optimal regret bounds for Thompson sampling. arXiv:1209.3353.
- Kaufmann, E., Korda, N. and Munos, R. (2012). Thompson sampling: an asymptotically optimal finite-time analysis. arXiv:1205.4217.
- Russo, D. and Van Roy, B. (2014). An information-theoretic analysis of Thompson sampling. arXiv:1403.5341.
- Russo, D., Van Roy, B., Kazerouni, A., Osband, I. and Wen, Z. (2018). A tutorial on Thompson sampling. Foundations and Trends in Machine Learning 11(1), 1–96.
- Chapelle, O. and Li, L. (2011). An empirical evaluation of Thompson sampling. Advances in Neural Information Processing Systems 24 (NIPS 2011).
- Auer, P., Cesa-Bianchi, N. and Fischer, P. (2002). Finite-time analysis of the multiarmed bandit problem. Machine Learning 47, 235–256.
- Lattimore, T. and Szepesvári, C. (2020). Bandit Algorithms. Cambridge University Press. Chapters 34–36 (Bayesian learning, Bayesian bandits, Thompson sampling).