Thompson Sampling & Bayesian Bandits
Sampling from your beliefs: the oldest bandit algorithm, and one of the best.
UCB asks how good each arm could plausibly be. Thompson sampling asks how likely each arm is to be the best, and pulls it with exactly that probability. Built from Bayes' rule in a dozen lines of code, it matches the best optimistic algorithms in theory and often beats them in practice. This lesson derives it, implements it, compares it with UCB, and maps the situations where it goes wrong.
What you’ll learn
- Derive the Beta–Bernoulli and Gaussian posterior updates, and read a prior as a number of imaginary observations.
- Implement Thompson sampling, including the Bernoulli trick for rewards in , and show that it is probability matching.
- Explain why a suboptimal arm is pulled about times, and state the guarantees that make Thompson sampling asymptotically optimal for Bernoulli arms.
- Compare Thompson sampling with UCB in theory and in simulation, including under delayed feedback.
- Recognize where it needs care: wrong priors or likelihoods, drifting arms, information that only suboptimal actions reveal, and approximate posteriors.
Bayes’ rule for slot machines
The algorithms of the previous lessons treat the arm means as fixed unknowns and surround their estimates with confidence intervals. The Bayesian view treats the means as random. A prior distribution describes what you believe before any pull, and after each pull Bayes' rule combines the prior with the likelihood of the observed reward into a posterior. The posterior is everything the history says about the arms.
For Bernoulli arms the natural prior is the Beta distribution , with density proportional to on . If the arms' priors are independent, so are their posteriors: a pull of arm changes only arm 's posterior.
Beta–Bernoulli. Arm has paid times in pulls, so pulls paid nothing. Multiply the prior density by the likelihood of these outcomes and renormalize:
The posterior is again a Beta distribution: the prior is conjugate to the likelihood, and updating means adding one to a count. The posterior mean blends the prior mean and the sample average with weights and , so the prior is worth imaginary pulls:
Gaussian, known variance. Rewards are and the prior is . The log posterior is quadratic in , so the posterior is Gaussian, and its precision (inverse variance) is the prior's plus per observation:
With and the posterior is : the average shrunk slightly toward 0, with width . This is the posterior of Gaussian Thompson sampling below.
Think first Two analysts watch an arm pay on 3 of its first 4 pulls. One started from Beta(1, 1), the other from Beta(20, 20). What are their posterior means, and which one is right?
Beta(4, 2) has mean , and Beta(23, 21) has mean . Both apply Bayes' rule correctly; they disagree because their priors do. The second analyst claimed in advance the equivalent of 40 pulls averaging 0.5. Which posterior is better calibrated depends on whether that prior described reality, for instance whether past arms like this one really paid about half the time. Bayesian guarantees hold on average over the prior the algorithm uses, so choosing the prior is part of the model, not a formality.
Thompson sampling is probability matching
Thompson sampling turns the posterior into a decision with one rule. In round , draw one sample of the means from the posterior given the history , play the arm that is best for the sample, , and update the posterior with the reward.
Write for the optimal arm; in the Bayesian model it is a random variable too. Given the history, the sample and the true means have the same distribution, by construction, and therefore so do the arms that maximize them:
import numpy as np
def thompson(pull, k, T, a0=1.0, b0=1.0, seed=0):
"""pull(i) returns a reward in [0, 1] from arm i. Beta(a0, b0) prior on each arm."""
rng = np.random.default_rng(seed)
a = np.full(k, a0) # prior + successes
b = np.full(k, b0) # prior + failures
for t in range(T):
theta = rng.beta(a, b) # one plausible mean per arm
i = int(np.argmax(theta)) # act as if the sample were true
r = pull(i)
x = float(rng.random() < r) # Bernoulli trick: a 0/1 reward with mean r
a[i] += x
b[i] += 1.0 - x
return a, b
# Gaussian version (unit-variance model, N(0, 1) prior): keep pulls n and reward sums s,
# and draw theta = rng.normal(s / (n + 1), 1 / np.sqrt(n + 1))Beta–Bernoulli Thompson sampling. For a reward strictly between 0 and 1, Agrawal and Goyal (2012) flip a coin that lands 1 with probability and update with the coin: the coin has the same mean as the reward, so the Beta updates, and the guarantees below, carry over to any rewards in . The Gaussian version in the last comment is the other variant they analyze. Neither needs a tuning parameter or the horizon.
Uniform priors. Arm A has paid 3 times in 4 pulls, so its posterior is Beta(4, 2), mean 0.67. Arm B has paid 29 times in 48 pulls: Beta(30, 20), mean 0.60. Greedy play would pull A every time. In what fraction of rounds does Thompson sampling pull A?
Show the answer
0.65
, from integrating over the two Beta densities. A's posterior rests on 4 pulls and is wide, so about one draw in three falls below B's narrow posterior near 0.6, and then B is pulled. That is not wasted effort: it is the right amount of doubt about an arm seen 4 times. Each pull of A narrows its posterior, and if A really is better its share climbs toward 1.
Why it explores just enough
Probability matching spends exploration only where it can still change the decision. How much is that? Follow one suboptimal Bernoulli arm with mean , and ask how often its posterior draw beats the best arm's draw, which stays near once the best arm has been pulled many times.
With a uniform prior, after pulls with successes the posterior is . A Beta variable with integer parameters is distributed like the -th smallest of independent uniforms, and that order statistic exceeds exactly when at most of the uniforms fall below :
With and , Chernoff's bound makes this binomial tail exponentially small. Its exponent is the Bernoulli relative entropy , the KL divergence between Bernoulli() and Bernoulli():
Over rounds the arm keeps winning a draw now and then until falls below about , and then essentially never. It is therefore pulled about
This is the Lai–Robbins constant, the smallest that any consistent policy can achieve (Regret Lower Bounds). The heuristic skips the hard part: the rounds in which the best arm's posterior is unluckily low, so that every arm looks equally bad. Controlling those rounds is the heart of the proofs in Regret Bounds for Thompson Sampling.
On the regret lab's 'easy' arms the best mean is 0.9 and the runner-up 0.7, with . About how many pulls of the runner-up does predict for Thompson sampling by ?
Show the answer
60
, and . UCB1 keeps pulling this arm while reaches 0.9, about times. Two things make up the factor of almost 8. UCB1's confidence level costs a factor 4 over a Hoeffding bound at level . And Hoeffding's inequality assumes the largest spread possible in , while the Beta posterior uses the arm's own Bernoulli shape: is almost twice Hoeffding's exponent . In the regret lab on these arms at , Thompson sampling's total regret averages about 18 and UCB1's about 145.
Thompson sampling and UCB compared
Both families have logarithmic regret on every fixed instance and regret of order , up to logarithms, in the worst case. The differences lie elsewhere: in how they randomize, what they need to know, and how they extend beyond independent arms.
| Aspect | Optimism (UCB) | Thompson sampling |
|---|---|---|
| Decision | A deterministic index: estimate plus confidence bonus | A random draw from the posterior, then a greedy choice |
| Needs | A concentration inequality for the reward family | A prior, and a likelihood whose posterior can be sampled |
| Tuning | The bonus scale; values with guarantees are conservative | The prior; with a uniform prior, nothing |
| Delayed or batched feedback | Repeats the same arm until the data arrive | Spreads a batch over the arms that may be best |
| Structured actions (linear, combinatorial, MDPs) | Must optimize over actions and a whole confidence set at once | Solves one ordinary optimization for the sampled model |
| Guarantees | Frequentist and finite-time, by construction | Frequentist for some models and priors; Bayesian in general |
| Cost per round | arithmetic | draws for conjugate models; costly when the posterior must be approximated |
Delayed feedback. Real systems update in batches: the rewards of an hour of decisions arrive together. A deterministic index cannot change until new data arrive, so UCB sends a whole batch to one arm, while Thompson sampling draws afresh for every decision. In Chapelle and Li's (2011) simulations with 10 arms, as the feedback delay grew from 1 to 1,000 rounds, UCB's regret grew from about 2.7 to about 3.8 times Thompson sampling's. On news-recommendation data with delays of 10 to 60 minutes, UCB was competitive at short delays and degraded markedly as the delay grew. The same paper ran Thompson sampling with an approximate (Laplace) posterior over a logistic-regression click model for display advertising, an early demonstration that approximate posteriors work at scale.
A Bayesian guarantee borrowed from UCB. Russo and Van Roy (2014) noticed that probability matching lets any confidence bound analyze Thompson sampling, although the algorithm never computes one. Take any upper confidence bounds computed from the history. Given , the function is fixed while and have the same distribution, so , and the expected regret of round splits in two:
A recommender updates its statistics once an hour, after thousands of decisions. Why does Thompson sampling suffer less from this delay than UCB1?
- Thompson sampling learns more from each reward
- UCB1 needs to know the horizon, which the delay hides
- UCB1's index cannot change during the hour, so every decision goes to the same arm; Thompson sampling draws afresh each time and spreads the decisions over the arms that may be best
- Thompson sampling ignores rewards that arrive late
Show the answer
C. UCB1's index cannot change during the hour, so every decision goes to the same arm; Thompson sampling draws afresh each time and spreads the decisions over the arms that may be best
Between updates both algorithms see the same data. UCB1 is deterministic given the data, so it repeats its choice for the whole batch, and a wrong choice is repeated thousands of times. Thompson sampling spreads the batch roughly in proportion to each arm's posterior probability of being best, which is what a careful experimenter would do with a batch.
Where Thompson sampling struggles
A wrong model. Every guarantee above assumes that the prior and the likelihood describe the arms. A prior that gives the truth little weight costs regret until the data overrule it: in a problem with two actions and two candidate models, Liu and Li (2016) showed that Thompson sampling's regret grows like , where is the prior probability of the true model, and that this dependence is tight. "Uninformative" priors are not automatically safe either. For Gaussian arms with unknown means and variances, Honda and Takemura (2014) proved Thompson sampling asymptotically optimal with priors uniform in the variance or in the standard deviation, but not with the reference prior or the Jeffreys prior, the textbook objective choices; with the Jeffreys prior the regret even grows polynomially.
Heavy tails break light-tailed likelihoods. One extreme draw can drag a sample mean far from the truth, and a Gaussian posterior centered on it is then confidently wrong. Robust mean estimators (truncated means, medians of means) restore logarithmic regret for UCB-type rules when only a moment of order is finite (Bubeck, Cesa-Bianchi & Lugosi, 2013); a Thompson sampler needs a likelihood that can represent the tails.
Think first Arms : exactly one of them, equally likely to be any, pays 1, and the others pay 0. An extra arm 0 pays when arm is the paying one, so a single pull of arm 0 reveals . How does Thompson sampling treat arm 0, and what does that cost as grows?
It never pulls arm 0. Under every posterior sample some arm pays 1, more than arm 0's , so arm 0 is never best for the sample. Thompson sampling therefore searches the arms one at a time, with expected regret growing linearly in , while one pull of arm 0 (regret below 1) followed by the revealed arm solves the problem whatever is. Probability matching values an action only by its chance of being optimal, never by what it teaches. Russo and Van Roy (2018) use this example to motivate information-directed sampling, which weighs each action's expected regret against the information it yields; that ratio returns in Regret Bounds for Thompson Sampling as the information ratio.
Approximate posteriors. Beyond conjugate models the posterior must be approximated, by Laplace's method, variational inference, Markov chain Monte Carlo or ensembles, and the error matters. Phan, Abbasi-Yadkori and Domke (2019) showed that an approximation off by even a small constant amount (in α-divergence) can cause linear regret, by exploring too little or too much. For one family of errors, those that can only make it explore too little, mixing in a small, decaying amount of uniform exploration restores sublinear regret.
Other objectives. Probability matching minimizes regret, not the time needed to identify the best arm: once one arm dominates the posterior, its closest rival is rarely sampled. Top-two variants that keep testing the strongest challenger are covered in Best-Arm Identification.
Key takeaways
- A Bayesian bandit keeps a posterior over the arm means. With Beta priors and Bernoulli rewards, updating adds the successes and failures to the Beta parameters, and a prior Beta(, ) is worth imaginary pulls.
- Thompson sampling draws one sample from the posterior and plays the arm that is best for the sample. Each arm is thus played with exactly its posterior probability of being the best one: probability matching.
- A suboptimal arm's draw beats the best arm with probability about , so it is pulled about times. For Bernoulli arms Thompson sampling attains the Lai–Robbins constant, and its worst-case regret is .
- Compared with UCB, Thompson sampling randomizes, which makes it robust to delayed and batched feedback, uses the shape of the reward model, and extends to any model whose posterior can be sampled. Any upper-confidence analysis also bounds its Bayesian regret.
- It needs care when the prior or the likelihood is wrong, when arms drift, when the information lies in actions that are never optimal, and when the posterior is only approximate.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
An arm has a Beta(2, 3) prior and pays on 4 of its first 6 pulls. What is its posterior?
- Beta(6, 5), with mean
- Beta(4, 2): the prior is forgotten once data arrive
- Beta(6, 9): the successes go to and all the pulls to
- Beta(2, 3) with its mean moved to
Show the answer
A. Beta(6, 5), with mean
Add the 4 successes to and the 2 failures to : Beta(2 + 4, 3 + 2) = Beta(6, 5). The prior still counts as imaginary pulls, which pulls the mean from the sample's toward the prior's .
In a Bernoulli bandit with independent Beta posteriors, with what probability does Thompson sampling pull arm in round ?
- In proportion to arm 's posterior mean
- until the posteriors have converged, then 1 for the best arm
- The posterior probability that arm has the largest mean
- if arm has the largest posterior mean
Show the answer
C. The posterior probability that arm has the largest mean
The sample and the true means have the same distribution given the history, so the arm that is best for the sample has the distribution of the arm that is truly best: .
Compared with an optimistic index built on Hoeffding's inequality, for which suboptimal Bernoulli arms does Thompson sampling's Beta posterior help the most?
- Arms with means near 1/2, because their rewards are the most random
- Arms whose rewards vary little, with means near 0 or 1: their posteriors are narrow, while Hoeffding's inequality assumes the largest possible spread
- Arms pulled early in the run, because Thompson sampling discounts old data
- None: the two exponents, and , are always equal
Show the answer
B. Arms whose rewards vary little, with means near 0 or 1: their posteriors are narrow, while Hoeffding's inequality assumes the largest possible spread
Thompson sampling pulls the arm about times, a Hoeffding index at least times. Pinsker's inequality gives , with near equality when both means are close to 1/2, where a Bernoulli reward has its largest variance. Near the boundary is much larger: click rates of 0.01 against 0.1 give against , more than four times as large.
Two arms swap their means halfway through a long run. Why does Thompson sampling adapt more slowly than UCB1?
- It needs to be told when the switch happens
- Its draws are biased toward the arms pulled most recently
- It stops updating its posteriors after the first half
- The formerly best arm's posterior rests on many old rewards, so it moves slowly and keeps winning the draws, while UCB1's bonus for the neglected arm grows with until that arm is retried
Show the answer
D. The formerly best arm's posterior rests on many old rewards, so it moves slowly and keeps winning the draws, while UCB1's bonus for the neglected arm grows with until that arm is retried
After a thousand pulls the old best arm's posterior is narrow and centered near its old mean; the new, worse rewards shift it only gradually, so its draws keep beating the neglected arm's. UCB1 also weighs all rewards equally, but its index for an arm it has stopped pulling keeps rising, which forces a retry. In the regret lab's 'switch' preset this is the difference between regret of about 236 and about 51 at .
Thompson sampling never pulls an arm that is optimal under no posterior sample. When does that cost the most?
- When such an arm is informative, for example when one pull of it would reveal which arm is best
- When the rewards are Bernoulli
- When the horizon is short
- Never: an arm that cannot be optimal is not worth pulling
Show the answer
A. When such an arm is informative, for example when one pull of it would reveal which arm is best
Probability matching values an action only by its chance of being optimal. In Russo and Van Roy's revealing-action example, a known-suboptimal arm identifies the best of arms in one pull, yet Thompson sampling never pulls it and searches arm by arm, with regret growing linearly in . Information-directed sampling, which weighs regret against information, pulls it once.
Go deeper
- Regret Bounds for Thompson Sampling · Frequentist proofs, and the information-ratio analysis of Bayesian regret.
- The Gittins Index · The exact Bayes-optimal policy for discounted bandits, and why it is an index.
- Posterior Sampling & Deep Exploration · PSRL, randomized value functions and bootstrapped DQN.
Further reading
- W. 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).
- D. Russo, B. Van Roy, A. Kazerouni, I. Osband & Z. Wen, "A tutorial on Thompson sampling," Foundations and Trends in Machine Learning 11(1), 1–96 (2018).
- O. Chapelle & L. Li, "An empirical evaluation of Thompson sampling," Advances in Neural Information Processing Systems 24 (2011).
- S. Agrawal & N. Goyal, "Near-optimal regret bounds for Thompson sampling," Journal of the ACM 64(5) (2017).