Worked Example: Explore or Exploit? Bandit Strategies Compared
Deconstruct the fundamental exploration-exploitation trade-off across multi-armed bandits, comparing epsilon-greedy, Upper Confidence Bound (UCB1), and Bayesian Thompson Sampling under regret bounds and production serving latency.
Contentsand lesson path
On this page
Lessons of Reinforcement Learning Foundations
- Agents, Rewards and Returns: Framing Decisions as an MDP Concept · 20 min
- Worked Example: Explore or Exploit? Bandit Strategies Compared Worked example · 20 min
- Lab: From a Q-Table to a Deep Q-Network Lab · 30 min
- Lab: Policy Gradients from REINFORCE to Actor-Critic Lab · 30 min
- Rewards for Language Models: RLHF, GRPO and Their Failure Modes Concept · 20 min
- Check: Pick and Debug an RL Approach Knowledge check · 8 questions
What you will learn
- Frame a sequential decision problem as a Markov decision process (states, actions, rewards, discounted return, policy, value function) and balance exploration against exploitation in a multi-armed bandit with epsilon-greedy and UCB or Thompson sampling.
Prerequisites: Deep Learning Fundamentals
01. The Multi-Armed Bandit Problem and Exploration-Exploitation
Before tackling full sequential Markov decision processes where actions alter downstream states, machine learning engineers must confront the fundamental dilemma of reinforcement learning in its purest non-associative formulation: the Multi-Armed Bandit (MAB) problem. In a multi-armed bandit, an agent repeatedly chooses between $K$ discrete actions (e.g., displaying one of 5 marketing headlines, routing queries to 3 candidate LLM models, or allocating traffic to website design variants). Each action $k$ yields a reward drawn from an unknown probability distribution with true mean $\mu_k$. The agent faces an inescapable dilemma:
-
Exploitation: Choose the action with the highest empirical historical reward to maximize immediate short-term payoffs.
-
Exploration: Choose suboptimal or lesser-known actions to gather statistical information, discovering if a currently underperforming arm actually possesses a superior true mean.
-
Cumulative Regret and the Lai-Robbins Lower Bound: The performance of a bandit algorithm is quantified by Cumulative Regret $R_T$: the total expected reward lost by not choosing the optimal arm $k^* = \arg\max_k \mu_k$ across all $T$ rounds:
$$R_T = T \mu^* - \sum_{t=1}^T \mathbb{E}[r_t] = \sum_{k=1}^K \mathbb{E}[N_k(T)] \cdot \Delta_k, \quad \text{where } \Delta_k = \mu^* - \mu_k$$
A landmark theorem by Lai and Robbins (1985) proved that any consistent bandit algorithm must suffer cumulative regret that scales at least logarithmically with time: $R_T = \Omega(\log T)$. Purely random exploration suffers linear regret $\mathcal{O}(T)$, which is catastrophic in commercial applications. Engineers compare three canonical strategies:
-
1. $\epsilon$-Greedy (Heuristic Exploration): With probability $1 - \epsilon$, select the greedy empirical arm $\hat{k} = \arg\max_k \hat{\mu}_k$; with probability $\epsilon$, select a random arm uniformly across all $K$ choices. While simple and computationally lightweight, standard constant-$\epsilon$ greedy suffers linear regret $\mathcal{O}(\epsilon T)$ because it explores suboptimal arms forever with fixed probability. Decaying epsilon $\epsilon_t = \min(1, c/t)$ achieves logarithmic regret theoretically, but requires tuning arbitrary hyperparameters sensitive to true reward gaps.
-
2. Upper Confidence Bound (UCB1 - Optimism in the Face of Uncertainty): Auer et al. (2002) formalized the principle of optimism: choose the arm that maximizes an upper confidence bound derived from Hoeffding's Inequality:
$$A_t = \arg\max_k \left( \hat{\mu}_k(t) + c \sqrt{\frac{2 \ln t}{N_k(t)}} \right)$$
The bonus term $\sqrt{\frac{2 \ln t}{N_k(t)}}$ acts as an uncertainty bonus. Arms that have been pulled rarely receive a high bonus, guaranteeing thorough exploration. As an arm is pulled more frequently, $N_k(t)$ grows, shrinking the confidence interval and transitioning naturally toward pure exploitation. UCB1 provably achieves optimal $\mathcal{O}(\log T)$ regret without tuning.
-
3. Bayesian Thompson Sampling (Probability Matching): Thompson Sampling maintains a posterior probability distribution over the expected reward of each arm. For Bernoulli conversion rates (e.g., ad click-throughs $\in {0, 1}$), conjugate $\text{Beta}(\alpha_k, \beta_k)$ priors are maintained. In each round:
- Sample a candidate conversion rate $\theta_k \sim \text{Beta}(\alpha_k, \beta_k)$ for every arm $k$.
- Pull the arm with the highest sampled value: $A_t = \arg\max_k \theta_k$.
- Observe reward $r_t \in {0, 1}$ and update the posterior: if $r_t = 1$, increment $\alpha_k \leftarrow \alpha_k + 1$; if $r_t = 0$, increment $\beta_k \leftarrow \beta_k + 1$. Thompson Sampling naturally matches the probability of pulling an arm to the posterior probability that it is the optimal arm. In empirical production benchmarks, Thompson Sampling consistently outperforms UCB1, exhibiting lower cumulative regret and rapid adaptation.
-
Contextual Bandits: Bridging Bandits and Supervised Models: In personalized news recommendations or dynamic pricing, rewards depend on customer context $x_t$ (e.g., device type, location, browsing history). Contextual bandit algorithms (such as LinUCB or Neural Bandits) model expected reward as a parametric function of context $E[r_t \mid x_t, a] = x_t^T \theta_a$, providing personalized exploration bounds per customer segment.
-
Production Serving Latency and Delayed Feedback: Deploying bandits in real-time recommendation engines introduces infrastructure constraints. While UCB and Thompson Sampling require updated counts $N_k$, production event pipelines often experience delayed reward attribution (e.g., conversions maturing over 24 hours). Distributed architectures batch updates asynchronously, maintaining cached posterior parameters in Redis or DynamoDB to maintain sub-10ms serving SLAs.
-
Non-Stationary Bandits and Sliding-Window Adaptation: In commercial production environments (such as news aggregation feeds or dynamic e-commerce pricing), underlying conversion rates $\mu_k(t)$ are inherently non-stationary. Consumer interests shift with breaking news and seasonal promotions. Standard stationary bandits accumulate sample counts $N_k \to \infty$, causing exploration intervals to shrink permanently and freezing adaptation. To overcome this, engineers deploy Discounted UCB (D-UCB) or Sliding-Window Thompson Sampling, applying an exponential discount factor $\gamma_{\text{bandit}} \in (0.95, 0.99)$ to historical counts, ensuring the algorithm maintains agility to detect emerging shifts in arm performance.
-
Multi-Armed Bandits vs Traditional A/B Testing: Classical fixed-sample A/B testing splits incoming traffic equally (e.g., 50% Control, 50% Variant) until reaching pre-calculated statistical sample sizes for hypothesis testing. In commercial settings, this incurs immense opportunity cost: if Variant B is disastrously ineffective, 50% of users continue suffering poor experiences for weeks. Multi-armed bandits dynamically route the vast majority of traffic toward emerging winners while continuing minimal exploratory testing, minimizing cumulative regret. When formal hypothesis tests are required for regulatory compliance, off-policy evaluation methods (such as Inverse Propensity Scoring) adjust for the adaptive sampling distribution.
-
Batched Asynchronous Updating in Distributed Architectures: High-throughput web services handle tens of thousands of requests per second. Executing atomic transactional updates to Beta posterior parameters on every single ad click creates unmanageable database locking overhead. Production systems implement Batched Asynchronous Updates: server instances serve decisions based on periodically synchronized local parameter caches, while streaming pipelines (Apache Kafka and Apache Flink) aggregate interaction counts across micro-batches (e.g., 60-second intervals) before writing updated posteriors back to the distributed cache.
import numpy as np
np.random.seed(42)
# True conversion probabilities across 3 arms
true_probs = [0.05, 0.12, 0.08]
n_arms = len(true_probs)
rounds = 1000
# 1. Epsilon-Greedy Simulation
eps = 0.1
counts_eps = np.zeros(n_arms)
values_eps = np.zeros(n_arms)
reward_eps = 0
for _ in range(rounds):
arm = np.random.choice(n_arms) if np.random.rand() < eps \
else np.argmax(values_eps)
r = 1 if np.random.rand() < true_probs[arm] else 0
counts_eps[arm] += 1
values_eps[arm] += (r - values_eps[arm]) / counts_eps[arm]
reward_eps += r
# 2. Thompson Sampling (Beta conjugate priors)
alpha = np.ones(n_arms)
beta = np.ones(n_arms)
reward_ts = 0
for _ in range(rounds):
samples = [np.random.beta(alpha[i], beta[i]) for i in range(n_arms)]
arm = np.argmax(samples)
r = 1 if np.random.rand() < true_probs[arm] else 0
alpha[arm] += r
beta[arm] += (1 - r)
reward_ts += r
print(f"Epsilon-Greedy Total Reward: {reward_eps}")
print(f"Thompson Sampling Total Reward: {reward_ts}")
print(f"TS Pulls: Arm 0={alpha[0]+beta[0]-2:.0f}, " \
f"Arm 1 (best)={alpha[1]+beta[1]-2:.0f}, " \
f"Arm 2={alpha[2]+beta[2]-2:.0f}")
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.