Skip to content
Physical AI
All experiments

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.

Loading simulation…

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

Qn+1(a)=Qn(a)+1N(a)(r−Qn(a))Q_{n+1}(a) = Q_n(a) + \tfrac{1}{N(a)}\big(r - Q_n(a)\big)
at=arg⁡max⁡a[Q(a)+cln⁡tN(a)](UCB)a_t = \arg\max_a \Big[Q(a) + c\sqrt{\tfrac{\ln t}{N(a)}}\Big] \quad \text{(UCB)}
p~a∼Beta⁡(1+Sa, 1+Fa),  at=arg⁡max⁡ap~a(Thompson)\tilde p_a \sim \operatorname{Beta}(1 + S_a,\, 1 + F_a),\; a_t = \arg\max_a \tilde p_a \quad \text{(Thompson)}
Regret(T)=∑t=1T(p∗−pat)\text{Regret}(T) = \sum_{t=1}^{T} \big(p^* - p_{a_t}\big)

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