Module contents
Lesson 5 of 37Advanced 100 min

Adversarial bandits and learning with experts: Hedge and EXP3

Study adversarial bandits and expert advice through Hedge, EXP3, entropy-regularized optimization, and non-stationary environments.

After this lesson you can

  • Prove the Hedge regret bound and choose its learning rate.
  • Implement EXP3 with importance-weighted loss estimates and analyze its regret.
  • Explain why deterministic algorithms cannot guarantee sublinear regret against an adversary.
  • Relate Hedge and EXP3 to FTRL and entropy-regularized mirror descent.
  • Adapt bandit algorithms to non-stationary settings using windows, discounting, or restarts.

Before you start

When the environment changes strategy

A detection rule that caught attempts yesterday can lose effectiveness when traffic patterns change. UCB1’s i.i.d. guarantees do not necessarily describe that environment. Adversarial learning replaces a fixed distribution with a sequence of losses and asks how much is lost compared with the best fixed action for that sequence.

The round order is part of the model. A non-anticipating adversary may depend on the history and the algorithm’s current distribution, but fixes the loss vector before seeing its private draw for that round. An adversary that first observes the selected action is more powerful: assigning loss one to that action and zero to the others makes any algorithm lose TT, while some fixed action loses at most T/KT/K. Its realized regret is at least T(1−1/K)T(1-1/K), even if the algorithm randomizes. No sublinear guarantee can ignore that order.

Experts and multiplicative weights

In prediction with expert advice, each expert i∈{1,…,N}i\in\{1,\ldots,N\} suffers loss ℓt,i∈[0,1]\ell_{t,i}\in[0,1] and, at the end of the round, you observe all losses. The algorithm distributes weights pt,ip_{t,i} and pays mixture loss ⟨pt,ℓt⟩\langle p_t,\ell_t\rangle; if it samples an expert, that is its conditional expected loss. The Hedge algorithm uses

Lt−1,i=∑s<tℓs,i,pt,i=e−ηLt−1,i∑je−ηLt−1,j,η>0.L_{t-1,i}=\sum_{s<t}\ell_{s,i},\qquad p_{t,i}=\frac{e^{-\eta L_{t-1,i}}}{\sum_j e^{-\eta L_{t-1,j}}},\quad \eta>0.

An expert with a better history receives more weight, but none disappears in exact arithmetic. To compute the exponents stably, subtract the minimum cumulative loss before exponentiating; this common shift does not change the distribution. With small η\eta the algorithm takes longer to distinguish experts; with large η\eta it can overreact to an alternating sequence.

InteractiveHow weights move

Preparing expert weights.

Change the rate and loss generator to observe the distribution over experts.

A potential-based proof

Define Wt=∑ie−ηLt,iW_t=\sum_i e^{-\eta L_{t,i}}, with W0=NW_0=N. For any fixed expert ii, log⁡(WT/W0)≥−ηLT,i−log⁡N\log(W_T/W_0)\geq-\eta L_{T,i}-\log N. On the other hand,

log⁡WtWt−1=log⁡(∑ipt,ie−ηℓt,i)≤−η⟨pt,ℓt⟩+η28,\log\frac{W_t}{W_{t-1}} =\log\left(\sum_i p_{t,i}e^{-\eta\ell_{t,i}}\right) \leq-\eta\langle p_t,\ell_t\rangle+\frac{\eta^2}{8},

by Hoeffding’s lemma for a variable in [0,1][0,1]. Sum over tt and combine both bounds. Since the inequality holds for every fixed expert,

∑t=1T⟨pt,ℓt⟩−min⁡iLT,i≤log⁡Nη+ηT8.\sum_{t=1}^T\langle p_t,\ell_t\rangle-\min_iL_{T,i} \leq\frac{\log N}{\eta}+\frac{\eta T}{8}.

This is a per-sequence inequality for mixture loss; sampling adds variation to realized loss. If N>1N>1 and TT is known, choosing η=8log⁡N/T\eta=\sqrt{8\log N/T} gives Tlog⁡N/2\sqrt{T\log N/2}. If the horizon is unknown, restart in phases of doubling duration and adjust each phase’s rate: the sum of square roots of their durations remains of the same order. The bound compares with a fixed expert, not a sequence that switches experts for free.

Only one observed loss

In a bandit you see only ℓt,At\ell_{t,A_t}. For pt,i>0p_{t,i}>0, the EXP3 estimator is

ℓ^t,i=1{At=i}ℓt,ipt,i.\widehat\ell_{t,i}=\frac{\mathbf1\{A_t=i\}\ell_{t,i}}{p_{t,i}}.

