The exploration-exploitation dilemma: stochastic bandits and UCB
Multi-armed bandits isolate exploration versus exploitation. Define regret, analyze ε-greedy and explore-then-commit, derive UCB1 from Hoeffding, and compare policies across replicates.
After this lesson you can
- Define regret and pseudo-regret and prove the gap decomposition.
- Implement incremental action-value estimation with sample-average and constant steps.
- Analyze ε-greedy and explore-then-commit, including linear regret from fixed exploration.
- Derive UCB1 and its logarithmic gap-dependent regret bound.
- Compare bandit algorithms using regret averaged across seeds.
Before you start
Learning also has a cost
An adaptive A/B test must choose which version to show while its effect remains unknown. Always using the detection rule that looks best can leave a useful alternative untested; splitting visits without exploiting what is learned also has a cost. A multi-armed bandit isolates this tension: choose an action, observe only its reward, and decide again.
There are arms and horizon . Arm produces i.i.d. rewards with unknown mean ; assume stationary distributions, independent sequences across arms, and rewards independent of past decisions once the arm is chosen. Imagine one potential sequence per arm fixed by the environment and revealed in order when pulled. At round , action depends on history through , not the still-unobserved reward. With full information all arm outcomes would be visible; here only of the chosen arm is observed.
Preparing the reproducible bandit.
Exploration obtains information about uncertain alternatives; exploitation chooses using current information. No universal boundary works for every distribution and horizon. A classical bandit also does not itself model an action’s effect on future states: Markov decision processes will address that.
Update without storing every sample
After pulls of the same arm, its sample mean satisfies
This follows by adding the new observation to the previous sum and dividing by . The incremental estimator needs only count and mean; with step it exactly equals the mean of all arm samples. A constant step gives
Old observations thus lose weight geometrically and the estimator can react to changes, though it retains noise in a stationary environment. The count is per arm, not global rounds. Stationary guarantees do not automatically transfer to a changing environment.
Regret: measuring the cost of not knowing
Let , and . Expected pseudo-regret relative to a best-mean arm is
The identity is exact: by iterated expectation, since choice depends only on the past, . Substitute , group by arm, and use linearity. An optimal arm has zero gap, even with several optima. Realized trajectory regret can be defined against potential rewards of the optimal arm; noise may make it negative. Sum is pseudo-regret of that action sequence, not observed cumulative reward. Their expectations agree under the preceding coupling and assumptions.
Explore with simple rules
In ε-greedy, with probability choose uniformly among arms; otherwise choose one with maximal estimated mean. With fixed , each round devotes at least probability to each arm. If a positive gap exists, : constant exploration contributes linear regret, though it can aid adaptation. Decreasing changes the tradeoff and needs its own analysis.
Another option initializes action values above expected rewards, then chooses the estimated maximum. An observation below the initial value reduces it and can encourage trying other arms, although an individual reward may exceed it. Scale and update step matter: initial optimism does not guarantee sustained exploration, especially in nonstationary problems.
Explore-then-commit (ETC) pulls each arm times and chooses the highest sample mean for remaining rounds. For independent 1-subgaussian rewards, , Lattimore and Szepesvári, theorem 6.1 give
The first term is exploration cost and the second controls committing to the wrong arm. For two arms and known gap , the interior continuous minimum of relaxed bound is . One recipe rounds upward: , clipped to the allowed integer interval if argument or horizon is outside the interior regime. It need not be the exact integer minimum. The rule uses the true gap, usually unknown: it is analysis, not an algorithm that magically estimates it. Gap-free schedules have order guarantees for a horizon-indexed family; do not confuse that bound with the temporal slope of one run with fixed . If wrong choice has positive probability, keeping fixed as grows produces linear expected regret after commitment.
Optimism with an upper bound
UCB1 pulls each arm once and, at round , selects a maximum of the index
The first part exploits observed mean; the second favors under-sampled arms. This is optimism under uncertainty: an uncertain arm may be best even if its empirical mean does not lead. The index is not a probability and may exceed one. For i.i.d. rewards in , Hoeffding gives, at fixed sample size ,
and the same bound for the lower tail. Since pull counts are chosen adaptively, simply inserting as though fixed is insufficient: the proof sums over possible sample sizes.
Preparing the UCB1 trajectory.
Proof of logarithmic regret
Fix optimal arm and another with . Let . If is chosen in round after at least pulls, at least one deviation occurs:
- The optimal arm’s empirical mean falls below for its observation count .
- The empirical mean of exceeds for its observation count .
Indeed, if neither occurs the optimal index is at least , while that of is at most , since and . Strict inequality avoids relying on equal-index tie breaking.
For each pair of possible sizes , Hoeffding bounds each deviation probability by . A conservative union over pairs gives at most for that round. Counting the first choices and summing deviations,
By the gap lemma, UCB1 satisfies
This is the bound of Auer, Cesa-Bianchi and Fischer. It can exceed for a small gap and finite horizon: still valid but uninformative. If rewards lie in , also . For a bound without explicit gap dependence, separate arms with , whose total contribution is at most , from others whose leading contribution is at most . Choosing proportional to gives order plus constant terms.
Reward scale is part of the assumption. Multiplying every payoff by 100 without multiplying the bonus by 100 changes the rule and no longer permits direct use of unit-range Hoeffding. Gaussian rewards are unbounded: they can be simulated, but this guarantee for rewards in does not literally apply.
Preparing the reproducible bandit simulation.
Lab: compare bandit policies
Use 200 replicates, common reward tables per arm, and horizon 500. Each Bernoulli replicate permutes the same ten means across arms, avoiding favoring the best through lowest-index tie breaking. In each Gaussian replicate standard-normal means and unit-variance normal rewards are drawn. Initial optimism is 1 or 5 respectively; after an arm is observed its sample mean is used. Table bands are normal approximations for the mean, not simultaneous guarantees. UCB1 with Gaussian rewards does not satisfy the bound’s bounded-reward assumption.
import numpy as np
def bandit(means, rewards, method, seed=2202, optimistic_init=1.0):
"""Una fila por réplica; rewards[r,a,j] es la j-ésima recompensa del brazo a."""
reps, k, horizon = rewards.shape
rows = np.arange(reps)
count = np.zeros((reps, k), dtype=np.int64)
values = np.zeros((reps, k), dtype=np.float64)
if method == 'optimista':
values[:] = optimistic_init
cumulative = np.zeros(reps)
optimal = np.zeros(reps)
reward_curve = np.empty(horizon)
optimal_curve = np.empty(horizon)
committed = np.zeros(reps, dtype=np.int64)
m = max(1, min(horizon // k, int(np.ceil((horizon / k) ** (2 / 3)))))
generator = np.random.default_rng(seed)
best = means.max(axis=1)
for step in range(horizon):
if method == 'ucb' and step < k:
action = np.full(reps, step)
elif method == 'etc' and step < k * m:
action = np.full(reps, step % k)
elif method == 'etc':
if step == k * m:
committed = values.argmax(axis=1)
action = committed
elif method == 'ucb':
action = (values + np.sqrt(2 * np.log(step + 1) / count)).argmax(axis=1)
elif method == 'epsilon':
action = values.argmax(axis=1)
explore = generator.random(reps) < .1
action[explore] = generator.integers(k, size=explore.sum())
elif method == 'optimista':
action = values.argmax(axis=1)
else:
raise ValueError(method)
pulls = count[rows, action]
reward = rewards[rows, action, pulls]
count[rows, action] += 1
# Optimismo inicial con media muestral; al visitar un brazo desaparece el prior.
values[rows, action] += (reward - values[rows, action]) / count[rows, action]
cumulative += best - means[rows, action]
optimal += np.isclose(means[rows, action], best, rtol=0, atol=1e-12)
reward_curve[step] = reward.mean()
optimal_curve[step] = np.isclose(means[rows, action], best, rtol=0, atol=1e-12).mean()
return {'pseudo': cumulative, 'optimal_fraction': optimal / horizon, 'count': count,
'm': m, 'reward_curve': reward_curve, 'optimal_curve': optimal_curve}
def make_environment(kind, reps=200, horizon=500, seed=2202):
generator = np.random.default_rng(seed)
if kind == 'bernoulli':
means = np.stack([generator.permutation(np.linspace(.6, .15, 10)) for _ in range(reps)])
rewards = (generator.random((reps, 10, horizon)) < means[:, :, None]).astype(np.float64)
elif kind == 'gaussiano':
means = generator.normal(size=(reps, 10))
rewards = generator.normal(size=(reps, 10, horizon)) + means[:, :, None]
else:
raise ValueError(kind)
return means, rewards
def benchmark(kind):
means, rewards = make_environment(kind)
print('\n', kind, '200 réplicas, 10 brazos, T=500')
results = {}
for method in ('epsilon', 'optimista', 'etc', 'ucb'):
out = bandit(means, rewards, method, optimistic_init=5.0 if kind == 'gaussiano' else 1.0)
results[method] = out
se = out['pseudo'].std(ddof=1) / np.sqrt(len(out['pseudo']))
print(f"{method:10s} regret={out['pseudo'].mean():7.2f} ± {1.96*se:5.2f}; "
f"elecciones óptimas={100*out['optimal_fraction'].mean():5.1f}%")
idx = np.array([0, 9, 49, 99, 249, 499])
print(' t=', idx+1, 'recompensa=', np.round(out['reward_curve'][idx], 3),
'óptima=', np.round(out['optimal_curve'][idx], 3))
if kind == 'gaussiano':
print('UCB1 con gaussianas es una comparación exploratoria; la cota acotada no se aplica.')
return results
def check_bound(gap):
reps = 200
for horizon in (100, 500, 1000):
means = np.tile([.6, .6-gap], (reps, 1))
generator = np.random.default_rng(2203)
rewards = (generator.random((reps, 2, horizon)) < means[:, :, None]).astype(float)
result = bandit(means, rewards, 'ucb')
pulls = result['count'][:, 1]
np.testing.assert_allclose(result['pseudo'], gap * pulls, atol=1e-10)
bootstrap = np.random.default_rng(2204).choice(pulls, size=(1000, reps), replace=True).mean(axis=1)
bound = 8*np.log(horizon)/gap**2 + 1 + np.pi**2/3
print(f'Δ={gap:.2f}, T={horizon}, visitas={pulls.mean():.3f}, '
f'IC bootstrap={np.quantile(bootstrap,[.025,.975])}, '
f'cota={bound:.3f}, regret={result["pseudo"].mean():.3f}')
print('La cota es sobre la esperanza y puede ser vacua; el intervalo describe estas réplicas.')
bernoulli = benchmark('bernoulli')gaussiano = benchmark('gaussiano')import matplotlib.pyplot as plt
def plot_benchmark(results, name):
fig, axes = plt.subplots(1, 2, figsize=(10, 3.4))
for label, result in results.items():
t = np.arange(1, len(result['reward_curve'])+1)
axes[0].plot(t, result['reward_curve'], label=label)
axes[1].plot(t, 100*result['optimal_curve'], label=label)
axes[0].set(title=f'{name}: recompensa media', xlabel='Ronda', ylabel='Recompensa')
axes[1].set(title='Acciones óptimas', xlabel='Ronda', ylabel='% de réplicas')
axes[1].legend()
fig.tight_layout()
plt.show()plot_benchmark(bernoulli, 'Bernoulli')plot_benchmark(gaussiano, 'Gaussiano')check_bound(.1)check_bound(.2)The final cells compare average visits and the UCB1 bound as horizon and gap vary. Bootstrap describes replicates and does not prove the theorem; a bound larger than the horizon is valid but vacuous. The guarantee is from Auer, Cesa-Bianchi and Fischer (2002), for independent rewards in [0,1].
Exercises
Step 1 of 3. What is the expectation of the round-t reward?
Step 1 of 4. If arm a has at least ℓ observations and neither confidence interval fails, why cannot it be chosen?
import numpy as np
def ucb1(env,T):
pass
import math
gap, horizon = .05, 10000
relaxed = (4/gap**2)*math.log(horizon*gap**2/4)
per_arm = min(horizon//2,max(1,math.ceil(relaxed)))
print('Mínimo continuo de la cota relajada:',relaxed)
print('Por brazo:',per_arm,'exploración total:',2*per_arm,'compromiso:',horizon-2*per_arm)