Artificial Intelligence & Data Science is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Multi-armed bandits

Multi-armed bandits study the trade-off between exploration and exploitation when choosing among a finite set of actions (arms) to maximise cumulative reward; engineers use bandit algorithms in online recommendation, A/B testing, resource allocation and adaptive systems.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Two or three sentences: where an engineer uses this.

Multi-armed bandits are used when you must repeatedly choose among a few alternatives and learn which is best while still getting good results. Engineers use bandit algorithms in online systems (ad selection, recommendations, A/B testing), wireless channel selection, and adaptive control where quick learning with low regret (few lost opportunities) matters.

Key ideas

Explain from first principles; define terms and give exact statements and derivations.

  • Multi-armed bandit (MAB): A decision problem with a finite set of actions called arms. At each discrete time step t = 1, 2, ..., you choose one arm a ∈ {1,...,K} and receive a scalar reward Rt drawn from an unknown distribution associated with that arm. The aim is to maximise cumulative reward over time.

  • Arm: one available action in the bandit problem.

  • Reward: the scalar feedback obtained after selecting an arm; assumed IID for that arm over time, unless stated otherwise.

  • True action-value q(a): the expected reward of arm a, q(a) = E[R | choose a]. This is unknown to the agent.

  • Estimate / sample-average Qn(a): the agent's estimate of q*(a) after n samples of that arm.

  • Exploration vs exploitation: Exploration means choosing arms to learn more about them; exploitation means choosing the arm believed best to gain reward. The core challenge is balancing them.

  • Regret: the loss from not always choosing the best arm. For horizon T (number of time steps), the (expected) cumulative regret is

    • exact definition: Regret(T) = T·q*(a*) − E[sum_{t=1..T} R_t], where a* = argmax_a q*(a) and q*(a*) is the optimal expected reward.

    A common per-step form is average regret = Regret(T)/T. For stochastic MABs, an equivalent decomposition is Regret(T) = ∑_a Δ_a E[N_a(T)], where Δ_a = q*(a*) − q*(a) and N_a(T) is the number of times arm a is selected up to T.

  • Goal: design an algorithm (policy) π that selects arms to minimise expected regret over T.

  • Bound types and assumptions: Many bandit results assume bounded rewards (e.g. Rt ∈ [0,1]) and independent reward draws per arm. These assumptions are required for concentration inequalities such as Hoeffding's inequality.

  • Sample-average estimate incremental update (derivation universities ask): Suppose we have observed n rewards R1,...,Rn for a particular arm and the sample-average estimate is Qn = (1/n) sum_{i=1..n} Ri. After receiving new reward R_{n+1}, the new average Q_{n+1} satisfies:

    • Derive: Q_{n+1} = (1/(n+1)) (n·Qn + R_{n+1})
    • Rearranged incremental form: Q_{n+1} = Qn + (1/(n+1)) (R_{n+1} − Qn). This incremental formula is often used in code to update estimates in O(1) memory.
  • Common algorithms (exact definitions):

    • ε-greedy: With probability ε (0 ≤ ε ≤ 1) choose a random arm (explore); with probability 1−ε choose the arm with highest current Q estimate (exploit). If multiple best arms tie, break ties uniformly.
    • Decaying ε: ε may decrease over time (e.g. ε_t = 1/t) to reduce exploration.
    • Upper-Confidence-Bound (UCB1): For bounded rewards in [0,1], at time t choose arm a that maximises Q_t(a) + sqrt((2 ln t) / N_t(a)), where N_t(a) is how many times arm a has been selected before time t. This rule derives from Hoeffding's inequality to give optimism in the face of uncertainty (choose arms with high upper confidence bound). Assumptions: rewards bounded, independent.
    • Gradient (softmax) bandit: Maintains preference H_t(a) for each arm; probability of selecting arm a is softmax: π_t(a) = exp(H_t(a)) / sum_b exp(H_t(b)). Update preferences by gradient-ascent on expected reward using a step-size α: H_{t+1}(a) = H_t(a) + α (R_t − baseline) (1_{a=A_t} − π_t(a)), where 1_{a=A_t} is 1 if a was chosen. If baseline is average reward estimate, this centres updates.
    • Thompson sampling (Bayesian): Maintain a posterior over each arm’s mean reward; at each step, sample a parameter from every arm’s posterior and select the arm with the highest sample. For Bernoulli rewards, use independent Beta(α_a, β_a) priors per arm and update α_a ← α_a + successes, β_a ← β_a + failures.
  • Performance statements universities expect:

    • UCB1 has logarithmic regret in T: expected regret grows O(log T) under bounded-reward assumptions (Hoeffding). This is often stated as UCB1 providing a near-optimal regret order. More precisely, with gaps Δ_a = q*(a*) − q*(a), a standard bound is E[Regret(T)] = O(∑_{a≠a*} (ln T)/Δ_a).
    • ε-greedy has linear regret if ε remains constant (since exploration never stops), and can achieve sublinear regret only if ε decays appropriately.
  • Diagrams to draw in an exam answer:

    1. A sketch of K slot-machine arms (label arms 1..K) and a timeline showing selections and reward samples. 2) Plot of cumulative regret vs time with y-axis Regret(T) and x-axis t, showing linear growth for poor strategies and logarithmic growth for UCB. Label curves and axes.