Conditional on the history and the loss vector fixed before the draw, E[ℓ^t,i]=ℓt,i\mathbb E[\widehat\ell_{t,i}]=\ell_{t,i}. Moreover,

E ⁣[∑ipt,iℓ^t,i 2∣Ht−1,ℓt]=∑iℓt,i2≤K.\mathbb E\!\left[\sum_i p_{t,i}\widehat\ell_{t,i}^{\,2}\mid\mathcal H_{t-1},\ell_t\right] =\sum_i\ell_{t,i}^2\leq K.

Inverse weighting corrects selective observation, but a small probability produces large individual estimates. One version of EXP3 uses exponential weights over these estimated losses. For x≥0x\geq0, e−x≤1−x+x2/2e^{-x}\leq1-x+x^2/2; repeating the potential argument with this inequality and taking expectations yields, for each fixed action,

E ⁣[∑tℓt,At−∑tℓt,i]≤log⁡Kη+ηKT2.\mathbb E\!\left[\sum_t\ell_{t,A_t}-\sum_t\ell_{t,i}\right] \leq\frac{\log K}{\eta}+\frac{\eta KT}{2}.

With η=2log⁡K/(KT)\eta=\sqrt{2\log K/(KT)} the bound is 2KTlog⁡K\sqrt{2KT\log K}. Positive weights hold in exact arithmetic; implementations must watch for numerical underflow. An explicit uniform mixture can impose a probability floor, but changes the rule and requires accounting for its exploration cost. The bound shown uses the version without mixing. The original algorithm and its analysis appear in Auer and colleagues.

The adversarial pseudo-regret against the best fixed arm in expectation is E[Lalg]−min⁡iE[Li]\mathbb E[L_{\mathrm{alg}}]-\min_i\mathbb E[L_i]. With adaptive losses depending on the random history, it is not automatically equal to E[Lalg−min⁡iLi]\mathbb E[L_{\mathrm{alg}}-\min_iL_i]: the minimum can choose a different arm on each trajectory. The inequality above controls the former; guarantees for other comparators and high probability require further arguments. The minimax lower bound from the previous lesson already applies to the adversarial worst case because it includes difficult stochastic environments.

InteractivePenalizing the predictable algorithm

Preparing the precommitted sequence.

A sequence fixed from deterministic UCB is then given to UCB and EXP3; the EXP3 comparison is an estimate over seeds.

One useful construction first simulates deterministic UCB and fixes, in each round, loss one for the arm it would choose and zero for the others. The entire sequence is fixed before running EXP3. UCB loses TT and the best fixed arm loses at most T/KT/K, but EXP3 does not reveal its draw when constructing the vector. If the protocol were changed to penalize the action actually sampled by EXP3, the guarantee would no longer apply.

The same update as optimization

Entropic regularization connects Hedge with follow the regularized leader (FTRL):

pt=arg⁡min⁡p∈ΔN{⟨p,Lt−1⟩+1η∑ipilog⁡pi}.p_t=\arg\min_{p\in\Delta_N}\left\{\langle p,L_{t-1}\rangle+\frac1\eta\sum_i p_i\log p_i\right\}.

The multiplier for constraint ∑ipi=1\sum_i p_i=1 leads to pi∝e−ηLip_i\propto e^{-\eta L_i}. With a fixed rate, the mirror descent step with KL divergence gives the same multiplicative update; with variable rates one must specify which version is implemented. The regularizer favors spread-out distributions, while cumulative losses shift mass toward promising actions.

Tsallis-INF changes the geometry: with exponent 1/21/2, symmetric regularization and importance-weighted losses, it uses ηt=2/t\eta_t=2/\sqrt t and obtains weights of the form

pt,i=4ηt2(L^t−1,i−xt)2,xt<min⁡iL^t−1,i,∑ipt,i=1.p_{t,i}=\frac{4}{\eta_t^2(\widehat L_{t-1,i}-x_t)^2},\qquad x_t<\min_i\widehat L_{t-1,i},\quad\sum_i p_{t,i}=1.

The constant xtx_t is found by solving a scalar equation; bracketed Newton with bisection avoids leaving its domain. For this variant with the IW estimator, theorem 1 gives adversarial pseudo-regret at most 4KT+14\sqrt{KT}+1. Under the self-bounding condition of the same theorem, with its corruption term CC bounded independently of TT, it obtains logarithmic growth in TT. The stochastic case with a unique best arm and positive gaps satisfies the condition with C=0C=0; if CC grows with the horizon, the bound also depends on that growth. Another variance-reduced variant uses a different rate and constants: do not mix their formulas. A finite-horizon graph illustrates experimental data, not proof of either order.

