Module contents
Lesson 2 of 37Core 105 min

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 KK arms and horizon TT. Arm aa produces i.i.d. rewards with unknown mean μa\mu_a; 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 tt, action AtA_t depends on history through t−1t-1, not the still-unobserved reward. With full information all arm outcomes would be visible; here only XtX_t of the chosen arm is observed.

InteractivePlay and learn

Preparing the reproducible bandit.

Compare your choices with algorithms receiving reproducible reward sequences for each arm.

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 nn pulls of the same arm, its sample mean satisfies

Qn=Qn−1+1n(Xn−Qn−1).Q_n=Q_{n-1}+\frac{1}{n}(X_n-Q_{n-1}).

This follows by adding the new observation to the previous sum and dividing by nn. The incremental estimator needs only count and mean; with step 1/n1/n it exactly equals the mean of all arm samples. A constant step 0<α≤10<\alpha\leq1 gives

Qn=(1−α)nQ0+α∑i=1n(1−α)n−iXi.Q_n=(1-\alpha)^nQ_0+\alpha\sum_{i=1}^n(1-\alpha)^{n-i}X_i.

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 μ∗=max⁡aμa\mu^*=\max_a\mu_a, Δa=μ∗−μa≥0\Delta_a=\mu^*-\mu_a\geq0 and Na(T)=∑t=1T1{At=a}N_a(T)=\sum_{t=1}^T\mathbf1\{A_t=a\}. Expected pseudo-regret relative to a best-mean arm is

RT=Tμ∗−E ⁣[∑t=1TXt]=∑a=1KΔa E[Na(T)].R_T=T\mu^*-\mathbb E\!\left[\sum_{t=1}^T X_t\right] =\sum_{a=1}^K\Delta_a\,\mathbb E[N_a(T)].

The identity is exact: by iterated expectation, since choice depends only on the past, E[Xt∣At=a,historia]=μa\mathbb E[X_t\mid A_t=a,\text{historia}]=\mu_a. Substitute μAt\mu_{A_t}, 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 ∑t(μ∗−μAt)\sum_t(\mu^*-\mu_{A_t}) 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 ε\varepsilon choose uniformly among KK arms; otherwise choose one with maximal estimated mean. With fixed ε>0\varepsilon>0, each round devotes at least ε/K\varepsilon/K probability to each arm. If a positive gap exists, RT≥(εT/K)∑aΔaR_T\geq (\varepsilon T/K)\sum_a\Delta_a: constant exploration contributes linear regret, though it can aid adaptation. Decreasing εt\varepsilon_t 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 mm times and chooses the highest sample mean for remaining rounds. For independent 1-subgaussian rewards, 1≤m≤T/K1\leq m\leq T/K, Lattimore and Szepesvári, theorem 6.1 give

RT≤m∑aΔa+(T−Km)∑aΔae−mΔa2/4.R_T\leq m\sum_a\Delta_a+(T-Km)\sum_a\Delta_a e^{-m\Delta_a^2/4}.

The first term is exploration cost and the second controls committing to the wrong arm. For two arms and known gap Δ>0\Delta>0, the interior continuous minimum of relaxed bound mΔ+TΔe−mΔ2/4m\Delta+T\Delta e^{-m\Delta^2/4} is 4Δ2log⁡(TΔ2/4)\frac4{\Delta^2}\log(T\Delta^2/4). One recipe rounds upward: m=⌈4Δ2log⁡(TΔ2/4)⌉m=\left\lceil\frac4{\Delta^2}\log(T\Delta^2/4)\right\rceil, 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 T2/3T^{2/3} guarantees for a horizon-indexed family; do not confuse that bound with the temporal slope of one run with fixed mm. If wrong choice has positive probability, keeping mm fixed as TT grows produces linear expected regret after commitment.

Optimism with an upper bound

UCB1 pulls each arm once and, at round t>Kt>K, selects a maximum of the index

UCB⁡a(t)=μ^a,Na(t−1)+2log⁡tNa(t−1).\operatorname{UCB}_a(t)=\widehat\mu_{a,N_a(t-1)}+\sqrt{\frac{2\log t}{N_a(t-1)}}.

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 [0,1][0,1], Hoeffding gives, at fixed sample size ss,

P ⁣(μ^a,s−μa≥2log⁡ts)≤t−4,\Pr\!\left(\widehat\mu_{a,s}-\mu_a\geq\sqrt{\frac{2\log t}{s}}\right)\leq t^{-4},

and the same bound for the lower tail. Since pull counts are chosen adaptively, simply inserting Na(t−1)N_a(t-1) as though fixed is insufficient: the proof sums over possible sample sizes.

InteractiveUCB means and indices

Preparing the UCB1 trajectory.

Advance through rounds to see each arm’s mean and bonus; an unobserved arm is explored before finite indices are compared.

Proof of logarithmic regret

Fix optimal arm a∗a^* and another aa with Δa>0\Delta_a>0. Let ℓ=⌊8log⁡T/Δa2⌋+1\ell=\lfloor 8\log T/\Delta_a^2\rfloor+1. If aa is chosen in round tt after at least ℓ\ell pulls, at least one deviation occurs:

  1. The optimal arm’s empirical mean falls below μ∗−2log⁡t/s\mu^*-\sqrt{2\log t/s} for its observation count ss.
  2. The empirical mean of aa exceeds μa+2log⁡t/n\mu_a+\sqrt{2\log t/n} for its observation count nn.

