Chapter 2 · Book pp. 25–45

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.

Sample average vs constant α ε-greedy Optimistic initial values UCB Gradient bandit Contextual bandits
Exam focus for this chapter

2.1 The k-armed bandit problem

Evaluative vs instructive feedback

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_*(a) \doteq \E[R_t \mid A_t = a]$$
True action value§2.1

$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

$$Q_t(a) \doteq \frac{\text{sum of rewards when } a \text{ taken prior to } t}{\text{number of times } a \text{ taken prior to } t} = \frac{\sum_{i=1}^{t-1} R_i\,\mathbb 1_{A_i=a}}{\sum_{i=1}^{t-1}\mathbb 1_{A_i=a}}$$
Sample-average action value(2.1)

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.

$$A_t \doteq \argmax_a Q_t(a)$$
Greedy action selection (ties broken arbitrarily)(2.2)

ε-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$.

$$\Pr\{\text{greedy action}\} = (1-\varepsilon) + \frac{\varepsilon}{k}, \qquad \Pr\{\text{a specific non-greedy action}\} = \frac{\varepsilon}{k}$$
ε-greedy selection probabilitiesEx 2.1
Exercise 2.1

Two actions, $\varepsilon=0.5$: P(greedy) $= 0.5 + 0.5/2 = \mathbf{0.75}$.

2.3 The 10-armed testbed

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:

Try it: the 10-armed testbed (Figures 2.2–2.5)

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:

$$Q_{n+1} = \frac1n\sum_{i=1}^{n}R_i = \frac1n\Big(R_n + (n-1)Q_n\Big) = Q_n + \frac1n\big[R_n - Q_n\big]$$
Incremental sample average(2.3)

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{NewEstimate} \leftarrow \textit{OldEstimate} + \textit{StepSize}\,\big[\textit{Target} - \textit{OldEstimate}\big]$$
General incremental update rule(2.4)

$[\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)$.

A simple bandit algorithmε-greedysample average
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)]
Replace 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]$.

$$Q_{n+1} \doteq Q_n + \alpha\big[R_n - Q_n\big]$$
Constant step-size update(2.5)

Unrolling the recursion shows $Q_{n+1}$ is a weighted average of past rewards and the initial estimate:

$$Q_{n+1} = (1-\alpha)^n Q_1 + \sum_{i=1}^{n}\alpha(1-\alpha)^{\,n-i} R_i$$
Exponential recency-weighted average(2.6)

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$).

See it: how much weight each past reward gets

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

$$\sum_{n=1}^{\infty}\alpha_n(a) = \infty \qquad\text{and}\qquad \sum_{n=1}^{\infty}\alpha_n^2(a) < \infty$$
Robbins–Monro step-size conditions(2.7)
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 rewardsEqual weight $1/n$ to every rewardExponentially more weight on recent rewards
Initial-value biasDisappears once the action is tried (weight on $Q_1$ is 0 after one update)Permanent but decreasing: weight $(1-\alpha)^n$
Stationary problemsIdealGood but noisier asymptotically
Nonstationary problemsPoor — reacts ever more slowly (treats the beginning of time as special)Tracks change — what we want
In practiceUsed in theoryUsed in most applications and empirical research
Why the book mostly uses constant α

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".

Common mistake

"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$:

$$Q_{n+1} = \Big[\prod_{j=1}^{n}(1-\alpha_j)\Big]Q_1 + \sum_{i=1}^{n}\alpha_i\Big[\prod_{j=i+1}^{n}(1-\alpha_j)\Big]R_i$$
Weights for a general step-size sequenceEx 2.4

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

$$\beta_n \doteq \alpha/\bar o_n, \qquad \bar o_n \doteq \bar o_{n-1} + \alpha(1-\bar o_{n-1}),\ \ \bar o_0 \doteq 0$$
Unbiased constant step size(2.8), (2.9)

$\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).

Try it: Exercise 2.5 — sample averages fail on a nonstationary bandit

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.

Exercise 2.6 — Mysterious spikes

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.

$$A_t \doteq \argmax_a\left[\,Q_t(a) + c\sqrt{\frac{\ln t}{N_t(a)}}\,\right]$$
UCB action selection (UCB1)(2.10)
Weaknesses of UCB (exam favourite)

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."

Exercise 2.8 — UCB spike at step 11

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:

$$\Pr\{A_t=a\} \doteq \frac{e^{H_t(a)}}{\sum_{b=1}^{k}e^{H_t(b)}} \doteq \pi_t(a)$$
Soft-max action probabilities(2.11)

Initially all $H_1(a)=0$ (equal probabilities). After selecting $A_t$ and receiving $R_t$:

$$\begin{aligned} H_{t+1}(A_t) &\doteq H_t(A_t) + \alpha\,(R_t-\bar R_t)\,\big(1-\pi_t(A_t)\big)\\ H_{t+1}(a) &\doteq H_t(a) - \alpha\,(R_t-\bar R_t)\,\pi_t(a) \qquad \text{for all } a\ne A_t \end{aligned}$$
Gradient bandit preference update(2.12)

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$.

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

$$\frac{\partial\,\E[R_t]}{\partial H_t(a)} = \E\Big[(R_t-\bar R_t)\big(\mathbb 1_{a=A_t}-\pi_t(a)\big)\Big]$$
Gradient of expected reward as an expectation§2.8 box

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.

Exercise 2.9

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 banditContextual banditFull RL problem
Multiple situations?NoYesYes
Learns a policy?No (one best action)YesYes
Actions affect next situation?NoNo — only immediate rewardYes
Exercise 2.10

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

MethodHow it exploresHyperparameter(s)StrengthsWeaknesses
GreedyDoesn't—Fast initiallyGets stuck on sub-optimal actions
ε-greedyRandom action with prob. ε — indiscriminateε (and α or 1/n)Simple; extends to full RL; works with nonstationarityWastes 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 simpleTemporary — useless for nonstationary; needs knowledge of reward scale
UCBDeterministic bonus for uncertainty$c$Best on the testbed; explores smartlyHard with nonstationarity and large state spaces / function approximation
Gradient banditStochastic soft-max over preferencesα (baseline choice)Invariant to reward shifts (with baseline); is SGA; leads to policy-gradient methodsSensitive 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.

Try it: reproduce the parameter study (Figure 2.6)

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

Hyperparameters in this chapter

ParameterUsed byToo smallToo largeTypical
$\varepsilon$ε-greedySlow discovery of the best action; may get stuckWastes 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 estimatesSlow learning / slow trackingNoisy estimates, never settle0.1
$1/n$sample averageNot tuned; converges on stationary problems but adapts ever more slowlystationary tasks
$Q_1$all value methodsRealistic (0): no exploration bonusVery optimistic: long initial exploration phase0; optimistic for stationary tasks (Fig 2.3 uses +5; the parameter study peaks near 1–2)
$c$UCBBehaves like greedyOver-explores≈ 1–2
$\alpha$ (preference)gradient banditSlow preference changePremature commitment / instability≈ 0.1 – 0.4
baseline $\bar R_t$gradient banditDoesn't change expected update; a good baseline reduces variance. No baseline when rewards are far from 0 → much slower learningrunning 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.