Tracking a changing target

In non-stationary bandits, a sliding window limits memory to recent observations, discounting gradually reduces the weight of old ones, and restarts forget history after a change signal or in preset phases. A short window reacts sooner but estimates from fewer samples. Detectors may be delayed or raise false alarms; performance depends on the pattern of change.

Dynamic regret compares each decision with the best action for its round. Without restrictions on how often or how much the means change, there is no reason to expect uniformly sublinear dynamic regret: the target may change too quickly to learn. A bound against the best fixed arm does not guarantee good tracking of a changing sequence either.

InteractiveMemory versus adaptation

Preparing nonstationary trajectories.

Compare strategies with reproducible means and change the window or temporal pattern.

In repeated games, both players having no regret informs convergence of average play under suitable assumptions. It does not say that the last action or instantaneous policies always converge. We will return to these distinctions when studying games and CFR.

The next cell compares full and partial loss information in [0,1]. Hedge observes the full vector; EXP3, UCB and Thompson observe only the selected arm’s loss. In the adaptive environment, the loss vector is fixed before sampling the action for the round and depends only on its history. Each algorithm therefore generates its own adaptive sequence, so the curves are not a comparison on the same loss vector. Finite-horizon differences do not prove asymptotic bounds.

[ ]Hedge, EXP3 and non-anticipating adversariesBrowser
import math
import random

def softmax_losses(cumulative, eta):
    floor = min(cumulative)
    weights = [math.exp(-eta*(loss-floor)) for loss in cumulative]
    total = sum(weights)
    return [weight/total for weight in weights]

def choose(probabilities, generator):
    u = generator.random()
    cumulative = 0.0
    for i, p in enumerate(probabilities):
        cumulative += p
        if u < cumulative:
            return i
    return len(probabilities)-1

def ucb_action(counts, observed, t, priority):
    unseen = [a for a in priority if counts[a] == 0]
    if unseen:
        return unseen[0]
    # Las observaciones son pérdidas, de modo que se minimiza un LCB.
    return min(priority, key=lambda a: observed[a]/counts[a] - math.sqrt(2*math.log(t)/counts[a]))

def experiment(method, environment, seed, horizon=400, k=3):
    generator = random.Random(seed)
    environment_rng = random.Random(seed + 10000)
    priority = list(range(k))
    generator.shuffle(priority)
    counts = [0]*k
    observed = [0.0]*k
    estimates = [0.0]*k
    total_by_arm = [0.0]*k
    actual = 0.0
    eta = math.sqrt(2*math.log(k)/(k*horizon))
    hedge_eta = math.sqrt(8*math.log(k)/horizon)
    for t in range(1,horizon+1):
        # El adversario decide todas las pérdidas antes del sorteo actual.
        if environment == 'bernoulli':
            losses = [float(environment_rng.random() < p) for p in (.2,.4,.6)]
        elif environment == 'alternante':
            losses = [float((t+a)%k != 0) for a in range(k)]
        elif environment == 'adaptativo':
            target = ucb_action(counts, observed, t, priority)
            losses = [float(a == target) for a in range(k)]
        else:
            raise ValueError('Entorno desconocido')
        if method == 'hedge':
            probabilities = softmax_losses(estimates, hedge_eta)
            action = choose(probabilities, generator)
        elif method == 'exp3':
            probabilities = softmax_losses(estimates, eta)
            action = choose(probabilities, generator)
        elif method == 'ucb':
            action = ucb_action(counts, observed, t, priority)
        elif method == 'thompson':
            # Prior Beta(1,1) para la probabilidad de pérdida.
            action = min(priority, key=lambda a: generator.betavariate(1+observed[a], 1+counts[a]-observed[a]))
        else:
            raise ValueError('Método desconocido')
        loss = losses[action]
        actual += loss
        counts[action] += 1
        observed[action] += loss
        for a in range(k):
            total_by_arm[a] += losses[a]
        if method == 'hedge':
            estimates = [estimates[a]+losses[a] for a in range(k)]
        elif method == 'exp3':
            estimates[action] += loss/probabilities[action]
    return actual-min(total_by_arm)

