Velamuvi AIAcademy

Lesson 3 of 12 · Foundations

Exploration vs Exploitation

The exploration-exploitation dilemma in reinforcement learning: ε-greedy, decaying ε, optimistic initial values, UCB and softmax, compared in NumPy.

  • 17 min read
  • Advanced
  • Reviewed
In this lesson you will learn
  • Explain the exploration-exploitation dilemma, and why a purely greedy agent gets stuck
  • Implement ε-greedy and decaying ε, and choose a sensible ε
  • Explore where it matters with optimistic initial values and UCB
  • Turn value estimates into action probabilities with softmax and a temperature
  • Compare exploration strategies fairly by simulation

The idea in plain words

You've just moved to a new town with five cafés. After one visit to each, you have a favourite. Do you keep going there, or do you give the others another try in case your first impression was wrong? Going back to the favourite is exploitation: using what you know to get the best result you can count on today. Trying the others is exploration: gathering information that might reveal something better, at the cost of some disappointing coffees.

RL agents face this at every step, because a reward only tells them about the action they actually took. Neither extreme works: an agent that only exploits can lock onto a mediocre choice forever, and one that only explores never uses what it has learned. This lesson shows the standard ways to balance the two on the simplest possible problem, one situation with a few actions to choose from. Every one of them carries over to full RL problems: Q-Learning, for example, explores with ε-greedy.

The café problem

The five cafés, numbered 0 to 4, have true average qualities of 1.0, 1.6, 1.3, 2.0 and 0.6, so café 3 is the best. The agent doesn't know these numbers. Each visit gives a satisfaction score: the café's true quality plus random day-to-day noise with a standard deviation of 1. A single visit can easily mislead: the best café scores below 1.0 on about 16% of visits.

The agent keeps two numbers per café: Q(a), the average score of its visits to café a so far, and N(a), the number of visits. A strategy is a rule that turns these into the next choice. To compare strategies fairly, the code below simulates 500 agents at once, one row of each array per agent, for 1,000 visits each, and every agent starts by trying each café once. (Multi-Armed Bandits studies this kind of problem in more depth.)

A greedy agent gets stuck

The greedy strategy always picks the café with the best average so far:

Try it yourselfPython
import numpy as np

MEANS = np.array([1.0, 1.6, 1.3, 2.0, 0.6])     # true average satisfaction of cafés 0-4; café 3 is best

def run(choose, runs=500, steps=1000, seed=0):
    """Play 500 independent agents at once, one row each. Every agent first tries each café once."""
    rng = np.random.RandomState(seed)
    total, count = np.zeros((runs, 5)), np.zeros((runs, 5))
    rows, rewards = np.arange(runs), []
    for t in range(steps):
        Q = total / np.maximum(count, 1)               # each café's average score so far
        a = np.full(runs, t) if t < 5 else choose(Q, count, t, rng)
        r = rng.normal(MEANS[a], 1.0)                  # true quality plus day-to-day noise
        total[rows, a] += r
        count[rows, a] += 1
        rewards.append(r.mean())
    return np.mean(rewards), count

def greedy(Q, count, t, rng):
    return Q.argmax(axis=1)                            # always the best average so far

avg_reward, count = run(greedy)
favourite = count.argmax(axis=1)                       # the café each agent visited most
print(f"greedy: average satisfaction per visit {avg_reward:.3f} (the best café gives 2.0)")
for cafe in range(5):
    print(f"  café {cafe} (true quality {MEANS[cafe]}): favourite of {np.mean(favourite == cafe):4.0%} of agents")
Output
greedy: average satisfaction per visit 1.850 (the best café gives 2.0)
  café 0 (true quality 1.0): favourite of   1% of agents
  café 1 (true quality 1.6): favourite of  22% of agents
  café 2 (true quality 1.3): favourite of   6% of agents
  café 3 (true quality 2.0): favourite of  71% of agents
  café 4 (true quality 0.6): favourite of   0% of agents

