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 , while some fixed action loses at most . Its realized regret is at least , even if the algorithm randomizes. No sublinear guarantee can ignore that order.
Experts and multiplicative weights
In prediction with expert advice, each expert suffers loss and, at the end of the round, you observe all losses. The algorithm distributes weights and pays mixture loss ; if it samples an expert, that is its conditional expected loss. The Hedge algorithm uses
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 the algorithm takes longer to distinguish experts; with large it can overreact to an alternating sequence.
Preparing expert weights.
A potential-based proof
Define , with . For any fixed expert , . On the other hand,
by Hoeffding’s lemma for a variable in . Sum over and combine both bounds. Since the inequality holds for every fixed expert,
This is a per-sequence inequality for mixture loss; sampling adds variation to realized loss. If and is known, choosing gives . 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 . For , the EXP3 estimator is
Conditional on the history and the loss vector fixed before the draw, . Moreover,
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 , ; repeating the potential argument with this inequality and taking expectations yields, for each fixed action,
With the bound is . 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 . With adaptive losses depending on the random history, it is not automatically equal to : 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.
Preparing the precommitted sequence.
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 and the best fixed arm loses at most , 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):
The multiplier for constraint leads to . 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 , symmetric regularization and importance-weighted losses, it uses and obtains weights of the form
The constant 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 . Under the self-bounding condition of the same theorem, with its corruption term bounded independently of , it obtains logarithmic growth in . The stochastic case with a unique best arm and positive gaps satisfies the condition with ; if 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.
Preparing nonstationary trajectories.
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.
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.
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
Step 1 of 3. How do you express the potential ratio in one round?
Step 1 of 3. What is the conditional expectation of ℓ̂ᵢ?
import numpy as np
def exp3(loss_fn,K,T,eta,gamma,seed):
pass
import math
print('eta:',math.sqrt(8*math.log(100)/10000))
print('cota:',math.sqrt(5000*math.log(100)))