Indeed, if neither occurs the optimal index is at least μ∗\mu^*, while that of aa is at most μa+22log⁡t/n<μ∗\mu_a+2\sqrt{2\log t/n}<\mu^*, since n≥ℓ>8log⁡T/Δa2n\geq\ell>8\log T/\Delta_a^2 and t≤Tt\leq T. Strict inequality avoids relying on equal-index tie breaking.

For each pair of possible sizes s,n≤ts,n\leq t, Hoeffding bounds each deviation probability by t−4t^{-4}. A conservative union over pairs gives at most 2t2t−4=2t−22t^2t^{-4}=2t^{-2} for that round. Counting the first ℓ\ell choices and summing deviations,

E[Na(T)]≤ℓ+∑t=1T2t−2≤8log⁡TΔa2+1+π23.\mathbb E[N_a(T)]\leq \ell+\sum_{t=1}^{T}2t^{-2} \leq\frac{8\log T}{\Delta_a^2}+1+\frac{\pi^2}{3}.

By the gap lemma, UCB1 satisfies

RT≤∑a:Δa>0(8log⁡TΔa+(1+π23)Δa).R_T\leq\sum_{a:\Delta_a>0}\left(\frac{8\log T}{\Delta_a}+\left(1+\frac{\pi^2}{3}\right)\Delta_a\right).

This is the bound of Auer, Cesa-Bianchi and Fischer. It can exceed TT for a small gap and finite horizon: still valid but uninformative. If rewards lie in [0,1][0,1], also RT≤TR_T\leq T. For a bound without explicit gap dependence, separate arms with Δa≤δ\Delta_a\leq\delta, whose total contribution is at most TδT\delta, from others whose leading contribution is at most 8Klog⁡T/δ8K\log T/\delta. Choosing δ\delta proportional to Klog⁡T/T\sqrt{K\log T/T} gives order O(KTlog⁡T)O(\sqrt{KT\log T}) 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 [0,1][0,1] does not literally apply.

InteractiveCost of learning

Preparing the reproducible bandit simulation.

Compare mean pseudo-regret and variation across seeds for policies on an explicit bandit.

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.

[ ]PythonBrowser
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.')
[ ]PythonBrowser
bernoulli = benchmark('bernoulli')
[ ]PythonBrowser
gaussiano = benchmark('gaussiano')
[ ]PythonBrowser
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()
[ ]PythonBrowser
plot_benchmark(bernoulli, 'Bernoulli')
[ ]PythonBrowser
plot_benchmark(gaussiano, 'Gaussiano')
[ ]PythonBrowser
check_bound(.1)
[ ]PythonBrowser
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

ProofThe cost of each arm
Prove: Prove expected pseudo-regret decomposition for a stationary bandit.
0
The K arms have means μa; action At is chosen using only history available before observing Xt. Conditional on that history and chosen arm, reward has mean μAt. Define Δa = μ*−μa and Na(T) as the number of choices of arm a.

Step 1 of 3. What is the expectation of the round-t reward?

ProofFrom Hoeffding to the UCB1 bound
Prove: Bound choices of a suboptimal UCB1 arm.
0
K independent arms, i.i.d. rewards in [0,1], horizon T≥K, and arm a with gap Δ>0. Each arm is pulled once; thereafter UCB1 maximizes empirical mean plus √(2 log t / n) in round t. Write ℓ=floor(8 log T / Δ²)+1.

Step 1 of 4. If arm a has at least ℓ observations and neither confidence interval fails, why cannot it be chosen?

NumericHow much ETC explores
Two arms have means 0.50 and 0.45; T=10,000. Using the lesson’s rule m=ceil[(4/Δ²) ln(TΔ²/4)], clipped to 1≤m≤floor(T/2), how many times is each arm explored? Use the natural logarithm.
QuizChanging reward units
You multiply all rewards by 100 but leave bonus √(2 log t / n) unchanged. What follows?
CodeUCB1 across replicates
Implement ucb1(env,T). env.means is a finite real matrix in [0,1] of shape (S,K), with positive S,K, holding true means of S stationary replicates. env.pull(actions) receives an integer vector of shape (S,) with one arm per replicate and returns finite rewards in [0,1] of the same shape. T is a nonnegative integer; reject booleans. Maintain separate statistics per replicate: first pull each arm once in index order while rounds remain; then, in global round t starting at 1, choose the maximum empirical mean plus sqrt(2·ln(t)/N), breaking ties by smallest index. Return an (S,T) matrix of cumulative pseudo-regret, with increments max_a means−means[replicate,action]. Do not confuse this with realized regret from noisy rewards. Do not modify env.means, use one pull call per round, and reject invalid T, shapes, or rewards with ValueError. For T=0 return shape (S,0).
import numpy as np

def ucb1(env,T):
  pass
Shift+Enter to run
[ ]Check ETC durationBrowser
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)