Almost a third of the greedy agents settled on the wrong café, most often café 1. For each of them, café 3's first visit was unlucky, or another café's was lucky, and a greedy agent never goes back to check. Its estimate of café 3 stays wrong forever, because the only way to fix an estimate is to visit again. One visit is a sample, not knowledge.

ε-greedy: explore at random, now and then

The simplest fix is to explore a small, fixed fraction of the time:

with probability ε:        choose a random action          (explore)
with probability 1 − ε:    choose the best estimate so far (exploit)

The program tries several values of ε, plus a decaying ε that starts at 0.5 and shrinks by 1% after every visit, down to a floor of 0.01. The last column is the share of each agent's final 100 visits that went to café 3:

Try it yourselfPython
import numpy as np

MEANS = np.array([1.0, 1.6, 1.3, 2.0, 0.6])     # café 3 is best

def run(choose, runs=500, steps=1000, seed=0):
    rng = np.random.RandomState(seed)
    total, count = np.zeros((runs, 5)), np.zeros((runs, 5))
    rows, rewards, best = np.arange(runs), [], []
    for t in range(steps):
        Q = total / np.maximum(count, 1)
        a = np.full(runs, t) if t < 5 else choose(Q, count, t, rng)
        r = rng.normal(MEANS[a], 1.0)
        total[rows, a] += r
        count[rows, a] += 1
        rewards.append(r.mean())
        best.append(np.mean(a == 3))
    return np.mean(rewards), np.mean(best[-100:])     # reward per visit, share of best in the last 100

def epsilon_greedy(epsilon):
    def choose(Q, count, t, rng):
        eps = epsilon(t) if callable(epsilon) else epsilon
        explore = rng.rand(len(Q)) < eps               # which agents explore this step
        return np.where(explore, rng.randint(5, size=len(Q)), Q.argmax(axis=1))
    return choose

print("strategy                      reward per visit   best café in last 100 visits")
for name, eps in [("epsilon = 0.01", 0.01), ("epsilon = 0.1", 0.1), ("epsilon = 0.3", 0.3),
                  ("decaying from 0.5 to 0.01", lambda t: max(0.01, 0.5 * 0.99 ** t))]:
    reward, best = run(epsilon_greedy(eps))
    print(f"{name:<29} {reward:12.3f} {best:20.0%}")
Output
strategy                      reward per visit   best café in last 100 visits
epsilon = 0.01                       1.871                  79%
epsilon = 0.1                        1.892                  91%
epsilon = 0.3                        1.776                  76%
decaying from 0.5 to 0.01            1.931                  93%

Compare them with greedy's 1.850 per visit. ε = 0.01 helps only a little: exploration is so rare that many agents still haven't corrected their mistake after 1,000 visits. ε = 0.1 finds café 3 far more often. ε = 0.3 does worse than greedy. Even an agent that knows the answer picks at random 30% of the time, so it visits café 3 at most 70% + 30% ÷ 5 = 76% of the time, exactly the share in the table, and the random visits drag its average down. The decaying ε gets the best of both: plenty of exploration early, when the estimates are poor, and very little later, when they are good. Drag the slider to see how the decay rate shapes the schedule:

ε = 0.5 × 0.99^t
010020030040050000.10.20.30.40.5
ε
With 0.99, ε halves about every 70 steps. The code also keeps a floor of 0.01, so a little exploration never stops.

Optimistic initial values

Another trick needs no randomness at all: start every estimate unrealistically high. Assume every café is excellent until proven otherwise. A greedy agent then visits a café, is disappointed, and moves on to the others, which still look excellent. It keeps rotating between them until real scores have pulled every estimate down to earth. Here, each café starts with an imaginary first visit that scored 5, far above any true quality:

estimate after n real visits = (5 + the sum of the n real scores) ÷ (n + 1)

The optimism fades as real visits pile up, so exploration happens early and then stops by itself. That's also the weakness: if the world changes later, say a café hires a better chef, an optimistic agent that has stopped exploring will never notice.

Upper confidence bound (UCB)

