AI Wiki中文/EN

Thompson sampling: draw a plausible model, then choose

汤普森采样

Update Beta-Bernoulli beliefs, sample success probabilities and test probability matching without confusing parameters with outcomes.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A plausible success rate is not an imaginary success

Two unfamiliar buttons each return either 0 or 1. Start with an independent uniform belief about each success probability. You try button 0 once and observe a success. Its posterior mean becomes two-thirds; button 1’s remains one-half. A greedy rule now always selects button 0 until later data change that ranking.

Thompson sampling asks a different question: what if we drew one plausible success probability for each button from the current beliefs, then chose the better button in that sampled model? Button 1 can still win the draw. In this particular example, button 0 is selected with probability two-thirds and button 1 with probability one-third.

The draw is a parameter such as 0.63, not a fabricated reward of 0 or 1. Only the reward obtained from the actual chosen action updates the posterior. Russo and colleagues’ tutorial emphasizes this distinction. Silver’s exploration lecture presents the rule as probability matching.

Posterior parameter densities determine action-selection probabilities. Repeated draws without feedback do not update the posterior; the learning comparison uses new observations.
Posterior parameter densities determine action-selection probabilities. Repeated draws without feedback do not update the posterior; the learning comparison uses new observations.

Update beliefs, sample a model, make one decision

Assume K arms have fixed unknown Bernoulli success probabilities theta_a. Given those probabilities, rewards are independent across pulls and arms. Begin with independent Beta priors with positive parameters alpha_a,beta_a. For one arm, the density and its normalizing integral are

p(θ∣α,β)=θα−1(1−θ)β−1B(α,β),0<θ<1,B(α,β)=∫01uα−1(1−u)β−1 du.p(\theta\mid\alpha,\beta)= \frac{\theta^{\alpha-1}(1-\theta)^{\beta-1}}{B(\alpha,\beta)},\quad 0<\theta<1, \qquad B(\alpha,\beta)=\int_0^1 u^{\alpha-1}(1-u)^{\beta-1}\,du.

Alpha and beta must be strictly positive; both equal to one give a uniform prior. They need not be integers. The mathematical distribution covers a continuum of possible success probabilities, unlike the Bernoulli observation which has only two outcomes.

Why does a success add one to alpha?

If one arm has S observed successes and F failures, its Bernoulli likelihood multiplies the prior by theta^S(1−theta)^F. Collecting exponents gives

p(θ∣H)∝θα−1+S(1−θ)β−1+F⟹θ∣H∼Beta⁡(α+S,β+F).p(\theta\mid H)\propto \theta^{\alpha-1+S}(1-\theta)^{\beta-1+F} \quad\Longrightarrow\quad \theta\mid H\sim\operatorname{Beta}(\alpha+S,\beta+F).

Only a selected arm contributes a new reward likelihood, so with independent priors only its parameters change. A real success adds one to alpha; a real failure adds one to beta. Unchosen arms receive neither a failure nor an imagined observation. If parameters were correlated a priori, feedback from one arm could inform another, and this independent-arm update would no longer describe the full posterior. The tutorial’s Beta-Bernoulli example states the independent model.

The mean and variance of a Beta posterior are

E[θ]=αα+β,Var⁡(θ)=αβ(α+β)2(α+β+1).\mathbb E[\theta]=\frac{\alpha}{\alpha+\beta},\qquad \operatorname{Var}(\theta)= \frac{\alpha\beta}{(\alpha+\beta)^2(\alpha+\beta+1)}.

The mean follows by integrating theta times the density: the integral is B(alpha+1,beta)/B(alpha,beta). Similarly, the second moment is alpha(alpha+1)/[(alpha+beta)(alpha+beta+1)]; subtracting the squared mean gives the variance. Equal posterior means need not imply equal uncertainty: Beta(1,1) and Beta(10,10) both have mean one-half, but variances 1/12 and 1/84.

The action distribution comes from the whole posterior

At each round, sample one parameter per arm, select a maximizing sample, observe the real reward r, and update only that arm:

