Lesson 4 · Exploration
Bandits: explore or exploit
The problem
Three pizza shops deliver to your street. Every night you order one pizza, from one shop. It arrives good or bad. Some shops are better than others, but nobody tells you which.
You have 20 nights. Try to get as many good pizzas as you can.
Night 1 of 20. Which shop tonight?
| Shop | Tries | Good | Average |
|---|---|---|---|
| 1 | 0 | 0 | – |
| 2 | 0 | 0 | – |
| 3 | 0 | 0 | – |
Good pizzas: 0 of 0.
You probably felt a pull in two directions. Once a shop gave you a couple of good pizzas, you wanted to stick with it. But a shop you tried once, and got unlucky with, might be the best one. To find out, you would have to spend nights on it.
That tension is the subject of this lesson and the next. Every learning method later in this course faces it.
A bandit
The pizza problem is the simplest kind of reinforcement learning problem. The agent (you) picks an action (a shop) and gets a reward: 1 for a good pizza, 0 for a bad one. Then it all repeats.
What's missing is a state. Tonight's choice doesn't change tomorrow's situation. Shop 3 is no better or worse because you ordered from it yesterday. Each night is the same problem again, and the only thing that changes is how much you know.
Repeated choices between options of unknown worth, with no state, form a bandit problem. The name comes from slot machines, once nicknamed "one-armed bandits". Picture a row of them, each paying out at its own unknown rate. Each option is called an arm, and choosing one is called pulling it.
Here are the shops' true chances of a good pizza. You only learn them by ordering:
| Shop | 1 | 2 | 3 |
|---|---|---|---|
| Chance of a good pizza | 0.4 | 0.5 | 0.7 |
Each night's result is a Bernoulli outcome: 1 with the shop's chance, 0 otherwise. Nights are independent of each other.
The value of a shop
A shop's value is its expected reward: what a pizza from shop is worth on average. For a 0/1 reward the expected value is the chance of a 1, so , and . This is the bandit version of an action value, with no state to condition on.
If you knew the values, the problem would be over: order from shop 3 every night. The whole difficulty is that you don't. You have to estimate them from the pizzas you've had.
DigressionWhere bandits come fromRobbins posed the two-armed version in 1952. The word 'bandit' came a few years later. · 1 min
The statistician Herbert Robbins set out the problem in a 1952 paper, "Some aspects of the sequential design of experiments". He asked how to share out tries between two options so that the average payoff per try approaches that of the better one. His interest was experiments: when to stop testing and start using what you've learned.
Robbins didn't say "arm" or "bandit". The phrase "two-armed bandit" appeared a few years later, in work by Bradt, Johnson and Karlin in 1956. An earlier paper by William Thompson, in 1933, asked the same kind of question about two medical treatments. The next lesson returns to his answer.
Estimating each shop
The natural estimate of a shop's value is the average reward it has given you: the sample mean. Write for the estimate of shop , and for how many times you've tried it.
You don't need to store every pizza. The incremental mean updates the average one result at a time. After a pizza with reward from shop :
Read it back: move the estimate a fraction of the way toward the new result. The fraction is the step size.
Worked example
Three pizzas from shop 2
Start: , .
By the law of large numbers, each estimate settles on the shop's true value, if you keep trying that shop. That condition is the whole problem.
Greedy: always pick the best-looking shop
The obvious plan is to order from whichever shop has the highest estimate so far. Picking the action with the highest estimated value is acting greedily, as a greedy policy does. In symbols, tonight's shop is (the argmax). When estimates tie, pick one of the tied shops at random.
Using what you know to get reward now is called exploiting. Greedy only ever exploits.
Predict first
Pure greedy. All three estimates start at 0. On night 1 it picks shop 1, and the pizza is good. Will it ever try shop 3?
Watch greedy play. The bars are the estimates; the dashed lines are the true chances, which greedy can't see.
Before night 1: every estimate is 0, so all three shops tie.
Over 1,000 greedy runs of 300 nights, the last 100 nights all went to shop 1 in 27%, shop 2 in 30% and shop 3 in 44%.
Things to notice:
- In the greedy run, shop 1 serves a good pizza on night 1 and gets every night after that. Shops 2 and 3 are never tried, so their estimates stay wrong at 0.
- Greedy locks onto whichever shop first serves a good pizza. Before that, all estimates are 0 and it picks at random. So it ends on shop 3 only of the time. The 1,000 runs at the bottom of the figure agree.
- Switch to ε-greedy and step through. It mostly picks the best-looking shop, but now and then tries another at random.
Explore or exploit
Greedy fails because it never explores: it never tries an option only to learn more about it. Exploring costs something now, since you might get a worse pizza tonight. It pays later, because you might find a better shop.
Choosing between trying options to learn more and using the best one found so far is the exploration–exploitation trade-off. Too little exploring, and you may never find the best option. Too much, and you keep paying for options you already know are worse.
ε-greedy
The simplest fix is to explore a fixed fraction of the time. Each night:
- with chance , pick the shop with the highest estimate (exploit);
- with chance , pick a shop uniformly at random (explore).
This is ε-greedy. The Greek letter (epsilon) is the exploration rate. The course default is : explore one night in ten.
Worked example
How often does ε-greedy pick the best-looking shop?
Exploit, with chance : it picks the best-looking shop for sure.
Random exploring means every shop keeps getting tried, about of the nights each. So every estimate keeps improving, and the best shop eventually looks best. That's what greedy lacked.
Regret: scoring a strategy
To compare strategies, count what each one loses against always picking the best shop. On a night you pick shop , you lose good pizzas on average, where is the best value. Add this up over the nights, and you get the regret:
Here is the shop picked on night . Read it back: each night adds the gap between the best shop's value and the chosen shop's value. Picking the best shop adds 0.
Worked example
Always shop 1, for 10 nights
Each night loses good pizzas on average.
Regret uses the true values, not the pizzas you happened to get. So it measures the quality of the choices, without the luck of each pizza. Only someone who knows the true chances can compute it, which is fine: we use it to compare strategies in simulation.
Low regret means two things together: explore enough to find the best shop, and don't waste too many nights once you have.
Choosing ε
Now move ε and watch the regret. Each curve is the average of 200 runs. The shaded band around each line is a 95% confidence interval for that average.
Predict first
After 1,000 nights, which ε has the lowest average regret?
Lines are means; shading is the 95% confidence interval of the mean.
After 1,000 nights: ε = 0.10 lost 32.7 good pizzas on average; greedy lost 132.6.
Working out regret for eight values of ε…
Things to notice:
- Greedy's curve is a straight line. A run stuck on shop 1 loses 0.3 every night, forever.
- Big ε is also a straight line, for the opposite reason. Even after it knows shop 3 is best, ε-greedy explores a fraction ε of the nights. Each exploring night loses on average. At ε = 0.5 that's about 0.08 a night.
- The best ε sits in the middle, around 0.05 to 0.1 here. The lower plot is U-shaped: too greedy on the left, too random on the right.
- Even the best ε-greedy never stops climbing. Once it has found shop 3, its curve becomes a shallow straight line, because it never stops exploring. The next lesson fixes this.
When the shops change
So far the shops never change. Real ones do. Suppose shop 3's chef leaves on night 500, and its chance of a good pizza drops from 0.7 to 0.3. Shop 2, at 0.5, is now the best.
The sample average gives every pizza ever eaten the same weight. After 500 nights of mostly good pizzas from shop 3, it takes a long run of bad ones to drag that average down.
A constant step size fixes this. Replace with a fixed (alpha):
The Maths toolkit's step size section showed the trade-off. A constant weights recent results more, so it follows changes. But it never fully settles. The course default is .
━ α = 0.1 · ╍ plain average · ┄ true chance
Lines are means; shading is the 95% confidence interval of the mean.
Share of nights 901–1,000 at the best shop (now shop 2): with α = 0.1, 72%; with the plain average, 30%. With ε = 0.1, 93% is the most possible.
Things to notice:
- With , the estimate for shop 3 falls within a few dozen nights of the change. ε-greedy moves to shop 2 soon after.
- The plain average drifts down slowly. In the run shown, it's still about 0.5 at night 1,000, 500 nights after the chef left.
- Over nights 901 to 1,000, the constant step size has about 72% of runs at shop 2. The plain average has about 30%. (With ε = 0.1, the most possible is 93%.)
- Before the change, the plain average does a little better. A constant step size never stops wobbling, so now and then shop 3's estimate dips and ε-greedy wanders off.
So use when the options never change, and a constant when they might. Most later methods in this course use a constant , because what they estimate keeps changing as the agent learns.
Optimistic starting values
Here is a cheaper way to make greedy explore. Start every estimate at 1, the best value a shop could possibly have. Then use a constant step size .
Now every untried shop looks perfect. Greedy picks one, and unless the pizza is good, its estimate drops below 1. The other shops still look perfect, so greedy tries them next. Each shop keeps being tried until bad pizzas pull its estimate below the others'.
Starting every estimate high, so that untried options look good and get tried, is called optimistic initialisation.
Predict first
Optimistic greedy: every estimate starts at 1, step size 0.1. Shop 1's first pizza is bad. Which shop does greedy pick on night 2?
Before night 1: every estimate is 1, as good as a shop could possibly be.
Lines are means; shading is the 95% confidence interval of the mean.
Things to notice:
- In the first nights, the bars fall from 1 one shop at a time. Greedy rotates through the shops on its own, with no random exploring.
- After 1,000 nights, optimistic greedy's regret is about 23, below ε-greedy's 33 and far below plain greedy's 133.
Why the constant step size? With the sample average, the first step is , so the first pizza wipes out the starting guess at once. With , the hopeful start fades over a few dozen tries. That's long enough to make greedy try everything.
Optimism has limits. It only drives exploring at the start. If the shops change later, nothing makes greedy go back and check. And picking the starting value needs a rough idea of how big rewards can be.
DigressionBandits in the wild: A/B tests and headlinesA bandit is an A/B test that shifts customers toward the winner while it runs. · 2 min
An A/B test splits customers at random between two versions, for a fixed time, and then picks a winner. The split stays 50/50 until the end. If version B is much worse, half the customers get it the whole time.
A bandit treats each customer as a night and each version as a shop. As evidence builds up, it sends more customers to the version that's doing better. So it loses less along the way: lower regret.
News sites use this to choose between headlines for the same story, and ad systems use it to choose which ad to show. The price is in the statistics. Because the split keeps changing, the clean p-values and confidence intervals of the A/B testing lesson no longer apply directly. Use an A/B test when you need a trustworthy answer to "is B better?". Use a bandit when you mostly care about doing well while you learn.
Bandits come back in more depth in the Auctions and mechanism design course. There, choosing which ad to show is part of running an ad auction.
DeeperSoftmax explorationExplore the promising shops more than the hopeless ones. · 2 min
ε-greedy explores blindly. When it explores, shop 1 (estimate 0.4) is as likely as shop 2 (estimate 0.5). A gentler idea is to pick each shop with a chance that grows with its estimate.
The softmax does this. It turns the estimates into chances:
The temperature (tau) sets how sharp the choice is. With estimates 0.4, 0.5 and 0.7 and , the chances are about 0.04, 0.11 and 0.84. As shrinks toward 0, this becomes greedy. As grows, it becomes uniformly random.
Softmax exploring needs a good , and that depends on the size of the rewards. The gradient bandit, in the policy gradients lesson, learns softmax preferences directly instead of estimates.
DigressionSix ways to score a bandit algorithmRegret is the usual score, but not the only one. · 2 min
Regret adds up what you lose along the way. Other goals give other scores:
- Find the best arm eventually. Easy, and weak: trying the arms in turn forever does it, without ever using what it learns.
- Maximise discounted reward. Count future rewards less, as later lessons in this course do. For this goal there's an exact answer, the Gittins index, but the idea doesn't carry over to problems with states.
- Maximise total reward over a fixed number of nights. Computable in principle, but the work grows exponentially with the number of nights.
- Find a near-best arm with high confidence. With chance at least , name an arm within of the best. The number of tries needed may grow only like a fixed power of the number of arms, and .
- Earn near-best reward with high confidence, after a similar number of tries.
- Make few mistakes: bound the number of nights spent on arms that are more than worse than the best.
Goals 4, 5 and 6 turn out to be equivalent: an algorithm for one can be turned into an algorithm for the others. Goal 4 is the "PAC" style of guarantee that the next lesson's Deeper aside works through.
In PyTorch: a thousand runs at once
One run of a bandit is noisy, so you always average many runs. The figures above play each run in turn. In PyTorch you can play all of them at once: give every tensor one row per run. Each row of a tensor is then one whole run, and one operation updates every run.
First, the shops' chances and a greedy choice per row. values.max(dim=1) gives each row's largest value (see max along a dimension). Ties are broken at random, using one uniform number per run:
SHOPS = torch.tensor(E.SHOP_PROBS, dtype=torch.float64) # (3,) chance of a good pizza
def argmax_random_ties(values: torch.Tensor, u: torch.Tensor) -> torch.Tensor:
"""Row-wise argmax of a (runs, k) tensor, breaking ties at random with one uniform per row.
Values within 1e-9 of the row's largest count as tied, so rounding can't split a tie.
"""
is_max = values >= values.max(dim=1, keepdim=True).values - 1e-9 # (runs, k) bool
pick = (u * is_max.sum(dim=1)).long() # (runs,) which of the tied shops: 0, 1, …
# The first column where the running count of tied shops passes `pick`.
return (is_max.cumsum(dim=1) > pick.unsqueeze(1)).int().argmax(dim=1)is_maxmarks every shop within a hair (1e-9) of the row's largest estimate, so rounding can't split a tie.is_max.cumsum(dim=1)counts the tied shops from left to right. The first column where the count passespickis the chosen one.
Then ε-greedy for all runs together. The loop is over nights, not runs:
def epsilon_greedy(
epsilon: float,
runs: int = 1000,
nights: int = 1000,
probs: torch.Tensor = SHOPS,
q0: float = 0.0,
alpha: float | None = None,
generator: torch.Generator | None = None,
uniforms: torch.Tensor | None = None,
) -> dict[str, torch.Tensor]:
"""Play ε-greedy for `nights` nights in `runs` independent runs at once.
probs is (k,) for fixed shops or (nights, k) if they change. alpha=None means the sample
average (step 1/n). Each night uses four uniforms per run: explore?, random shop, tie-break,
pizza. Pass `uniforms` (runs, nights, 4) to replay given numbers instead of drawing them.
"""
probs = probs.expand(nights, -1) if probs.dim() == 1 else probs # (nights, k)
k = probs.shape[1]
if uniforms is None:
uniforms = torch.rand(runs, nights, 4, generator=generator, dtype=torch.float64)
Q = torch.full((runs, k), q0, dtype=torch.float64) # estimates
N = torch.zeros(runs, k, dtype=torch.float64) # tries per shop
rows = torch.arange(runs)
choices = torch.empty(runs, nights, dtype=torch.long)
for t in range(nights):
u = uniforms[:, t] # (runs, 4)
greedy = argmax_random_ties(Q, u[:, 2]) # (runs,)
random_shop = (u[:, 1] * k).long()
shop = torch.where(u[:, 0] < epsilon, random_shop, greedy)
reward = (u[:, 3] < probs[t, shop]).double() # 1 = good pizza
N[rows, shop] += 1
step = 1 / N[rows, shop] if alpha is None else alpha
Q[rows, shop] += step * (reward - Q[rows, shop]) # incremental mean
choices[:, t] = shop
# Regret: what each night's choice lost against that night's best shop.
gaps = probs.max(dim=1).values - probs.gather(1, choices.T).T # (runs, nights)
return {"choices": choices, "regret": gaps.cumsum(dim=1), "estimates": Q, "counts": N}uniformsholds four random numbers per run per night, drawn from a seededtorch.Generator. The tests replay the figures' own random numbers through this function, and it makes exactly the same choices as the TypeScript.Q[rows, shop]picks one entry per row: runi's estimate for the shop it chose.rowsistorch.arange(runs), andshopis a tensor of chosen shops. This is indexing with tensors of positions.torch.where(explore, random_shop, greedy)chooses per run between the two options.probs.gather(1, choices.T)looks up each night's chance for each chosen shop, in one call.- Everything is
float64, like the TypeScript's numbers, so the two agree on every estimate.
def compare_epsilons(epsilons: list[float], runs: int = 1000, nights: int = 1000, seed: int = 0) -> dict[float, float]:
"""Average total regret after `nights` nights for each ε (same seed for each, for a fair race)."""
out = {}
for eps in epsilons:
g = torch.Generator().manual_seed(seed)
out[eps] = epsilon_greedy(eps, runs, nights, generator=g)["regret"][:, -1].mean().item()
return outtorch.manual_seed(0)
results = compare_epsilons([0.0, 0.01, 0.1, 0.5])
for eps, r in results.items():
print(f"epsilon {eps:<4}: average regret after 1,000 nights {r:5.1f}")
g = torch.Generator().manual_seed(0)
greedy = epsilon_greedy(0.0, generator=g)
stuck = torch.bincount(greedy["choices"][:, -1], minlength=3) / 1000
print("greedy ends on shops 1, 2, 3:", [round(s, 2) for s in stuck.tolist()])
g = torch.Generator().manual_seed(0)
hopeful = epsilon_greedy(0.0, q0=1.0, alpha=0.1, generator=g)
print(f"greedy from estimates of 1, alpha 0.1: regret {hopeful['regret'][:, -1].mean():.1f}")epsilon 0.0 : average regret after 1,000 nights 141.7
epsilon 0.01: average regret after 1,000 nights 72.3
epsilon 0.1 : average regret after 1,000 nights 29.9
epsilon 0.5 : average regret after 1,000 nights 85.7
greedy ends on shops 1, 2, 3: [0.26, 0.31, 0.42]
greedy from estimates of 1, alpha 0.1: regret 21.8These are 1,000 runs drawn from PyTorch's generator, so they differ a little from the figures' 200 runs. The pattern is the same. ε = 0.1 beats both extremes, and greedy ends on the best shop well under half the time. Optimistic greedy does best of all.
Putting it together
Here's one ε-greedy run, , from the start:
- Estimates start at 0, with no tries. Every shop ties, so night 1 picks at random.
- Each night, with chance 0.9 pick the shop with the highest , and with chance 0.1 a random shop. Overall it picks the best-looking shop about 93% of the time.
- After each pizza, update that shop's estimate with the incremental mean, . If the shops can change, use instead of .
- Score it by regret: each night adds . Over 1,000 nights, ε = 0.1 loses about 33 good pizzas on average; greedy loses about 133.
- Optimistic starts (every estimate at 1, ) let even pure greedy explore early on, and do better still here: about 23.
Each of these strategies explores without knowing where it's most useful to explore. The next lesson explores where it's most unsure.
Common misconceptions
"Greedy finds the best shop once it has enough data." It only gets data about the shops it picks. A shop that looked bad early is never retried, so its estimate never gets fixed. In the figure, greedy ended on shop 3 in under half of its runs.
"Exploring means picking a different shop from the best-looking one." ε-greedy's random pick can land on the best-looking shop too. That's why it picks the best-looking shop with chance 0.93, not 0.9.
"Regret counts the bad pizzas you got." It counts the expected loss of your choices, , using the true values. Picking shop 3 adds no regret, even on a night its pizza is bad.
"More exploring is safer." Exploring costs reward every time. At ε = 0.5 the regret is almost three times what it is at ε = 0.1.
"Always use the plain average, since it's exact." It's exact only if the shops never change. When they can, a constant step size follows the change and the plain average lags far behind.
Recap
- A bandit is a repeated choice between options of unknown value, with no state. Each option's value is its expected reward.
- Estimate each value by the incremental mean, , or with a constant step size if the values can change.
- Greedy only exploits, and can lock onto a worse option forever.
- The exploration–exploitation trade-off: trying options to learn costs reward now and pays later.
- ε-greedy explores with chance ε. It picks the best-looking of 3 options with chance , about 0.93 at ε = 0.1.
- Regret adds up over the nights. Always picking shop 1 for 10 nights has regret 3.
- Optimistic initialisation starts every estimate high, so greedy tries everything early.
- PyTorch names in this lesson:
torch.Generatorandtorch.rand,max(dim=1)andargmax(dim=1),cumsum,torch.where,gather, and indexing with tensors of positions.