ε-greedy explores blindly: it is as likely to revisit a café it knows is poor as one it is unsure about. Upper confidence bound (UCB) selection explores where the uncertainty is. It adds a bonus to each estimate and picks the highest total:

UCB score(a) = Q(a) + c × √( ln t ÷ N(a) )

Q(a)   the average reward of action a so far
N(a)   how many times a has been tried
t      the number of steps so far
c      how strongly to favour uncertain actions

The bonus is large for an action tried only a few times and shrinks as N(a) grows, because each visit makes the average more reliable. The ln t on top grows slowly with time, so an action that hasn't been tried for a long while eventually earns another look. The principle is optimism in the face of uncertainty: treat every action as being as good as it could plausibly be, then let the evidence decide.

Softmax (Boltzmann) selection

Softmax selection chooses every action with some probability, and the better an action's estimate, the higher its probability:

P(a) = e^(Q(a) ÷ τ) ÷ Σ e^(Q(b) ÷ τ)        the sum runs over every action b

The temperature τ (tau) controls how random the choice is. The name comes from the Boltzmann distribution in physics, which has the same formula, and in which a higher temperature makes a system more disordered. Here is what different temperatures do to the same five estimates:

Try it yourselfPython
import numpy as np

Q = np.array([1.0, 1.6, 1.3, 2.0, 0.6])        # an agent's current estimates for the five cafés

def softmax_probabilities(Q, tau):
    z = np.exp((Q - Q.max()) / tau)            # subtracting the largest Q avoids overflow
    return z / z.sum()

for tau in [0.05, 0.2, 0.5, 1.0, 5.0]:
    probabilities = softmax_probabilities(Q, tau)
    print(f"tau = {tau:<4}  chance of café 0-4: " + "  ".join(f"{p:.2f}" for p in probabilities))
Output
tau = 0.05  chance of café 0-4: 0.00  0.00  0.00  1.00  0.00
tau = 0.2   chance of café 0-4: 0.01  0.12  0.03  0.85  0.00
tau = 0.5   chance of café 0-4: 0.07  0.24  0.13  0.53  0.03
tau = 1.0   chance of café 0-4: 0.13  0.24  0.18  0.36  0.09
tau = 5.0   chance of café 0-4: 0.19  0.21  0.20  0.23  0.17

A low temperature makes softmax almost greedy, and a high one makes it almost uniform. In between, it does something ε-greedy can't: at τ = 0.2 it still gives the close rival, café 1, a 12% chance, but almost never wastes a visit on café 4, the clear loser.

Comparing the strategies

The same 500 agents and 1,000 visits, now with all five ideas:

Try it yourselfPython
import numpy as np

MEANS = np.array([1.0, 1.6, 1.3, 2.0, 0.6])     # café 3 is best

def run(choose, runs=500, steps=1000, seed=0, start=0.0):
    """start: an imaginary first visit to every café that scored `start` (0 means none)."""
    rng = np.random.RandomState(seed)
    total, count = np.full((runs, 5), start), np.full((runs, 5), 1.0 if start else 0.0)
    rows, rewards, best = np.arange(runs), [], []
    for t in range(steps):
        Q = total / np.maximum(count, 1)
        a = np.full(runs, t) if t < 5 else choose(Q, count, t, rng)
        r = rng.normal(MEANS[a], 1.0)
        total[rows, a] += r
        count[rows, a] += 1
        rewards.append(r.mean())
        best.append(np.mean(a == 3))
    return np.mean(rewards), np.mean(best[-100:])

def greedy(Q, count, t, rng):
    return Q.argmax(axis=1)

def epsilon_greedy(epsilon):
    def choose(Q, count, t, rng):
        eps = epsilon(t) if callable(epsilon) else epsilon
        explore = rng.rand(len(Q)) < eps
        return np.where(explore, rng.randint(5, size=len(Q)), Q.argmax(axis=1))
    return choose

def ucb(c):
    def choose(Q, count, t, rng):
        return (Q + c * np.sqrt(np.log(t) / count)).argmax(axis=1)
    return choose