θ~a∼Beta⁡(αa,βa),A=argmax⁡aθ~a,(αA,βA)←(αA+r,βA+1−r).\widetilde\theta_a\sim\operatorname{Beta}(\alpha_a,\beta_a),\qquad A=\operatorname*{argmax}_a\widetilde\theta_a,\qquad (\alpha_A,\beta_A)\leftarrow(\alpha_A+r,\beta_A+1-r).

The continuous independent Beta model has probability zero of an exact maximum tie. Code still needs a tie rule for finite-precision values; ours samples uniformly among exact maximizing values. Replacing the parameter samples by posterior means gives a different, greedy algorithm.

Let H be the observed history. Because the sampled vector has the joint posterior law, the probability of choosing an arm matches its posterior probability of being optimal:

Pr⁡(A=a∣H)=Pr⁡(θ~a>θ~b ∀b≠a∣H)=Pr⁡(θa>θb ∀b≠a∣H).\Pr(A=a\mid H)= \Pr(\widetilde\theta_a>\widetilde\theta_b\ \forall b\ne a\mid H) =\Pr(\theta_a>\theta_b\ \forall b\ne a\mid H).

This is a statement inside the specified Bayesian model. With fixed real parameters, it is not a guarantee that the arm selected on this round is truly best. A badly chosen prior or likelihood can produce confident but wrong beliefs. Nor does probability matching say the rule maximizes every finite-horizon Bayesian objective.

Compute the opening probability exactly

After one success on arm 0, its posterior is Beta(2,1), with density 2x; arm 1 remains uniform, whose cumulative distribution at x is x. Integrate over the first draw:

Pr⁡(θ~0>θ~1)=∫012xPr⁡(θ~1<x) dx=∫012x2 dx=23.\Pr(\widetilde\theta_0>\widetilde\theta_1) =\int_0^1 2x\Pr(\widetilde\theta_1<x)\,dx =\int_0^1 2x^2\,dx=\frac23.

The numerical coincidence with arm 0’s posterior mean is specific to this uniform competitor. In general, an arm’s selection probability is not its posterior mean or that mean normalized across arms. All competing posterior distributions matter.

Use separate random streams for beliefs and rewards

Save this standard-library Python 3 program as thompson.py and run python3 thompson.py. BetaAgent.select draws hypothetical parameters; observe accepts a real binary reward. It rejects fractional rewards because the implemented likelihood is Bernoulli. A different reward model would need a corresponding update, not an arbitrary fractional success count presented as the same model.

import math
import random
import statistics


def integer(x, name, minimum=0):
    if isinstance(x, bool) or not isinstance(x, int) or x < minimum:
        raise ValueError(name + ' must be an integer >= ' + str(minimum))
    return x


def finite(x, name, low=None, high=None):
    if isinstance(x, bool) or not isinstance(x, (int, float)) or not math.isfinite(x):
        raise ValueError(name + ' must be finite')
    if (low is not None and x < low) or (high is not None and x > high):
        raise ValueError(name + ' is outside its domain')
    return float(x)


def probabilities(values):
    p = [finite(v, 'probability', 0, 1) for v in values]
    if not p:
        raise ValueError('at least one arm is required')
    return p


class Bernoulli:
    """The learner receives only pull(action), never the mean vector."""
    def __init__(self, means, seed):
        self._means = probabilities(means)
        integer(seed, 'seed')
        self._streams = [random.Random(seed + 104729 * a) for a in range(len(means))]

    def pull(self, action):
        integer(action, 'action')
        if action >= len(self._means):
            raise ValueError('unknown action')
        return int(self._streams[action].random() < self._means[action])


def summary(values):
    if len(values) < 2:
        raise ValueError('at least two independent runs are needed for an SE')
    return dict(mean=statistics.mean(values), se=statistics.stdev(values) / math.sqrt(len(values)))