# Para cualquier vector de pérdidas y distribución con soporte, la media
# exacta del estimador de cada brazo, promediada sobre A, es su pérdida.
p = [.1,.3,.6]
losses = [.2,.5,.9]
for a in range(3):
    average = sum(p[b] * (losses[b]/p[b] if b == a else 0) for b in range(3))
    assert math.isclose(average,losses[a],abs_tol=1e-12)
assert all(math.isfinite(p) and p > 0 for p in softmax_losses([10000,10001,10002], .5))

for env in ('bernoulli','alternante','adaptativo'):
    for method in ('hedge','exp3','ucb','thompson'):
        samples = [experiment(method,env,seed=200+i) for i in range(8)]
        print(env,method,'regret externo medio',round(sum(samples)/len(samples),3),
              'mínimo',round(min(samples),3),'máximo',round(max(samples),3))

Here each trajectory’s external regret compares the algorithm’s cumulative loss with the best fixed arm in hindsight on the loss vector generated in that trajectory. It can be negative. Guarantees for adaptive adversaries depend on the exact regret notion and information order; they do not allow the adversary to see the current random action before fixing its losses. In Bernoulli and alternating settings, environmental randomness is separate from selection randomness. The Thompson policy uses a Bernoulli model, which need not be correct in the adaptive environment.

We implement the IW variant of Tsallis-INF with exponent 1/2, symmetric regularization and ηₜ=2/√t. The source is Zimmert and Seldin, algorithms 1 and 2 and theorem 1. The constant for this variant must not be mixed with that of the variance-reduced estimator. The following method uses bracketed Newton and falls back to bisection if a proposal leaves the interval.

[ ]Tsallis-INF with bracketed Newton normalizationBrowser
import math
import random

def tsallis_weights(cumulative, eta):
    if not cumulative or not math.isfinite(eta) or eta <= 0:
        raise ValueError('Se requieren pérdidas y tasa positiva finita')
    if any(not math.isfinite(value) for value in cumulative):
        raise ValueError('Las pérdidas estimadas deben ser finitas')
    k = len(cumulative)
    minimum = min(cumulative)
    gaps = [value-minimum for value in cumulative]
    # Si d = min(L) - x, d está en [2/eta, 2*sqrt(K)/eta].
    lower = 2/eta
    upper = lower*math.sqrt(k)
    if not all(math.isfinite(gap) for gap in gaps) or not math.isfinite(upper) or lower <= 0:
        raise ValueError('La escala excede el rango de float64')
    d = lower+(upper-lower)/2
    for _ in range(60):
        weights = [(2/(eta*(gap+d)))**2 for gap in gaps]
        error = sum(weights)-1
        if abs(error) < 1e-12:
            break
        if error > 0:
            lower = d
        else:
            upper = d
        derivative = -2*sum(w/(gap+d) for w,gap in zip(weights,gaps))
        candidate = d-error/derivative if math.isfinite(derivative) and derivative != 0 else math.nan
        d = candidate if lower < candidate < upper else lower+(upper-lower)/2
    weights = [(2/(eta*(gap+d)))**2 for gap in gaps]
    if abs(sum(weights)-1)>1e-10 or any(not math.isfinite(w) or w <= 0 for w in weights):
        raise ArithmeticError('No converge la normalización o falta precisión')
    # Normalización de seguridad contra el error de redondeo residual.
    total = sum(weights)
    return [w/total for w in weights]

def draw(probabilities, generator):
    u = generator.random()
    total = 0.0
    for a,p in enumerate(probabilities):
        total += p
        if u < total:
            return a
    return len(probabilities)-1

def tsallis_run(seed, mode, horizon=600):
    action_rng = random.Random(seed)
    env_rng = random.Random(seed+50000)
    estimated = [0.0]*3
    cumulative_loss = [0.0]*3
    actual = 0.0
    pseudo = 0.0
    checkpoints = {}
    means = (.2,.4,.6)
    for t in range(1,horizon+1):
        # El entorno fija el vector sin observar la acción de la ronda.
        if mode == 'estocastico':
            losses = [float(env_rng.random()<mean) for mean in means]
        elif mode == 'alternante':
            losses = [float((t+a)%3 != 0) for a in range(3)]
        else:
            raise ValueError('Entorno desconocido')
        probabilities = tsallis_weights(estimated,2/math.sqrt(t))
        action = draw(probabilities,action_rng)
        estimated[action] += losses[action]/probabilities[action]
        actual += losses[action]
        for a in range(3):
            cumulative_loss[a] += losses[a]
        if mode == 'estocastico':
            pseudo += means[action]-min(means)
        if t in (100,300,600):
            checkpoints[t] = pseudo if mode == 'estocastico' else actual-min(cumulative_loss)
    return checkpoints

