Multi-armed Bandits
The exploration–exploitation trade-off in its simplest setting — one situation, k actions, evaluative feedback. This chapter introduces the incremental update rule, step-size choices, and four ways to explore that reappear throughout the book.
- Evaluative vs instructive feedback.
- Sample-average estimate (2.1), incremental form (2.3) and the general rule (2.4).
- Constant vs decreasing step size: exponential recency-weighted average (2.6), the convergence conditions (2.7), when each is appropriate.
- Probability of choosing the greedy action under ε-greedy: $1-\varepsilon+\varepsilon/k$.
- How each exploration method works, its hyperparameter, and its weaknesses (especially for nonstationary problems).
- Gradient-bandit update (2.12), the role of the baseline, and why it is stochastic gradient ascent.
- Reading a parameter study (inverted-U curves).
2.1 The k-armed bandit problem
Evaluative feedback tells you how good the action you took was, but not whether it was the best — it depends entirely on the action taken. Instructive feedback tells you the correct action regardless of what you did (supervised learning). Evaluative feedback is what creates the need for active exploration.
You repeatedly choose among $k$ actions. After each choice you receive a numerical reward drawn from a stationary distribution that depends on the action. Goal: maximise expected total reward over, say, 1000 time steps. The setting is nonassociative — there is only one situation.
$Q_t(a)$ is our estimate of $q_*(a)$ at time $t$. Actions with the highest estimate are greedy. Choosing one is exploiting; choosing a non-greedy action is exploring. Exploitation maximises reward on the one step; exploration may give greater total reward in the long run. You cannot do both with one selection — hence the "conflict". The book's aim is not to balance them optimally (methods that do rely on strong assumptions about stationarity and priors) but simply to balance them at all.
2.2 Action-value methods
If the denominator is zero, use a default (e.g. 0). By the law of large numbers $Q_t(a)\to q_*(a)$ as the count goes to infinity.
ε-greedy: behave greedily with probability $1-\varepsilon$; with probability $\varepsilon$ pick an action uniformly at random (which may itself be the greedy one). In the limit every action is sampled infinitely often, so all $Q_t(a)\to q_*(a)$ and the probability of choosing the optimal action converges to more than $1-\varepsilon$.
Two actions, $\varepsilon=0.5$: P(greedy) $= 0.5 + 0.5/2 = \mathbf{0.75}$.
2.3 The 10-armed testbed
- 2000 randomly generated bandit problems, $k=10$. True values $q_*(a)\sim\mathcal N(0,1)$; rewards $R_t\sim\mathcal N(q_*(A_t),1)$.
- Each run = 1000 steps on one problem; curves are averaged over the 2000 runs.
- Best possible average reward ≈ 1.54 (the expected maximum of 10 standard normals).
| Method (sample averages, $Q_1=0$) | What happens (Figure 2.2) |
|---|---|
| Greedy ($\varepsilon=0$) | Improves slightly faster at the very start, then levels off at reward ≈ 1. Finds the optimal action in only ~⅓ of tasks — it gets stuck after disappointing early samples of the best arm. |
| $\varepsilon=0.1$ | Explores more, finds the optimal action earlier, but never selects it more than 91% of the time ($0.9 + 0.1/10$). |
| $\varepsilon=0.01$ | Improves more slowly, but eventually beats $\varepsilon=0.1$ on both measures (asymptotically 99.1% optimal). |
One can also reduce ε over time to get the best of both. The advantage of ε-greedy depends on the task:
- Higher reward variance (e.g. 10) → more exploration needed → ε-greedy does even better relative to greedy.
- Zero variance → greedy learns each value after one try and may do best.
- Nonstationary task → exploration is needed even in the deterministic case. Nonstationarity is the common case in RL (even a stationary task looks nonstationary while the policy is changing).
Pick a preset (changing it re-runs). Each method runs on the same set of bandit problems. More runs → smoother curves (the book uses 2000).
Average reward
% optimal action
2.4 Incremental implementation
Storing every reward and re-averaging needs growing memory and computation. Instead, for one action, with $Q_n$ the estimate after $n-1$ rewards:
It holds even for $n=1$ (giving $Q_2=R_1$ for any $Q_1$). Memory: just $Q_n$ and $n$. This is an instance of the most important pattern in the book:
$[\textit{Target}-\textit{OldEstimate}]$ is an error; we take a step toward the (possibly noisy) target. Here the step size is $1/n$, which changes from step to step. The book writes the step size as $\alpha$ or $\alpha_t(a)$.
Initialize, for a = 1 to k: Q(a) ← 0 N(a) ← 0 Loop forever: A ← argmax_a Q(a) with probability 1 − ε (breaking ties randomly) a random action with probability ε R ← bandit(A) N(A) ← N(A) + 1 Q(A) ← Q(A) + (1 / N(A)) · [R − Q(A)]
1/N(A) by a constant α for nonstationary problems (§2.5). Constant memory and constant per-step computation.2.5 Tracking a nonstationary problem — constant vs varying step size
When reward probabilities change over time, it makes sense to weight recent rewards more heavily. The most popular way: a constant step size $\alpha\in(0,1]$.
Unrolling the recursion shows $Q_{n+1}$ is a weighted average of past rewards and the initial estimate:
The weights sum to 1: $(1-\alpha)^n + \sum_{i=1}^n\alpha(1-\alpha)^{n-i}=1$. The weight on $R_i$ decays exponentially with how many rewards ago ($n-i$) it was seen. If $\alpha=1$, all weight goes on the latest reward $R_n$ (using $0^0=1$).
Convergence conditions (stochastic approximation)
Let $\alpha_n(a)$ be the step size used for the $n$-th reward of action $a$. Convergence with probability 1 is assured if
- First condition: steps are large enough to eventually overcome any initial conditions or random fluctuations.
- Second condition: steps eventually become small enough to assure convergence.
| Sample average $\alpha_n = 1/n$ | Constant $\alpha$ | |
|---|---|---|
| Satisfies (2.7)? | Both conditions ✓ | First ✓, second ✗ ($\sum\alpha^2=\infty$) |
| Converges? | Yes, to $q_*(a)$ w.p. 1 (law of large numbers) | No — keeps fluctuating in response to recent rewards |
| Weighting of past rewards | Equal weight $1/n$ to every reward | Exponentially more weight on recent rewards |
| Initial-value bias | Disappears once the action is tried (weight on $Q_1$ is 0 after one update) | Permanent but decreasing: weight $(1-\alpha)^n$ |
| Stationary problems | Ideal | Good but noisier asymptotically |
| Nonstationary problems | Poor — reacts ever more slowly (treats the beginning of time as special) | Tracks change — what we want |
| In practice | Used in theory | Used in most applications and empirical research |
Problems that are effectively nonstationary are the most common in RL. Also, step-size sequences that meet (2.7) often converge very slowly or need considerable tuning, so they are "seldom used in applications and empirical research".
"Any decreasing step size converges." — No. $\alpha_n = 1/n^2$ decreases but violates the first condition ($\sum 1/n^2<\infty$): steps shrink too fast and the estimate can stall before reaching $q_*$. $\alpha_n=1/n$ and $\alpha_n = 1/n^{p}$ with $\tfrac12 \lt p\le1$ satisfy both.
Exercise 2.4 — general step-size weighting
With varying step sizes $\alpha_1,\alpha_2,\dots$:
With $\alpha_j=\alpha$ this reduces to (2.6); with $\alpha_j=1/j$ every weight becomes $1/n$ and the weight on $Q_1$ becomes 0.
Exercise 2.7 — the unbiased constant-step-size trick
$\bar o_n = 1-(1-\alpha)^n$, so $\beta_1 = 1$ — the first update sets $Q_2=R_1$ and wipes out $Q_1$ (no initial bias). As $n\to\infty$, $\bar o_n\to1$ and $\beta_n\to\alpha$ — it becomes an exponential recency-weighted average (keeps the tracking advantage).
All $q_*(a)$ start equal (0) and take independent random walks: each step add $\mathcal N(0, 0.01^2)$. Both agents use ε = 0.1.
% optimal action
2.6 Optimistic initial values
All methods so far are biased by their initial estimates $Q_1(a)$. For sample averages the bias disappears once every action is selected; for constant α it is permanent (decaying as $(1-\alpha)^n$). Usually harmless, sometimes helpful — the initial values become user-set parameters that can encode prior knowledge.
Trick: set $Q_1(a)=+5$ on the testbed (wildly optimistic, since $q_*\sim\mathcal N(0,1)$). Whatever is tried, the reward is "disappointing", so the learner switches to other actions. All actions are tried several times even with purely greedy selection.
- Figure 2.3 (α = 0.1): optimistic greedy ($Q_1=5,\varepsilon=0$) is worse at first (explores more) but eventually better than realistic ε-greedy ($Q_1=0,\varepsilon=0.1$) because its exploration dies out.
- Limitation: the drive to explore is temporary. Not suited to nonstationary problems — "the beginning of time occurs only once". (The same criticism applies to sample averages, which also treat the beginning specially.)
Early on, every action looks great, so the optimistic greedy agent cycles through all 10 actions. After each has been tried about once, the optimal action — whose reward was the least disappointing on average — tends to have the highest estimate and is picked by many runs at the same step → a spike in % optimal. Picking it lowers its estimate below the still-optimistic others, so the agent moves away → a dip. Because all runs share this synchronised schedule, the oscillation shows up in the average.
2.7 Upper-confidence-bound (UCB) action selection
ε-greedy explores indiscriminately. Better: prefer non-greedy actions according to their potential for being optimal — how close their estimates are to maximal and how uncertain they are.
- $N_t(a)$ = times $a$ was selected before $t$. If $N_t(a)=0$, $a$ is treated as maximising (try every action once first).
- $c>0$ controls the degree of exploration (the confidence level).
- The square-root term measures uncertainty: selecting $a$ increases $N_t(a)$ → bonus shrinks; selecting other actions increases $t$ → bonus grows. Because of $\ln t$, the increases get smaller over time but are unbounded — every action is eventually selected, but low-value or frequently tried actions with decreasing frequency.
- Deterministic exploration (no randomness), unlike ε-greedy.
Performs well on bandits (Fig 2.4: better than ε-greedy except in the first $k$ steps), but is hard to extend beyond bandits: (1) nonstationary problems need more complex methods than §2.5; (2) large state spaces / function approximation — counts $N_t(a)$ don't make sense. "In these more advanced settings the idea of UCB action selection is usually not practical."
In steps 1–10 each untried action is selected once ($N=0$ counts as maximising). At step 11 all $N_t(a)=1$, so the bonuses are equal and UCB picks the action with the best single sample — often the optimal one → reward spikes. That action's $N$ becomes 2, so its bonus $c\sqrt{\ln t/2}$ falls well below the others' $c\sqrt{\ln t/1}$; with $c=2$ the bonus difference dominates the value differences, so UCB switches to other actions → reward drops. With $c=1$ the bonus matters less, so the spike (and subsequent drop) is smaller.
2.8 Gradient bandit algorithms
Instead of estimating action values, learn a numerical preference $H_t(a)\in\mathbb R$. Only relative preferences matter (adding 1000 to all changes nothing). Action probabilities follow a soft-max (Gibbs/Boltzmann) distribution:
Initially all $H_1(a)=0$ (equal probabilities). After selecting $A_t$ and receiving $R_t$:
Compactly: $H_{t+1}(a) = H_t(a) + \alpha(R_t-\bar R_t)(\mathbb 1_{a=A_t}-\pi_t(a))$ for all $a$.
- $\bar R_t$ = average of rewards so far — the baseline. Reward above baseline → probability of $A_t$ goes up; below → goes down. Non-selected actions move the opposite way.
- Figure 2.5: with $q_*$ near +4, the baseline instantly adapts and performance is unaffected; without a baseline ($\bar R_t=0$) performance is significantly degraded.
Why it is stochastic gradient ascent
Exact gradient ascent on expected reward $\E[R_t]=\sum_x\pi_t(x)q_*(x)$ would be $H_{t+1}(a)=H_t(a)+\alpha\,\partial\E[R_t]/\partial H_t(a)$ (2.13). Using $\partial\pi_t(x)/\partial H_t(a)=\pi_t(x)(\mathbb 1_{a=x}-\pi_t(a))$ and the fact that $\sum_x\partial\pi_t(x)/\partial H_t(a)=0$ (so any baseline $B_t$ independent of $x$ can be subtracted), the gradient equals
So the expected update of (2.12) equals the true gradient → robust convergence. The baseline does not change the expected update, only its variance (and hence the speed of learning). Any baseline that does not depend on the selected action works; the reward average is simple and works well.
With two actions, $\pi(1)=\dfrac{e^{H(1)}}{e^{H(1)}+e^{H(2)}}=\dfrac{1}{1+e^{-(H(1)-H(2))}}=\sigma\big(H(1)-H(2)\big)$ — the logistic sigmoid of the preference difference.
2.9 Associative search (contextual bandits)
So far, tasks were nonassociative: find (or track) one best action. In associative search you face one of several bandit tasks each step and receive a clue (e.g. the machine's colour) about which. You learn a policy: situation → best action.
| k-armed bandit | Contextual bandit | Full RL problem | |
|---|---|---|---|
| Multiple situations? | No | Yes | Yes |
| Learns a policy? | No (one best action) | Yes | Yes |
| Actions affect next situation? | No | No — only immediate reward | Yes |
Case A: values (10, 20); case B: (90, 80), each with probability 0.5. Not told the case: action 1 gives $0.5\cdot10+0.5\cdot90=50$, action 2 gives $0.5\cdot20+0.5\cdot80=50$ — best expected reward is 50, any behaviour. Told the case: choose action 2 in A and action 1 in B: $0.5\cdot20+0.5\cdot90=\mathbf{55}$.
2.10 Summary — comparing the methods
| Method | How it explores | Hyperparameter(s) | Strengths | Weaknesses |
|---|---|---|---|---|
| Greedy | Doesn't | — | Fast initially | Gets stuck on sub-optimal actions |
| ε-greedy | Random action with prob. ε — indiscriminate | ε (and α or 1/n) | Simple; extends to full RL; works with nonstationarity | Wastes exploration on clearly bad actions; caps % optimal at $1-\varepsilon+\varepsilon/k$ |
| Optimistic init. | "Disappointment" with optimistic estimates | $Q_1$ (with α) | Even greedy explores; very simple | Temporary — useless for nonstationary; needs knowledge of reward scale |
| UCB | Deterministic bonus for uncertainty | $c$ | Best on the testbed; explores smartly | Hard with nonstationarity and large state spaces / function approximation |
| Gradient bandit | Stochastic soft-max over preferences | α (baseline choice) | Invariant to reward shifts (with baseline); is SGA; leads to policy-gradient methods | Sensitive to α; needs a baseline for good performance |
Parameter study (Figure 2.6)
Each point = average reward over the first 1000 steps (∝ area under the learning curve) for one algorithm at one parameter value; parameters vary by factors of two on a log scale. All curves are inverted-U: best at an intermediate value, neither too large nor too small. Assess a method by its best performance and its sensitivity — all are fairly insensitive (good over about an order of magnitude). On this problem UCB performs best.
x-axis is the algorithm's own parameter (ε, α, c, or Q₁) on a log₂ scale. Optimistic greedy uses α = 0.1. Takes a few seconds.
Beyond the simple methods
- Gittins indices — a special action value giving optimal solutions in some special cases, but require complete knowledge of the prior distribution of problems; don't generalise to full RL.
- Bayesian methods — keep a posterior over action values. Thompson (posterior) sampling: pick each action with its posterior probability of being best; often performs like the best distribution-free methods.
- The Bayes-optimal balance can in principle be computed over the information state, but the tree explodes ($2^{2000}$ leaves for 2 actions, 2 rewards, 1000 steps).
Hyperparameters in this chapter
| Parameter | Used by | Too small | Too large | Typical |
|---|---|---|---|---|
| $\varepsilon$ | ε-greedy | Slow discovery of the best action; may get stuck | Wastes steps on random actions; caps % optimal at $1-\varepsilon+\varepsilon/k$ | 0.01 – 0.1 (testbed peak ≈ 1/16); or decay over time |
| $\alpha$ (value) | constant-step estimates | Slow learning / slow tracking | Noisy estimates, never settle | 0.1 |
| $1/n$ | sample average | Not tuned; converges on stationary problems but adapts ever more slowly | stationary tasks | |
| $Q_1$ | all value methods | Realistic (0): no exploration bonus | Very optimistic: long initial exploration phase | 0; optimistic for stationary tasks (Fig 2.3 uses +5; the parameter study peaks near 1–2) |
| $c$ | UCB | Behaves like greedy | Over-explores | ≈ 1–2 |
| $\alpha$ (preference) | gradient bandit | Slow preference change | Premature commitment / instability | ≈ 0.1 – 0.4 |
| baseline $\bar R_t$ | gradient bandit | Doesn't change expected update; a good baseline reduces variance. No baseline when rewards are far from 0 → much slower learning | running average of rewards | |
Self-test
Ex 2.2 — Bandit example. k = 4, ε-greedy, sample averages, $Q_1=0$. A₁=1,R₁=−1; A₂=2,R₂=1; A₃=2,R₃=−2; A₄=2,R₄=2; A₅=3,R₅=0. On which steps did the ε case definitely occur? Possibly occur?
Track estimates: after step 1, $Q=(-1,0,0,0)$. Step 2: action 2 is among the greedy {2,3,4} — could be greedy. $Q(2)=1$. Step 3: action 2 is greedy. $Q(2)=(1-2)/2=-0.5$, so $Q=(-1,-0.5,0,0)$. Step 4: chose 2 but greedy are {3,4} → definitely random. $Q(2)=(1-2+2)/3=1/3$. Step 5: chose 3 but greedy is 2 → definitely random. The ε case could have occurred on every step (1–5), since a random selection can also land on a greedy action.
Ex 2.3 — In Figure 2.2, which method is best in the long run, and by how much?
$\varepsilon=0.01$. Asymptotic P(optimal): $0.99+0.001=99.1\%$ vs $0.9+0.01=91\%$ for $\varepsilon=0.1$. Expected reward per step ≈ $1.54\times$P(optimal) plus a small amount from random arms (mean ≈ 0): about 1.53 vs 1.40 — roughly 9–10% more reward per step, and more cumulative reward in the long run (after the slow start).
State the two step-size convergence conditions and say which one constant α violates. Why is that sometimes good?
$\sum\alpha_n=\infty$ and $\sum\alpha_n^2<\infty$. Constant α violates the second, so estimates never fully converge and keep responding to recent rewards — exactly what's needed for tracking a nonstationary problem.
With $\alpha=0.1$, what weight does the reward from 10 steps ago get in $Q_{n+1}$? What weight remains on $Q_1$ after 20 updates?
$R_{n-10}$ gets $\alpha(1-\alpha)^{10}=0.1\times0.9^{10}\approx0.0349$. Weight on $Q_1$ after 20 updates: $0.9^{20}\approx0.122$.
Why does optimistic initialisation not help on nonstationary problems?
Its exploration is driven by the initial values, which are quickly "used up". When the task later changes and renewed exploration is needed, nothing drives it. Any method focusing on initial conditions can't help with general nonstationarity.
How does UCB's exploration differ from ε-greedy's?
ε-greedy explores randomly and indiscriminately — all non-greedy actions equally likely. UCB explores deterministically, favouring actions that are both nearly greedy and uncertain (few samples), via the bonus $c\sqrt{\ln t/N_t(a)}$.
In the gradient bandit, what happens to $H$ of non-selected actions when $R_t>\bar R_t$?
They decrease, each by $\alpha(R_t-\bar R_t)\pi_t(a)$, while the selected action's preference increases by $\alpha(R_t-\bar R_t)(1-\pi_t(A_t))$. Total change across actions sums to zero.
Does the choice of baseline change what the gradient bandit converges to? What does it change?
No — any baseline independent of the selected action leaves the expected update equal to the gradient. It changes the variance of the updates and therefore the rate of learning (Fig 2.5).
What is a parameter study, and what does the inverted-U shape tell you?
A plot of a performance summary (e.g. average reward over 1000 steps) against each algorithm's parameter. Inverted-U: performance peaks at an intermediate value; too little and too much exploration/learning rate both hurt. Width of the U shows sensitivity.
Why is the bandit problem called "nonassociative", and what makes the full RL problem different from a contextual bandit?
Nonassociative: one situation, so no need to associate actions with situations. Contextual bandits have several situations but actions affect only immediate reward; in full RL actions also affect the next situation (state).
Chapter quiz — check your understanding
Scored quiz: pick an answer (or type a number) to get instant feedback and an explanation. Questions marked Exam-style give you values to interpret (sweeps, logs, returns, learning curves), the way exam problems do. Your best score is saved in this browser and shown on the home page. "Shuffle & restart" re-orders the questions.