Module contents
Lesson 3 of 37Advanced 110 min

Lower bounds, KL-UCB and Thompson sampling

Study minimax and Lai–Robbins lower bounds, KL-UCB, Thompson sampling, Gittins indices, and pure exploration for best-arm identification.

After this lesson you can

  • Prove a minimax lower bound via change of measure and Bretagnolle–Huber.
  • Explain Lai–Robbins and calculate its Bernoulli instance constant.
  • Implement KL-UCB and Thompson sampling for Bernoulli and Gaussian rewards.
  • Calculate truncated Gittins indices using calibration and dynamic programming.
  • Design best-arm experiments with successive elimination and halving.

Before you start

How much must learning cost?

UCB1 supplies an upper regret bound. Is there a policy that always needs much less? The answer depends on what is held fixed: in an easy instance some arms are clearly worse; in the worst case means can be so close that identifying them consumes much of the horizon. Lower bounds compare environments producing similar observations but different optimal actions.

Two environments, hard-to-distinguish histories

Let PP and QQ be full-history distributions induced by the same policy in two environments. For any event EE, the Bretagnolle–Huber lemma states

P(E)+Q(Ec)≥12e−KL⁡(P∥Q).P(E)+Q(E^c)\geq\tfrac12e^{-\operatorname{KL}(P\Vert Q)}.

If the algorithm behaves very differently in the two environments, this sum can be small only when history KL is sufficiently large. KL order matters. The bound concerns a sum of two error probabilities in distinct environments, not error probability in one alone.

If environments differ only in arm ii’s distribution, the chain rule and past-based selection give

KL⁡(P∥Q)=EP[Ni(T)] KL⁡(Pi∥Qi).\operatorname{KL}(P\Vert Q) =\mathbb E_P[N_i(T)]\,\operatorname{KL}(P_i\Vert Q_i).

Each observation of that arm provides information; actions of one policy add no independent divergence term once conditioned on history. Small KL does not prove distributions equal: it limits how far decisions based on those data can separate.

InteractiveChange a distribution

Preparing both environments.

Compare accumulated information with average error and its bound when environments are equally likely.

A minimax lower bound

The minimax lower bound says that for every policy a hard instance exists. We construct a Bernoulli family and make constants explicit. Let K≥2K\geq2, T≥K−1T\geq K-1 and ε=18(K−1)/T≤1/8\varepsilon=\tfrac18\sqrt{(K-1)/T}\leq1/8. In P0P_0, arm 1 has mean 1/2+ε1/2+\varepsilon and others 1/21/2. Since expected counts sum to at most TT, some i≠1i\ne1 satisfies E0Ni≤T/(K−1)\mathbb E_0N_i\leq T/(K-1). In PiP_i only that arm changes: its mean becomes 1/2+2ε1/2+2\varepsilon and it is now best.

Take E={Ni(T)≥T/2}E=\{N_i(T)\geq T/2\}. In P0P_0, pulling arm ii costs gap ε\varepsilon; in PiP_i, not pulling it costs at least ε\varepsilon each round. Therefore,

R0≥εT2P0(E),Ri≥εT2Pi(Ec).R_0\geq\tfrac{\varepsilon T}{2}P_0(E),\qquad R_i\geq\tfrac{\varepsilon T}{2}P_i(E^c).

Also kl⁡(1/2,1/2+2ε)=−12log⁡(1−16ε2)≤323ε2\operatorname{kl}(1/2,1/2+2\varepsilon)=-\tfrac12\log(1-16\varepsilon^2)\leq\tfrac{32}{3}\varepsilon^2, because 16ε2≤1/416\varepsilon^2\leq1/4. The chain rule gives KL⁡(P0∥Pi)≤1/6\operatorname{KL}(P_0\Vert P_i)\leq1/6. Applying Bretagnolle–Huber to the sum above, then using max⁡(x,y)≥(x+y)/2\max(x,y)\geq(x+y)/2 gives

max⁡(R0,Ri)≥e−1/664(K−1)T.\max(R_0,R_i)\geq \frac{e^{-1/6}}{64}\sqrt{(K-1)T}.