class BetaAgent:
    def __init__(self, arms, seed, prior=(1., 1.)):
        integer(arms, 'arms', 1); integer(seed, 'seed')
        if len(prior) != 2: raise ValueError('need two prior parameters')
        a, b = [finite(x, 'prior', 0) for x in prior]
        if min(a, b) <= 0: raise ValueError('prior parameters must be positive')
        self.alpha = [a] * arms; self.beta = [b] * arms; self.rng = random.Random(seed)

    def select(self, method='sample'):
        if method == 'sample': values = [self.rng.betavariate(a, b) for a, b in zip(self.alpha, self.beta)]
        elif method == 'mean': values = [a / (a + b) for a, b in zip(self.alpha, self.beta)]
        else: raise ValueError('unknown posterior decision rule')
        best = max(values)
        return self.rng.choice([i for i, v in enumerate(values) if v == best])

    def observe(self, action, reward):
        integer(action, 'action'); reward = finite(reward, 'Bernoulli reward', 0, 1)
        if action >= len(self.alpha) or reward not in (0., 1.): raise ValueError('need an existing arm and a binary reward')
        self.alpha[action] += reward; self.beta[action] += 1 - reward

    def moments(self):
        return [dict(mean=a / (a + b), variance=a * b / ((a + b)**2 * (a + b + 1))) for a, b in zip(self.alpha, self.beta)]


def run(seed, method='sample', steps=800):
    integer(steps, 'steps', 1); means = [.25, .45, .7]; env = Bernoulli(means, seed)
    agent = BetaAgent(3, seed + 1000003); counts = [0] * 3; loss = 0.
    for _ in range(steps):
        a = agent.select(method); r = env.pull(a); agent.observe(a, r)
        counts[a] += 1; loss += max(means) - means[a]
    return dict(counts=counts, alpha=agent.alpha, beta=agent.beta, moments=agent.moments(), pseudoregret=loss)


def demo():
    toy = BetaAgent(2, 51); toy.observe(0, 1)
    selected = [toy.select() for _ in range(20000)]
    comparisons = {name: summary([run(s, name)['pseudoregret'] for s in range(30)]) for name in ['sample', 'mean']}
    return dict(horizon=800, seeds=list(range(30)), comparisons=comparisons,
                posterior_example=dict(alpha=toy.alpha, beta=toy.beta, moments=toy.moments(),
                                       draws=20000, sampled_probability_arm0=selected.count(0) / len(selected),
                                       exact_probability_arm0=2 / 3), single_seed=run(0))


if __name__ == '__main__':
    import json
    print(json.dumps(demo(), indent=2, allow_nan=False))

The opening posterior experiment performs 20,000 decisions without collecting more feedback. The posteriors therefore remain Beta(2,1) and Beta(1,1); arm 0 is selected with frequency 0.6635 for seed 51, near the exact 2/3 probability. Drawing parameters alone must not make the model more certain.

The learning experiment uses original Bernoulli means [0.25,0.45,0.70], uniform priors, 800 rounds and 30 seed labels 0–29. Parameter randomness is separate from each arm’s reward stream. Mean path pseudo-regret is 11.81 for posterior sampling, with standard error about 1.14172; posterior-mean greedy gives 54.1933 with standard error about 16.3361. These are finite simulated results for this instance, not the tutorial’s reported experiment or a general superiority theorem. Unlike the neighboring UCB and epsilon examples, this experiment does not force one initial pull per arm; account for that protocol difference in comparisons.

Per decision the algorithm draws K Beta samples and scans them; it stores O(K) parameters, and a selected update costs O(1). Calling this O(K) time assumes a distribution sample is a unit-cost operation. The library’s sampling routine uses rejection methods, so the number of internal random draws is not a fixed worst-case constant. The simulation stores summaries and final parameters rather than every trajectory.

Belief uncertainty does not replace model checking

Beta-Bernoulli conjugacy makes this example easy. Continuous rewards, correlated arms, drifting probabilities and delayed outcomes require other models or explicit approximations. A strong prior can dominate limited data. Repeatedly updating from an imagined reward would create artificial certainty rather than additional information.

UCB constructs a frequentist index under bounded-reward assumptions. Thompson sampling randomizes according to a posterior. Neither the word “Bayesian” nor a single learning curve guarantees calibrated beliefs, optimal finite-horizon planning or successful deployment. Contextual bandits adds observed features; ignoring them may mix distinct reward populations into one arm mean.