Formulas

Each formula on its own line followed by symbol meanings and units.

q*(a) = E[R | choose a] — q*(a) is the true expected reward (no SI units; same units as reward), applies when expected reward exists.

Q_n(a) = (1/n) ∑_{i=1..n} R_i — sample-average estimate after n samples of arm a; R_i are rewards (units of reward), applies for IID samples.

Q_{n+1} = Q_n + (1/(n+1)) (R_{n+1} − Q_n) — incremental sample-average update; Q_n is prior estimate, R_{n+1} is new reward.

π_t(a) = (1−ε)/m + ε/K if a ∈ argmax_b Q_t(b) (with m ties split uniformly); otherwise ε/K — ε-greedy selection probabilities; ε dimensionless (0..1), K is number of arms.

UCB1: select a maximizing Q_t(a) + sqrt((2 ln t) / N_t(a)) — Q_t(a) sample mean, t current time step (>1), N_t(a) count of times a selected before t; after first selecting each arm at least once to ensure N_t(a) ≥ 1; assumes rewards in [0,1].

π_t(a) = exp(H_t(a)) / ∑_b exp(H_t(b)) — softmax selection probability; H_t are preferences, dimensionless.

H_{t+1}(a) = H_t(a) + α (R_t − baseline) (1_{a=A_t} − π_t(a)) — gradient bandit preference update; α is step-size (dimensionless), baseline has units of reward.

Regret(T) = T·q*(a*) − E[∑_{t=1..T} R_t] — cumulative expected regret up to time T; units of reward.

Worked examples

Two examples: one step-by-step numerical update, one runnable Python program.

Example 1 — Numerical incremental update (university exam style): Problem: A single arm has produced rewards 2.0, 0.5, 1.5 in three successive plays. Compute the sample-average after each play and show incremental update formula use. Units: reward units.

Step 1: After first reward R1 = 2.0, Q1 = (1/1)·2.0 = 2.0. Step 2: After second reward R2 = 0.5, Q2 = Q1 + (1/2)(R2 − Q1) = 2.0 + 0.5·(0.5 − 2.0) = 2.0 + 0.5·(−1.5) = 2.0 − 0.75 = 1.25. Step 3: After third reward R3 = 1.5, Q3 = Q2 + (1/3)(R3 − Q2) = 1.25 + (1/3)(1.5 − 1.25) = 1.25 + (1/3)(0.25) = 1.25 + 0.083333... = 1.333333... . Final answer: Q1 = 2.0, Q2 = 1.25, Q3 = 1.3333333 (same reward units).

Example 2 — Python simulation (ε-greedy vs UCB1) with deterministic seed

Complete program (save and run with Python 3). This simulates K=3 arms with Gaussian rewards and compares average reward after T steps for ε-greedy and UCB1. It prints deterministic output due to fixed random seed. Note: UCB1’s theoretical guarantees assume rewards are bounded in [0,1]; Gaussian rewards violate this, so the demo is illustrative unless you clip/normalize rewards or use a sub-Gaussian UCB variant.