We construct K−1K-1 alternatives to find an underexplored arm, though ultimately only two environments are compared. Two fixed environments without that argument do not explain factor K\sqrt K. For horizons below arm count, per-round regret is bounded and the overall scale must saturate at TT. This is a worst-case conclusion: it does not say all instances are hard or the bound applies to a policy informed of the instance in advance.

An instance-specific constant

For Bernoulli, write

kl⁡(p,q)=plog⁡pq+(1−p)log⁡1−p1−q,\operatorname{kl}(p,q)=p\log\frac pq+(1-p)\log\frac{1-p}{1-q},

with the continuity convention for zero-mass terms and infinite value when qq assigns zero probability to an outcome possible under pp. If 0<μa<μ∗<10<\mu_a<\mu^*<1 and the policy is uniformly efficient in the considered family, the Lai–Robbins lower bound implies

lim inf⁡T→∞RTlog⁡T≥∑a:Δa>0Δakl⁡(μa,μ∗).\liminf_{T\to\infty}\frac{R_T}{\log T}\geq \sum_{a:\Delta_a>0}\frac{\Delta_a}{\operatorname{kl}(\mu_a,\mu^*)}.

Uniform consistency requires subpolynomial regret on every family instance, not only the selected instance. Thus it does not contradict a policy knowing the best arm in advance for one instance. This is asymptotic, not a bound that must attain that value at every horizon. Statistical separation appears as KL: similar-mean arms need more samples to distinguish. See Lai and Robbins and KL-UCB analysis.

KL-UCB: distribution-aware optimism

For observed mean p^\widehat p after n>0n>0 pulls and budget b(t)>0b(t)>0, the Bernoulli KL-UCB index is

sup⁡{q∈[p^,1]:nkl⁡(p^,q)≤b(t)}.\sup\{q\in[\widehat p,1]:n\operatorname{kl}(\widehat p,q)\leq b(t)\}.

The set is an interval because KL increases in qq for q>p^q>\widehat p. Calculate it by bisection, handling p^=0\widehat p=0 and p^=1\widehat p=1 separately and prioritizing untried arms. For t≥3t\geq3, one analyzed choice is b(t)=log⁡t+3log⁡log⁡tb(t)=\log t+3\log\log t. Under their assumptions Garivier and Cappé show KL-UCB attains the asymptotic lower constant in the Bernoulli case. The index adapts to KL geometry; it does not dominate every finite trajectory.

InteractiveTwo ways to express uncertainty
0.000.250.500.751.00KL-UCBUCB1

Hollow circle: empirical mean. Each bar ends at its index; the plot clips UCB1 at 1 while the readout retains the unclipped index. These are upper bounds, not probabilities that an arm is optimal.

KL-UCB is the largest q in [p,1] satisfying n·kl(p,q) ≤ ln(t)+3 ln ln(t), calculated by bisection. UCB1 uses p+√(2 ln(t)/n). The rules use different budgets; this comparison does not assert universal dominance. The p control is continuous to explore the index: some p and n pairs do not correspond to an integer number of Bernoulli successes. To avoid n≥t, t=1000; n=0 requires trying the arm before either formula. Source: Garivier and Cappé, KL-UCB.

10 %
100
1000
KL-UCB
0.311
Unclipped UCB1
0.472
KL budget / n
0.1271
Compare Hoeffding’s bonus with the KL index for the same count and time budget.

Thompson: sample a hypothesis

In Thompson sampling, maintain a posterior over means, draw a joint sample, and choose an optimal arm for that sample. If the posterior is continuous and ties have zero probability, conditional choice probability for each arm equals its posterior probability of being best. This probability matching does not mean one finite trajectory’s frequency exactly matches that probability.

With independent prior θa∼Beta⁡(αa,βa)\theta_a\sim\operatorname{Beta}(\alpha_a,\beta_a) and Bernoulli data, ss successes and ff failures yield Beta⁡(αa+s,βa+f)\operatorname{Beta}(\alpha_a+s,\beta_a+f). For normal observations with known variance σ2\sigma^2 and prior θ∼N(m0,v0)\theta\sim N(m_0,v_0), the posterior has precision vn−1=v0−1+n/σ2v_n^{-1}=v_0^{-1}+n/\sigma^2 and mean mn=vn(m0/v0+∑jxj/σ2)m_n=v_n(m_0/v_0+\sum_jx_j/\sigma^2). Choice probability depends on the joint posterior; independently sampling marginals breaks it when means are correlated.