Separate the parameter, observation and decision

  1. Starting from Beta(1,1), an arm produces rewards 1,0,1. What is its posterior and mean?

    Answer: Beta(3,2), with mean 3/5. Two successes increment alpha twice and one failure increments beta once. Other independent arms are unchanged.

  2. Why does Beta(2,1) beat an independent uniform draw with probability 2/3?

    Answer: Conditional on its value x, the uniform draw is smaller with probability x. Average this against density 2x: integrating 2x² from zero to one gives 2/3.

  3. You call select 20,000 times without observing rewards. Should alpha and beta change?

    Answer: No. Those are decisions under the same evidence. Updating from the sampled parameter or an imagined outcome would count nonexistent data and distort uncertainty.

  4. Two Beta posteriors have the same mean but different concentrations. May a mean-greedy rule treat them identically while Thompson sampling behaves differently?

    Answer: Yes. Mean-greedy sees only the means; parameter samples use the entire distributions. Different variances change how often each can beat the other arms. Selection probabilities must consider the competitors too, not just an isolated arm’s variance.

Keep the tutorial’s version and claims separate

The source used here is Russo et al.’s explicit arXiv v3, dated July 2020; its metadata separately records the 2017 preprint and 2018 journal publication. The scoped reading covers the Beta-Bernoulli construction and its early examples, not every application or later theorem in the tutorial. Silver’s lecture supplies the probability-matching perspective. We use the success-to-alpha convention above; changing parameter names in another presentation must not reverse the update accidentally.

Make a prediction, then check

In Beta-Bernoulli Thompson sampling, what is sampled before choosing an arm?

Choose one answer

Learning objectives

  • Update only the selected arm and derive its Beta posterior moments.
  • Explain probability matching and why posterior-mean greedy selection differs.

Prerequisites & connections

Explore related knowledge →

References

  1. A Tutorial on Thompson Sampling — arXiv v3
    Daniel J. Russo, Benjamin Van Roy, Abbas Kazerouni, Ian Osband, Zheng Wen · 2020
  2. Lecture 9: Exploration and Exploitation
    David Silver · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: Read PDF1 and13–16 of explicit2020-07-14 arXivv3; metadata separately records first preprint2017 and journal2018. Beta-Bernoulli updating, parameter rather than outcome samples, probability matching and reported simulation conditions. Figure3.1 was not visually inspected; neither the10000-run experiments nor later theory chapters were replicated/audited. Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse. 6 paired equations and four explained exercises. Checked positive priors, selected-only binary feedback, posterior moments by exact polynomial integration, parameter versus reward draws, probability matching, seeded control and posterior-mean greedy comparison. Repeated draws do not count as feedback; no universal Bayesian optimality claim.

  • Checked positive priors, selected-only binary feedback, posterior moments by exact polynomial integration, parameter versus reward draws, probability matching, seeded control and posterior-mean greedy comparison. Repeated draws do not count as feedback; no universal Bayesian optimality claim.
  • Four computed SVG variants per topic;12 numeric/geometry tests and30 responsive cases passed. Ten selected current captures inspected: seven final captures directly viewed, three byte-identical to directly viewed earlier captures; actual byte identity checked. Browser inputs bound by SHA before integration. Full article acceptance recorded separately.

Source locations checked:

  • A Tutorial on Thompson Sampling — arXiv v3 · Read PDF1 and13–16 of explicit2020-07-14 arXivv3; metadata separately records first preprint2017 and journal2018. Beta-Bernoulli updating, parameter rather than outcome samples, probability matching and reported simulation conditions. Figure3.1 was not visually inspected; neither the10000-run experiments nor later theory chapters were replicated/audited.
  • Lecture 9: Exploration and Exploitation · Author teaching page dates the course2015, not its2025 upload. Read PDF1,3–20,22,24–25,28,30,33; directly viewed20. Its bottom regret formula uses gaps instead of inverse gaps; use Auer Theorem1, not this slide, for the bound. Constant exploration, probability matching and contextual feedback only; no universal TS optimality claim. Alpha/beta success conventions follow Russo, not the reversed slide28/30 labels. Link-only, no slide reuse.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.