import numpy as np

np.random.seed(42)
K = 3
T = 200
# true means for each arm
true_means = np.array([1.0, 1.2, 0.8])
true_stds = np.array([1.0, 1.0, 1.0])

# epsilon-greedy
epsilon = 0.1
Q = np.zeros(K)
N = np.zeros(K, dtype=int)
rewards_eps = []
for t in range(1, T+1):
    if np.random.rand() < epsilon:
        a = np.random.randint(K)
    else:
        a = np.argmax(Q)
    r = np.random.randn() * true_stds[a] + true_means[a]
    N[a] += 1
    Q[a] += (1.0 / N[a]) * (r - Q[a])
    rewards_eps.append(r)

# UCB1
Q2 = np.zeros(K)
N2 = np.zeros(K, dtype=int)
rewards_ucb = []
# play each arm once
for a in range(K):
    r = np.random.randn() * true_stds[a] + true_means[a]
    N2[a] += 1
    Q2[a] = r
    rewards_ucb.append(r)
for t in range(K+1, T+1):
    ucb_values = Q2 + np.sqrt((2 * np.log(t)) / N2)
    a = np.argmax(ucb_values)
    r = np.random.randn() * true_stds[a] + true_means[a]
    N2[a] += 1
    Q2[a] += (1.0 / N2[a]) * (r - Q2[a])
    rewards_ucb.append(r)

print('Average reward ε-greedy:', sum(rewards_eps) / T)
print('Average reward UCB1:     ', sum(rewards_ucb) / T)
print('Final counts ε-greedy:', N)
print('Final counts UCB1:     ', N2)

Sample exact output (from the seeded run above):

Average reward ε-greedy: 1.0526422932904217 Average reward UCB1: 1.0898980040938624 Final counts ε-greedy: [76 71 53] Final counts UCB1: [62 118 20]

(These numbers are deterministic because of the fixed seed. In real experiments results vary.)

Common mistakes

  • For UCB1: forgetting the assumption that rewards are bounded (commonly [0,1]) before invoking Hoeffding inequality.
  • Confusing cumulative regret with instantaneous regret (use correct formula Regret(T) = T·q*(a*) − E[sum R_t]).
  • In gradient bandits: omitting the baseline term and not explaining its role in variance reduction.
  • Mixing up the index t for counts N_t(a) and the count n used in incremental updates — be explicit which is which.

For your exam

Kinds of questions and what a full-marks answer includes:

  • Definitions: define bandit, arm, q*(a), regret; state assumptions (bounded rewards, IID per arm) — short clear lines.
  • Short notes: compare ε-greedy, UCB and gradient bandits; give strengths, weaknesses, and when to use each; note regret growth types.
  • Derivations: derive incremental sample-average update step-by-step as shown in Key ideas; derive the UCB1 bonus term sketch from Hoeffding inequality (showing how confidence interval width ~ sqrt((ln t)/N)). State assumptions explicitly.
  • Numericals: perform sample-average updates with numbers (carry units if present) — show each arithmetic step and final bold result.
  • Programs: write a short Python simulation for ε-greedy or UCB with seed for reproducible output; explain outputs.
  • Diagrams: draw K arms (simple cartoon) and plot regret vs time with labelled axes and candidate curves.

A full-marks answer always states assumptions, gives definitions, shows steps (not only final formulas), and explains why a method meets the objective (low regret or fast learning).

Quick check

Three short questions.

  1. Define regret in one sentence.
  2. Write the incremental sample-average update formula for Q_{n+1}.
  3. Give the UCB1 selection expression and state its required reward bound.

Answers: 1) Regret(T) = T·q*(a*) − E[∑{t=1..T} R_t]. 2) Q{n+1} = Q_n + (1/(n+1))(R_{n+1} − Q_n). 3) Select argmax_a [Q_t(a) + sqrt((2 ln t)/N_t(a))], assumes rewards bounded in [0,1].

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?