InteractivePosterior race

Preparing the posterior race.

Observe changing distributions and compare sample-based choice with posterior probability of being best.

Bayesian regret also averages over an environment prior, while the previous lesson’s frequentist regret fixes the instance and averages histories. These are different questions: a small prior average does not guarantee good performance on each instance. Agrawal and Goyal analyze Thompson for stochastic bandits under specific assumptions; Russo and colleagues present Bayesian interpretation and analyses. A prior with zero support in a region cannot recover it by ordinary Bayesian observation; a very concentrated wrong prior can greatly delay exploration. No robustness result should be extrapolated to every prior.

Agrawal and Goyal’s frequentist argument for two Bernoulli arms with a uniform prior counts suboptimal choices between successive optimal-arm visits. After many suboptimal samples its posterior concentrates; to control time until choosing the optimal arm again, the analysis compares the wait with a geometric variable whose probability depends on a beta tail. It also controls few initial samples and occasions when the suboptimal posterior exceeds a threshold. Under the paper’s assumptions, for positive gap Δ\Delta they obtain expected regret of order O(log⁡T/Δ+1/Δ3)O(\log T/\Delta+1/\Delta^3). This concerns that model, not every prior or reward.

Russo and Van Roy’s information view asks how much expected regret is paid to learn the optimal action A∗A^*. Let rtr_t be expected round regret and It=I(A∗;(At,Rt)∣Ht−1)I_t=I(A^*;(A_t,R_t)\mid\mathcal H_{t-1}) conditional mutual information about that action. If Γt=rt2/It\Gamma_t=r_t^2/I_t is bounded by Γ\Gamma in relevant rounds, Cauchy–Schwarz and the information chain rule imply

BayesRegret⁡(T)=∑t=1Trt≤ΓT∑t=1TIt≤ΓTH(A∗).\operatorname{BayesRegret}(T)=\sum_{t=1}^T r_t \leq \sqrt{\Gamma T\sum_{t=1}^T I_t} \leq \sqrt{\Gamma T H(A^*)}.

Entropy H(A∗)H(A^*) is finite for a finite action set. The first inequality expresses accumulated information-acquisition cost; the second uses that learning about A∗A^* cannot reveal more than its initial uncertainty. If a round has It=0I_t=0, the case must be treated consistently with rt=0r_t=0. The bound depends on model, prior, and algorithm through Γ\Gamma; it does not imply Thompson is optimal in every problem.

Gittins: value of continuing to learn

Each arm’s posterior is a belief state. For independent arms frozen when not selected, one choice per round, and geometrically discounted infinite-horizon rewards, the Gittins index makes choosing a maximal-index arm optimal. These assumptions matter: restless arms, coupled constraints, or finite horizons require different analysis.

Calibration compares continuing one arm with retiring for constant reward λ\lambda. In the surplus problem truncated to hh steps, with posterior Beta⁡(a,b)\operatorname{Beta}(a,b), μ=a/(a+b)\mu=a/(a+b) and discount 0<γ<10<\gamma<1,

Vhλ(a,b)=max⁡ ⁣{0, μ−λ+γ[μVh−1λ(a+1,b)+(1−μ)Vh−1λ(a,b+1)]},V0λ=0.V_h^\lambda(a,b)=\max\!\left\{0,\ \mu-\lambda+\gamma\left[\mu V_{h-1}^\lambda(a+1,b)+(1-\mu)V_{h-1}^\lambda(a,b+1)\right]\right\},\quad V_0^\lambda=0.

Find the λ\lambda threshold where continuation value vanishes by bisection. With finite hh this approximates the infinite-horizon index; it does not prove the resulting policy optimal for a joint finite-horizon problem. For rewards and λ\lambda in [0,1][0,1], the discounted surplus tail is bounded in magnitude by γh/(1−γ)\gamma^h/(1-\gamma); also record bisection error. Retirement is absorbing in this auxiliary problem, not proof that a multi-arm policy must abandon an arm forever.

InteractiveDiscounted policies

Preparing the bandit trajectories.

Compare a stopping-based approximate index with Thompson and UCB under the same simulation protocol.

Explore to identify, not to earn

