Inferensys

Glossary

Thompson Sampling

A Bayesian algorithm for the multi-armed bandit problem that selects actions randomly according to their posterior probability of being optimal, naturally balancing exploration and exploitation.
Developer demonstrating multi-agent tool use, agent tool selection interface on laptop, casual tech demo moment.
BAYESIAN BANDIT ALGORITHM

What is Thompson Sampling?

A probabilistic algorithm for the multi-armed bandit problem that selects actions by sampling from their posterior probability distributions, naturally balancing exploration and exploitation.

Thompson Sampling is a Bayesian algorithm that selects actions randomly according to their posterior probability of being optimal. For each arm in a multi-armed bandit, the algorithm maintains a probability distribution over its expected reward, samples from each distribution, and chooses the arm with the highest sampled value. This stochastic selection mechanism provides a principled approach to the exploration-exploitation tradeoff.

The algorithm updates its posterior distributions using Bayes' theorem as new reward observations arrive, typically employing Beta distributions for binary outcomes or Gaussian distributions for continuous rewards. Unlike epsilon-greedy strategies that explore uniformly, Thompson Sampling allocates exploration proportionally to uncertainty—arms with high variance are sampled more frequently until their true value is learned. It achieves logarithmic regret and often outperforms Upper Confidence Bound (UCB) methods in practice.

Bayesian Decision Theory

Key Characteristics of Thompson Sampling

Thompson Sampling is a probability matching algorithm that selects actions based on their posterior probability of being optimal. Unlike deterministic methods, it naturally balances exploration and exploitation by sampling from the belief distribution of each arm's reward.

01

Probability Matching Mechanism

The core mechanism of Thompson Sampling is probability matching: an action is chosen with a frequency proportional to its probability of being the best option. At each decision step, the algorithm draws a random sample from the posterior distribution of each arm's expected reward and selects the arm with the highest sampled value. This stochastic selection ensures that arms with high uncertainty are explored naturally, while arms with high estimated rewards are exploited frequently. The process is inherently self-correcting—as more data is gathered, the posterior distributions narrow, reducing exploration automatically.

02

Bayesian Foundation and Priors

Thompson Sampling is fundamentally a Bayesian algorithm that requires specifying a prior distribution over each arm's reward parameter. Common choices include:

  • Beta-Bernoulli model: For binary outcomes (click/no-click), using a Beta(α, β) prior where α represents successes and β represents failures.
  • Gaussian model: For continuous rewards with known variance, using a Normal prior on the mean.
  • Dirichlet-Multinomial model: For categorical outcomes with more than two possible results. The choice of prior encodes initial beliefs and can incorporate domain knowledge. A uniform prior (Beta(1,1)) represents complete ignorance, while an informed prior can accelerate early performance.
03

Regret Minimization Properties

Thompson Sampling achieves logarithmic regret in the stochastic multi-armed bandit setting, meaning the cumulative difference between its performance and an optimal oracle strategy grows only logarithmically with time. This is provably optimal. Key regret characteristics include:

  • Lai-Robbins lower bound: Thompson Sampling asymptotically matches the theoretical lower bound for regret in stochastic bandits.
  • Finite-time guarantees: Recent theoretical work provides finite-time regret bounds, not just asymptotic results.
  • Empirical superiority: In practice, Thompson Sampling often outperforms UCB (Upper Confidence Bound) and ε-greedy strategies, especially in the early stages of learning when uncertainty is high.
04

Contextual Extension: Contextual Thompson Sampling

The algorithm extends naturally to contextual bandits where side information is available before each decision. In Contextual Thompson Sampling, the reward model becomes a function of context features (e.g., user demographics, time of day). A common implementation uses Bayesian logistic regression or Bayesian linear regression with a prior over the weight vector. At each step:

  1. A weight vector is sampled from the posterior distribution over model parameters.
  2. The predicted reward is computed for each arm using the sampled weights and current context.
  3. The arm with the highest predicted reward is selected. This allows personalization based on observed features while maintaining the exploration-exploitation balance.
05

Computational Efficiency and Implementation

Thompson Sampling is computationally lightweight compared to many alternatives. For the Beta-Bernoulli case, each update requires only incrementing two counters (successes and failures), and sampling from a Beta distribution is a standard library call. Key implementation considerations:

  • Conjugate priors: Using conjugate prior-likelihood pairs (Beta-Binomial, Normal-Normal) ensures the posterior remains in the same distribution family, enabling closed-form updates without MCMC.
  • Batch updates: Posterior updates can be performed in batches rather than after every single observation, reducing computational overhead in high-throughput systems.
  • Non-conjugate extensions: For complex reward models (e.g., neural networks), approximate inference methods like variational inference or Monte Carlo dropout can approximate Thompson Sampling.
06

Comparison to Alternative Bandit Algorithms

Thompson Sampling differs from other bandit algorithms in fundamental ways:

  • vs. ε-greedy: ε-greedy explores uniformly at random with fixed probability ε, while Thompson Sampling directs exploration toward arms that might plausibly be optimal, making it far more efficient.
  • vs. UCB (Upper Confidence Bound): UCB constructs deterministic confidence intervals and always selects the arm with the highest upper bound. Thompson Sampling is stochastic and naturally handles complex posterior shapes that UCB's symmetric intervals cannot capture.
  • vs. Boltzmann exploration: Softmax/Boltzmann exploration uses a temperature parameter to control exploration randomness, while Thompson Sampling's randomness is driven by genuine posterior uncertainty, which diminishes automatically with data.
BAYESIAN DECISION THEORY

Frequently Asked Questions About Thompson Sampling

Clear, technically precise answers to the most common questions about the Thompson Sampling algorithm, its mechanisms, and its application in modern reinforcement learning and personalization systems.

Thompson Sampling is a Bayesian algorithm for the multi-armed bandit problem that selects actions randomly according to their posterior probability of being optimal, naturally balancing exploration and exploitation. The algorithm works by maintaining a probability distribution over the expected reward for each available action. At each decision step, it samples a single value from each action's posterior distribution and selects the action with the highest sampled value. After observing the actual reward, it updates the posterior distribution for the chosen action using Bayes' theorem. This stochastic selection mechanism ensures that actions with high uncertainty but promising potential are explored proportionally to their chance of being optimal, while actions with high certainty of high reward are exploited consistently. Unlike epsilon-greedy approaches that explore uniformly at random, Thompson Sampling directs exploration toward actions that have a non-trivial probability of being the best.

ALGORITHM COMPARISON

Thompson Sampling vs. Other Bandit Algorithms

A technical comparison of Thompson Sampling against alternative multi-armed bandit algorithms across key decisioning dimensions.

FeatureThompson SamplingEpsilon-GreedyUpper Confidence Bound (UCB)

Exploration Mechanism

Posterior probability matching via Bayesian sampling

Uniform random exploration with fixed probability

Optimistic bonus based on confidence intervals

Prior Knowledge Integration

Handles Non-Stationary Rewards

Computational Complexity per Step

O(K) with conjugate priors

O(1)

O(K log N)

Regret Bound (Asymptotic)

O(log N) with optimal prior

O(N) linear regret

O(log N)

Cold Start Performance

Excellent with informative priors

Poor without tuning

Moderate

Deterministic Action Selection

Empirical Regret on Standard Benchmarks

0.3%

1.2%

0.4%

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.