def softmax(tau):
    def choose(Q, count, t, rng):
        z = np.exp((Q - Q.max(axis=1, keepdims=True)) / tau)
        cumulative = np.cumsum(z / z.sum(axis=1, keepdims=True), axis=1)
        return (rng.rand(len(Q), 1) < cumulative).argmax(axis=1)    # draw one café per agent
    return choose

print("strategy                        reward per visit   best café in last 100 visits")
for name, choose, start in [
        ("greedy", greedy, 0.0),
        ("epsilon-greedy, epsilon = 0.1", epsilon_greedy(0.1), 0.0),
        ("decaying epsilon", epsilon_greedy(lambda t: max(0.01, 0.5 * 0.99 ** t)), 0.0),
        ("optimistic start, greedy", greedy, 5.0),
        ("UCB, c = 1", ucb(1.0), 0.0),
        ("softmax, tau = 0.2", softmax(0.2), 0.0)]:
    reward, best = run(choose, start=start)
    print(f"{name:<31} {reward:12.3f} {best:20.0%}")
Output
strategy                        reward per visit   best café in last 100 visits
greedy                                 1.850                  71%
epsilon-greedy, epsilon = 0.1          1.892                  91%
decaying epsilon                       1.931                  93%
optimistic start, greedy               1.974                  98%
UCB, c = 1                             1.969                  99%
softmax, tau = 0.2                     1.909                  86%

On this problem, the two "smart" explorers win: the optimistic greedy agent and UCB find café 3 almost every time and average close to the maximum of 2.0. Softmax and the ε-greedy variants come next, and pure greedy comes last. The ranking depends on the problem, though, so here is what each strategy is good and bad at:

StrategyHow it exploresStrengthWeakness
ε-greedyA random action, with probability εSimple, and works with any agentExplores blindly, and a fixed ε never stops wasting visits
Decaying εLike ε-greedy, with ε shrinking over timeExplores early, exploits lateThe schedule needs tuning
Optimistic startEvery untried action looks greatNo randomness, no extra codeExplores only at the start, so it misses later changes
UCBA bonus for rarely tried actionsExplores where the uncertainty isNeeds a count per action, which is hard when there are millions of states
SoftmaxProbabilities that rise with the estimateRarely wastes visits on clear losersτ must match the size of the rewards

Common mistakes

Practice

Practice exercise

Café 2 has the lowest average so far, but only two visits. Complete ucb_scores so that it returns every café's UCB score, Q + c × √(ln t ÷ N). Which café does UCB choose, and which would a greedy agent choose?

Your solutionPython
import numpy as np

Q = np.array([1.8, 2.0, 1.2])        # average satisfaction so far at cafés 0, 1 and 2
N = np.array([40, 30, 2])            # visits so far
t = 72                               # total visits so far

def ucb_scores(Q, N, t, c=1.0):
    # Return Q plus the exploration bonus c * sqrt(ln t / N), for every café at once
    return Q

scores = ucb_scores(Q, N, t)
print("UCB scores:", " ".join(f"{s:.2f}" for s in scores))
print("UCB chooses café", scores.argmax())
print("greedy chooses café", Q.argmax())
Knowledge check

An ε-greedy agent with ε = 0.3 already knows which of its 5 actions is best. In the long run, how often does it choose that action?

Summary

  • An agent must exploit what it knows and explore to learn more. A purely greedy agent can lock onto a poor action forever, because it never collects the evidence that would correct it.
  • ε-greedy explores at random with probability ε. A decaying ε explores early and exploits later, usually with a small floor.
  • Optimistic initial values make every untried action look great, and UCB adds a bonus c × √(ln t ÷ N) that steers exploration towards uncertain actions.
  • Softmax picks actions with probabilities that rise with their estimates. The temperature τ sets how random it is, and must suit the size of the rewards.
  • Compare strategies by averaging many simulated runs: on the café problem, UCB and optimism did best, but the ranking depends on the problem.

Next: Value Functions.

Finished reading? Tick it off to track your progress.