In best-arm identification, the final recommendation matters, such as its error probability or gap, instead of accumulated exploration regret. With fixed confidence control error and minimize samples; with fixed budget reduce error using limited samples. These objectives differ and require specifying what happens with several best arms.

Successive elimination keeps candidates and removes an arm when its upper bound falls below another’s lower bound, using bounds controlling errors across arms and times. Successive halving allocates budget in phases, keeps a fraction of empirically best arms, and concentrates resources on survivors. Phase samples, rounding, ties, and observation reuse change the algorithm. In hyperparameter tuning a configuration is an arm and budget may mean steps or data; short evaluation need not rank like full training. Hyperband organizes several resource allocations; it does not automatically make that assumption true.

Compare algorithms across 500 replicates with reward sequences and a shared arm permutation per replicate. Permutation prevents systematic advantage for the best arm from lowest-index ties. The Lai–Robbins constant is an asymptotic reference for algorithms satisfying its assumptions; a finite-horizon ratio need not equal it. KL-UCB is applied only to Bernoulli here. Gaussian Thompson uses known observation variance and independent normal prior.

[ ]Thompson, UCB1, and KL-UCBBrowser
import numpy as np

REPS, K, T, SEED = 500, 3, 300, 220301

def kl_bernoulli(p, q):
    p, q = np.broadcast_arrays(np.asarray(p, dtype=float), np.asarray(q, dtype=float))
    if np.any(~np.isfinite(p) | ~np.isfinite(q) | (p < 0) | (p > 1) | (q < 0) | (q > 1)):
        raise ValueError('Probabilidades fuera de [0,1]')
    with np.errstate(divide='ignore', invalid='ignore'):
        first = np.where(p == 0, 0., p * (np.log(p)-np.log(q)))
        second = np.where(p == 1, 0., (1-p)*(np.log1p(-p)-np.log1p(-q)))
    return first+second

def kl_index(means, counts, t):
    means=np.asarray(means,dtype=float)
    counts=np.asarray(counts,dtype=float)
    if (not np.isfinite(t) or t < 3 or t != int(t)
        or np.any(~np.isfinite(means)) or np.any((means<0) | (means>1))
        or np.any(~np.isfinite(counts)) or np.any(counts <= 0)
        or np.any(counts != np.floor(counts))):
        raise ValueError('Visita cada brazo antes de calcular el índice')
    budget = (np.log(t)+3*np.log(np.log(t)))/counts
    lo = np.array(means,dtype=float,copy=True)
    hi = np.ones_like(lo)
    for _ in range(32):
        mid=(lo+hi)/2
        feasible=kl_bernoulli(means,mid)<=budget
        lo=np.where(feasible,mid,lo)
        hi=np.where(feasible,hi,mid)
    return lo

def compare_bernoulli(means, rewards, method, seed=SEED+100):
    reps, arms, horizon = rewards.shape
    means=np.broadcast_to(np.asarray(means), (reps,arms))
    rows=np.arange(reps)
    count=np.zeros((reps,arms),dtype=int)
    success=np.zeros((reps,arms),dtype=float)
    cumulative=np.zeros(reps)
    random=np.random.default_rng(seed)
    best=np.max(means,axis=1)
    for t in range(1,horizon+1):
        if method in ('ucb','kl') and t<=arms:
            action=np.full(reps,t-1,dtype=int)
        elif method=='ts':
            action=np.argmax(random.beta(1+success,1+count-success),axis=1)
        elif method=='ucb':
            action=np.argmax(success/count+np.sqrt(2*np.log(t)/count),axis=1)
        elif method=='kl':
            action=np.argmax(kl_index(success/count,count,t),axis=1)
        else:
            raise ValueError('Método desconocido')
        sample=rewards[rows,action,count[rows,action]]
        count[rows,action]+=1
        success[rows,action]+=sample
        cumulative+=best-means[rows,action]
    return cumulative,count

assert abs(float(kl_bernoulli(0,.8))-np.log(5))<1e-12
assert float(kl_bernoulli(1,1))==0
assert np.isinf(kl_bernoulli(.5,1))
assert kl_index(np.array([1.]),np.array([1]),3)[0]==1.
for invalid in (float('nan'),float('inf')):
    try: kl_bernoulli(invalid,.5)
    except ValueError: pass
    else: raise AssertionError('La KL debe rechazar entradas no finitas')