# Simetría, raíz y permutación de las coordenadas.
assert tsallis_weights([2.0],1.0)==[1.0]
equal = tsallis_weights([7.0,7.0,7.0],.5)
assert max(abs(w-1/3) for w in equal)<1e-11
v = tsallis_weights([0.0,2.0,7.0],.2)
permuted = tsallis_weights([7.0,0.0,2.0],.2)
assert max(abs(a-b) for a,b in zip(permuted,[v[2],v[0],v[1]]))<1e-11
assert abs(sum(v)-1)<1e-11 and all(w>0 for w in v)
eta = .2
implied_x = [loss-2/(eta*math.sqrt(weight)) for loss,weight in zip([0.,2.,7.],v)]
assert max(implied_x)-min(implied_x)<1e-8

# Verificación exacta de la esperanza de la pérdida importance-weighted.
truth = [.3,.5,.8]
for a in range(3):
    expectation = sum(v[b]*(truth[b]/v[b] if b == a else 0) for b in range(3))
    assert math.isclose(expectation,truth[a],abs_tol=1e-12)

for mode in ('estocastico','alternante'):
    runs = [tsallis_run(400+seed,mode) for seed in range(8)]
    for t in (100,300,600):
        values = [run[t] for run in runs]
        print(mode,'T',t,'regret medio',round(sum(values)/len(values),3),
              'rango',round(min(values),3),round(max(values),3))

In the stochastic environment, the displayed value sums the differences between the chosen arm’s mean loss and that of the best arm. In the alternating environment it compares realized losses with the best fixed arm in hindsight. The eight replications and three horizons check that the implementation works; they do not prove logarithmic or square-root slopes. Under the cited theorem’s assumptions, the IW version has adversarial pseudo-regret bounded by 4√(KT)+1; stochastic guarantees require the result’s conditions and gaps and do not follow from this finite simulation.

Exercises

ProofA potential-based bound
Prove: Prove the Hedge bound for losses in [0,1].
0
There are N≥2 experts, fixed η>0 and T rounds. W₁=Σᵢ exp(−ηL₀,ᵢ)=N, pₜ,ᵢ=exp(−ηLₜ₋₁,ᵢ)/Wₜ y Lₜ,ᵢ=Σₛ≤ₜℓₛ,ᵢ. In each round the loss vector is fixed before the draw and revealed in full afterward.

Step 1 of 3. How do you express the potential ratio in one round?

ProofUnobserved losses
Prove: Prove unbiasedness and bound the second moment of the EXP3 estimator.
0
Condition on the history and the loss vector ℓ∈[0,1]ᴷ fixed before the action. Draw A from distribution p, where pᵢ>0, and define ℓ̂ᵢ=1{A=i}ℓᵢ/pᵢ.

Step 1 of 3. What is the conditional expectation of ℓ̂ᵢ?

NumericChoosing the Hedge rate
For N=100 experts and T=10 000 rounds, minimize the bound ln(N)/η+ηT/8 over η>0. What is the minimum bound? Use the natural logarithm.
QuizWho observes what
An adversary knows the policy and history. Which change invalidates the usual EXP3 adversarial guarantee by allowing it to anticipate the current randomization?
CodeEXP3 with losses fixed before the draw
Implement exp3(loss_fn, K, T, eta, gamma, seed). First call loss_fn(history), where history is an immutable tuple of (action, observed loss) pairs from earlier rounds; it must return a vector of K finite real losses in [0,1]. Then sample an action and observe only its loss. Initialize estimated losses to zero. Each round compute wᵢ=exp(−η(L̂ᵢ−minⱼ L̂ⱼ)), pᵢ=(1−γ)wᵢ/Σw+γ/K; add ℓA/pA only to L̂A. Return (actions, probabilities, estimated) with shapes (T,), (T,K), and (K,). Accept integer K in 1..1000, integer T in 0..100000 and K·T≤2 000 000 to bound the table, integer seed in 0..2³²−1, excluding booleans; finite 0<eta≤10 and 10⁻⁶≤gamma≤1. Reject invalid inputs or losses with ValueError and use numpy.random.default_rng(seed). The same seed and deterministic environment must reproduce the result.
import numpy as np

def exp3(loss_fn,K,T,eta,gamma,seed):
  pass
Shift+Enter to run
[ ]Check the optimized Hedge boundBrowser
import math
print('eta:',math.sqrt(8*math.log(100)/10000))
print('cota:',math.sqrt(5000*math.log(100)))