Exploration versus exploitation: multi-armed bandit
Why an agent must sometimes try actions that currently look worse, and how greedy, ε-greedy, UCB and Thompson sampling trade exploration against exploitation, measured by regret and by how often the best action is chosen.
What it demonstrates
Why an agent must sometimes try actions that currently look worse, and how greedy, ε-greedy, UCB and Thompson sampling trade exploration against exploitation, measured by regret and by how often the best action is chosen.
How it works
A bandit is RL with a single state: each of k slot machines (arms) pays 1 with a hidden probability and 0 otherwise. The probabilities are drawn uniformly from [0.05, 0.95] when you press New machines.
Five strategies play the same machines. Each strategy runs 100 independent learners with their own random draws, and the charts average over them. All learners keep a sample-average estimate Q(a) per arm. Random ignores it. Greedy always takes the best estimate. ε-greedy explores at random with probability ε. UCB adds an exploration bonus c·√(ln t / N(a)) that shrinks as an arm is tried more. Thompson sampling keeps a Beta posterior per arm, samples one plausible success rate from each, and pulls the arm with the highest sample.
Regret is the expected reward lost compared with always pulling the best arm, computed from the true probabilities (which the learners never see).
Adjustable parameters
- ε for ε-greedy (0–0.5)
- UCB bonus scale c (0–3)
- Pulls per frame (1–20)
- 5 or 10 arms
- Restart learners / new machines
Known limitations
- A bandit has no state transitions: actions do not affect future situations. Full RL adds that credit-assignment problem on top of exploration.
- Robot RL with continuous actions usually explores by adding Gaussian noise to the policy's actions (Menlo documents an initial policy noise std of 1.0), not by ε-greedy or UCB.
Equations
Core update rule
// lib/sim/ch07-bandit.ts
switch (strategy) {
case "epsilon-greedy":
return rng() < eps ? randInt(rng, k) : argmax(Q);
case "ucb":
return argmax(Q.map((q, a) => q + c * Math.sqrt(Math.log(t + 1) / N[a])));
case "thompson":
return argmax(S.map((s, a) => betaSample(rng, 1 + s, 1 + N[a] - s)));
}
// after pulling arm a and observing reward r ∈ {0, 1}:
N[a] += 1; S[a] += r; Q[a] += (r - Q[a]) / N[a];Explained in Chapter 7: RL Fundamentals