[ ]Bernoulli: finite-horizon ratioBrowser
bernoulli_means=np.array([.7,.6,.5])
random=np.random.default_rng(SEED)
bernoulli_rewards=(random.random((REPS,K,T))<bernoulli_means[None,:,None]).astype(float)
reference=sum((bernoulli_means[0]-x)/float(kl_bernoulli(x,bernoulli_means[0])) for x in bernoulli_means[1:])
permutations=np.random.default_rng(SEED+991).permuted(np.tile(np.arange(K),(REPS,1)),axis=1)
permuted_means=bernoulli_means[permutations]
bernoulli_rewards=np.take_along_axis(bernoulli_rewards,permutations[:,:,None],axis=1)
print('Constante asintótica de Lai y Robbins:',round(reference,4))
for method in ('ucb','kl','ts'):
    regret, counts=compare_bernoulli(permuted_means,bernoulli_rewards,method)
    se=regret.std(ddof=1)/np.sqrt(REPS)
    print(method,'pseudo-regret medio:',round(regret.mean(),4),
          '± 1,96 EE:',round(1.96*se,4),'regret / ln T:',round(regret.mean()/np.log(T),4))
    assert np.allclose(regret,np.sum(counts*(permuted_means.max(axis=1)[:,None]-permuted_means),axis=1),atol=1e-10)
print('La comparación es a T=300 y no prueba convergencia asintótica.')
[ ]Thompson with Gaussian posteriorBrowser
def compare_gaussian(means,rewards,method,seed=SEED+200):
    reps,arms,horizon=rewards.shape
    means=np.broadcast_to(np.asarray(means),(reps,arms))
    rows=np.arange(reps);count=np.zeros((reps,arms),dtype=int);sums=np.zeros((reps,arms))
    cumulative=np.zeros(reps);random=np.random.default_rng(seed)
    for t in range(1,horizon+1):
        if method=='ucb' and t<=arms:
            action=np.full(reps,t-1,dtype=int)
        elif method=='ts':
            precision=1+count
            posterior_mean=sums/precision
            sample=random.normal(posterior_mean,1/np.sqrt(precision))
            action=np.argmax(sample,axis=1)
        elif method=='ucb':
            action=np.argmax(sums/count+np.sqrt(2*np.log(t)/count),axis=1)
        else:
            raise ValueError('Método desconocido')
        observation=rewards[rows,action,count[rows,action]]
        count[rows,action]+=1;sums[rows,action]+=observation
        cumulative+=means.max(axis=1)-means[rows,action]
    return cumulative,count

gaussian_means=np.array([.5,.3,0.])
random=np.random.default_rng(SEED+1)
gaussian_rewards=random.normal(size=(REPS,K,T))+gaussian_means[None,:,None]
permutations=np.random.default_rng(SEED+992).permuted(np.tile(np.arange(K),(REPS,1)),axis=1)
permuted_means=gaussian_means[permutations]
gaussian_rewards=np.take_along_axis(gaussian_rewards,permutations[:,:,None],axis=1)
for method in ('ucb','ts'):
    regret,counts=compare_gaussian(permuted_means,gaussian_rewards,method)
    se=regret.std(ddof=1)/np.sqrt(REPS)
    print(method,'pseudo-regret medio:',round(regret.mean(),4),'± 1,96 EE:',round(1.96*se,4))
    assert np.allclose(regret,np.sum(counts*(permuted_means.max(axis=1)[:,None]-permuted_means),axis=1),atol=1e-10)
print('Prior N(0,1), varianza observacional conocida 1; las recompensas gaussianas no están en [0,1].')

Calculate a truncated index for one Beta–Bernoulli arm. The retirement problem allows continuing to collect arm rewards or retiring with constant reward each round. Dynamic programming ends after H decisions, so the result is not presented as the exact infinite-horizon index. The classical Gittins theorem requires independent arms, common geometric discount, and arms frozen when not chosen.

[ ]Gittins calibration and finite horizonBrowser
from functools import lru_cache

def continuation(a,b,h,gamma,retirement):
    """Ventaja sobre retirarse ya, con como máximo h tiradas adicionales."""
    @lru_cache(None)
    def value(alpha,beta,remaining):
        if remaining==0: return 0.
        p=alpha/(alpha+beta)
        play=p-retirement+gamma*(p*value(alpha+1,beta,remaining-1)
                                  +(1-p)*value(alpha,beta+1,remaining-1))
        return max(0.,play)
    return value(a,b,h)

@lru_cache(None)
def truncated_index(a,b,h,gamma):
    if min(a,b,h)<1 or not 0<=gamma<1:
        raise ValueError('Parámetros fuera de rango')
    low,high=0.,1.
    for _ in range(32):
        mid=(low+high)/2
        if continuation(a,b,h,gamma,mid)>1e-14: low=mid
        else: high=mid
    return (low+high)/2

@lru_cache(None)
def finite_optimum(a,b,c,d,h,gamma):
    """Valor óptimo exacto de dos brazos independientes en h rondas."""
    if h==0: return 0.
    p=a/(a+b); q=c/(c+d)
    first=p+gamma*(p*finite_optimum(a+1,b,c,d,h-1,gamma)
                   +(1-p)*finite_optimum(a,b+1,c,d,h-1,gamma))
    second=q+gamma*(q*finite_optimum(a,b,c+1,d,h-1,gamma)
                    +(1-q)*finite_optimum(a,b,c,d+1,h-1,gamma))
    return max(first,second)

@lru_cache(None)
def finite_index_policy(a,b,c,d,h,gamma):
    if h==0: return 0.
    p=a/(a+b); q=c/(c+d)
    if truncated_index(a,b,h,gamma)>=truncated_index(c,d,h,gamma):
        return p+gamma*(p*finite_index_policy(a+1,b,c,d,h-1,gamma)
                        +(1-p)*finite_index_policy(a,b+1,c,d,h-1,gamma))
    return q+gamma*(q*finite_index_policy(a,b,c+1,d,h-1,gamma)
                    +(1-q)*finite_index_policy(a,b,c,d+1,h-1,gamma))

gamma=.9
assert abs(truncated_index(2,3,1,gamma)-.4)<1e-8
for h in (1,4,8,12):
    print('Beta(1,1), horizonte',h,'índice truncado:',round(truncated_index(1,1,h,gamma),6))
for state in ((1,1,2,1),(1,2,2,2),(2,3,1,1),(3,3,1,2)):
    optimum=finite_optimum(*state,5,gamma)
    indexed=finite_index_policy(*state,5,gamma)
    assert indexed<=optimum+1e-10
    print('Priors',state,'valor óptimo de 5 rondas:',round(optimum,6),
          'política por índices truncados:',round(indexed,6),'brecha:',round(optimum-indexed,6))
print('La coincidencia o discrepancia en estos casos no prueba optimalidad general a horizonte finito.')

Compare two best-arm identification rules on the same Bernoulli sequences and random arm permutation per replicate. Both receive at most 240 pulls; successive halving may leave some unused through rounding, and successive elimination may stop early if one arm remains. If budget runs out before all but one are eliminated, breaking ties by observed mean is a forced recommendation: it is not assigned the δ error guarantee of the procedure waiting for complete elimination. Metrics are specific to this simulation, not a superiority promise.

[ ]Identify the best armBrowser
import math
import numpy as np

K, BUDGET, REPS, SEED = 8, 240, 200, 220303
means=np.array([.70,.60,.55,.50,.45,.40,.35,.30])
random=np.random.default_rng(SEED)
rewards=(random.random((REPS,K,BUDGET))<means[None,:,None])
permutations=np.random.default_rng(SEED+991).permuted(np.tile(np.arange(K),(REPS,1)),axis=1)

def successive_halving(table,budget):
    k=len(table); rounds=math.ceil(math.log2(k)); active=list(range(k))
    count=[0]*k; sums=[0]*k; used=0
    for phase in range(rounds):
        each=budget//(rounds*len(active))
        if each==0: raise ValueError('Presupuesto insuficiente para una fase')
        for arm in active:
            for _ in range(each):
                sums[arm]+=int(table[arm,count[arm]])
                count[arm]+=1; used+=1
        # Empates por índice menor; se usan todas las muestras acumuladas.
        active.sort(key=lambda a:(-sums[a]/count[a],a))
        active=active[:math.ceil(len(active)/2)]
    return active[0],used,len(active)

def successive_elimination(table,budget,delta=.05):
    k=len(table);active=list(range(k));count=[0]*k;sums=[0]*k;used=0
    while len(active)>1 and used+len(active)<=budget:
        for arm in active:
            sums[arm]+=int(table[arm,count[arm]])
            count[arm]+=1;used+=1
        # Unión conservadora sobre brazos, tamaños de muestra y ambas colas.
        radii={a:math.sqrt(math.log(4*k*budget**2/delta)/(2*count[a])) for a in active}
        best_lower=max(sums[a]/count[a]-radii[a] for a in active)
        active=[a for a in active if sums[a]/count[a]+radii[a]>=best_lower]
    if not active or any(count[a]==0 for a in active):
        raise ValueError('Presupuesto insuficiente')
    recommendation=min(active,key=lambda a:(-sums[a]/count[a],a))
    return recommendation,used,len(active)

for method in (successive_halving,successive_elimination):
    outcomes=[method(rewards[i,permutations[i]],BUDGET) for i in range(REPS)]
    best_positions=np.argmax(means[permutations],axis=1)
    successes=sum(chosen==best_positions[i] for i,(chosen,_,_) in enumerate(outcomes))
    fraction=successes/REPS
    se=math.sqrt(fraction*(1-fraction)/REPS)
    used=np.array([n for _,n,_ in outcomes])
    remaining=np.array([n for _,_,n in outcomes])
    assert np.all(used<=BUDGET)
    print(method.__name__,'identifica el mejor:',successes,'/',REPS,
          'frecuencia:',round(fraction,4),'error estándar:',round(se,4),
          'tiradas medias:',round(float(used.mean()),2),
          'brazos restantes medios:',round(float(remaining.mean()),2))
print('200 réplicas con recompensas y permutaciones comunes; el mejor brazo único tiene media 0,70.')
print('Un resultado finito no demuestra una cota asintótica ni garantiza una clasificación en cada ejecución.')

Exercises

ProofA family of hard environments
Prove: Prove the minimax bound by constructing a Bernoulli family and applying Bretagnolle–Huber.
0
K≥2, T≥K−1. Under P0 arm 1 has mean 1/2+ε and others 1/2, with ε=(1/8)√((K−1)/T). The policy is the same in every environment.

Step 1 of 4. How do you choose a hard alternative for that policy?

NumericAn instance-dependent constant
Three Bernoulli arms have means 0.9, 0.8 and 0.5. Calculate the sum of Δa/KL(μa,0.9) for suboptimal arms. Use natural logarithms.
NumericA posterior draw
Starting with Beta(1,1), you observe 7 successes in 10 Bernoulli pulls. What is the posterior probability a Thompson draw exceeds 0.8?
QuizBatch decisions
A system makes 1000 assignments before receiving any batch reward. What advantage can Thompson offer over repeating one deterministic maximum calculated initially?
CodeInvert a divergence
Implement kl_ucb_index(mean,n,t) for a finite Bernoulli mean in [0,1], an integer 1≤n≤10⁹, and an integer round 3≤t≤10¹², rejecting booleans. Return the largest q in [mean,1] satisfying n·kl(mean,q)≤ln(t)+3·ln(ln(t)), with absolute tolerance 1e−9. Define divergence limits at 0 and 1, avoid log(0), and raise ValueError for invalid inputs. The function neither calculates nor uses future rewards.
def kl_ucb_index(mean, n, t):
  pass
Shift+Enter to run
[ ]Check exercise figuresBrowser
import math

def kl_bernoulli_exercise(p,q):
    return p*math.log(p/q)+(1-p)*math.log((1-p)/(1-q))

kl_08=kl_bernoulli_exercise(.8,.9)
kl_05=kl_bernoulli_exercise(.5,.9)
constant=.1/kl_08+.4/kl_05
tail=sum(math.comb(11,j)*.8**j*.2**(11-j) for j in range(8))
print('KL(0,8 || 0,9):',kl_08,'KL(0,5 || 0,9):',kl_05)
print('Constante de Lai y Robbins:',constant,'cola de Beta(8,4) sobre 0,8:',tail)