Reinforcement learning5 / 5

Lesson 5 · Exploration

Smarter exploration: UCB and Thompson sampling

The problem

ε-greedy explores blindly. When it explores, it picks a shop at random. After 1,000 nights at ε = 0.1, it has spent about 33 nights on shop 1, the worst shop, at random. It kept doing so long after shop 1 had shown it was worst. And it will keep doing so, one night in thirty, forever.

It also ignores how much it knows. Suppose shop 2 has been tried 100 times and shop 3 only 4 times, and both average 0.5. ε-greedy treats them the same. But shop 2's 0.5 is solid, while shop 3's could easily be 0.3 or 0.8. Another try at shop 3 would teach you much more.

So a better plan is to explore where you're unsure, and less where you already know the answer. This lesson shows two ways to do that, using the same three shops (chances 0.4, 0.5 and 0.7) as the bandits lesson.

How unsure is an estimate?

One pizza from a shop with chance 0.5 has a standard deviation of 0.5×0.5=0.5\sqrt{0.5 \times 0.5} = 0.5. The average of nn pizzas wobbles less. Its standard error is 0.5/n0.5 / \sqrt{n}:

Tries nn425100
Typical error of the estimate0.250.100.05

The error shrinks like 1/n1/\sqrt{n}: four times the tries halve it. By the central limit theorem, the estimate is rarely more than about two standard errors from the truth.

So shop 3's estimate of 0.5 after 4 tries could well be anything from 0 to 1. After 100 tries, shop 2's estimate is almost surely between 0.4 and 0.6.

Optimism under uncertainty

Here's the idea. For each shop, ask: how good could it plausibly be? Then pick the shop with the highest answer.

A shop you know well can't be much better than its estimate. A shop you've barely tried could be a lot better. So the rarely tried shops get picked, until enough tries show what they're worth. Then they either earn their place or drop away.

Preferring options you're unsure about, as if each is as good as it plausibly could be, is called optimism under uncertainty. The last lesson's optimistic starting values were a crude version: optimism only at the start. Now the optimism follows the uncertainty all the way through.

UCB: estimate plus a bonus

The most common way to put the idea into a formula adds a bonus to each estimate. After tt nights, shop aa's score is

score(a)=Q(a)+cln⁡tN(a)\text{score}(a) = Q(a) + c \sqrt{\frac{\ln t}{N(a)}}

and tonight's shop is the one with the highest score. As before, Q(a)Q(a) is the estimate and N(a)N(a) the number of tries. Before using the formula, try each shop once, so no N(a)N(a) is 0.

The score is an upper confidence bound: a value the shop is unlikely to beat. Picking by it is called UCB. The version with c=2c = \sqrt{2}, so a bonus of 2ln⁡t/N(a)\sqrt{2 \ln t / N(a)}, is called UCB1 (Auer, Cesa-Bianchi and Fischer, 2002). This lesson uses UCB1.

Read the bonus back, one part at a time:

  • 1/N(a)1/\sqrt{N(a)}: the bonus shrinks like the standard error. The more tries, the less a shop could surprise you.
  • ln⁡t\ln t: the natural log of the number of nights so far. It grows, but slowly. A shop that's left alone sees its bonus creep up, so it gets checked again now and then. Even a shop that looks bad is never written off for good.
  • cc: a dial for how much to explore. A bigger cc means more exploring.

Worked example

One UCB1 choice, by hand

  1. After t=20t = 20 nights: shop 1 was tried 3 times (0 good), shop 2 6 times (3 good) and shop 3 11 times (8 good). So Q=0Q = 0, 0.50.5 and 8/11≈0.738/11 \approx 0.73.

The scores are all above 1, though no shop's chance can be. Early on the bonuses are big, so the scores aren't chances. They only rank the shops.

Predict first

After 110 nights, shop 2 has been tried 100 times and shop 3 only 4 times. Both estimates are 0.5. Which does UCB1 pick between them?

Watch UCB1 play. Each bar is an estimate, and the dashed box on top is the bonus.

shop 1shop 2shop 300.511.522.5estimate + bonusuntrieduntrieduntried
ShopTriesEstimateBonusScore
10–∞∞
20–∞∞
30–∞∞

Night 1 (t = 0 nights so far): each shop gets one try first. Pizza: bad.

Step 0 of 79
UCB1 night by night. Solid bar: estimate. Dashed box: bonus. The outlined shop has the highest top and is picked. Dashed lines: the true chances. The table gives the numbers.

Things to notice:

  • UCB picks the highest top, not the highest estimate. Often the tallest solid bar loses to a shorter one with a bigger box.
  • A shop's box shrinks each time it's picked, since N(a)N(a) grows. A shop's box grows slowly while it's left alone, since ln⁡t\ln t grows.
  • After a few dozen nights, shop 3 gets most of the nights. Shops 1 and 2 still get the occasional check.
  • There's no randomness in the choice. Given the same pizzas, UCB always makes the same choices. The exploring comes from the bonus.
DeeperHow sure after n tries? Hoeffding's boundA guarantee for the average of n samples, and where UCB1's bonus comes from. · 4 min

The standard error says how far an estimate typically lands from the truth. Sometimes you want a guarantee: how unlikely is a big miss?

For rewards between 0 and 1, there's a clean answer. Let QQ be the average of nn independent rewards with true mean qq. For any distance d>0d > 0,

P(∣Q−q∣≥d)≤2e−2nd2.P\big(|Q - q| \ge d\big) \le 2 e^{-2 n d^2} .

This is Hoeffding's bound. Read it back: the chance of missing by dd or more falls exponentially in nd2n d^2. It needs nothing about the rewards except that they lie between 0 and 1.

A worked example. You've ordered 100 pizzas from a shop and 30 were good, so Q=0.3Q = 0.3. How sure can you be that the true chance is between 0.2 and 0.4?

  • Here d=0.1d = 0.1: 2e−2×100×0.01=2e−2≈0.272 e^{-2 \times 100 \times 0.01} = 2e^{-2} \approx 0.27.
  • So with chance at least 1−0.27=0.731 - 0.27 = 0.73, the true chance is in [0.2,0.4][0.2, 0.4].
  • With 400 pizzas: 2e−8≈0.00072 e^{-8} \approx 0.0007. Four times the data, and a miss of 0.1 becomes almost impossible.
  • Asking for a narrower range is expensive: dd is squared. Halving dd needs four times the tries for the same guarantee.

Where UCB1's bonus comes from. The one-sided version says the truth sits more than dd above the estimate with chance at most e−2Nd2e^{-2 N d^2}. UCB1 wants that chance to shrink as the nights go by, like t−4t^{-4}. Solve for dd:

e−2Nd2=t−42Nd2=4ln⁡t(take logs)d=2ln⁡tN\begin{aligned} e^{-2 N d^2} &= t^{-4} \\ 2 N d^2 &= 4 \ln t \qquad \text{(take logs)} \\ d &= \sqrt{\frac{2 \ln t}{N}} \end{aligned}

That is the bonus. So a UCB1 score is a value the shop beats with chance at most t−4t^{-4}. The bound is loose for any particular shop, which is one reason UCB1 explores more than it needs to.

DeeperPAC bandits: how many tries to find a near-best shop?Combine Hoeffding's bound with the union bound. · 3 min

A different question: you have a budget of tries, then must name a shop. How many tries per shop guarantee a shop within 0.1 of the best, with chance at least 95%?

Step 1: what's enough. If every estimate is within 0.05 of its truth, the shop with the best estimate is within 0.1 of the best shop. At worst, the best shop looks 0.05 too low and another looks 0.05 too high. They swap only if their true values are within 0.1.

Step 2: all three at once. Each estimate misses by more than 0.05 with some small chance. The chance that at least one misses is at most the sum of the three chances. This is the union bound, and it holds even if the misses aren't independent.

So it's enough for each shop to miss with chance at most 0.05/30.05 / 3.

Step 3: Hoeffding. Solve 2e−2n(0.05)2=0.05/32 e^{-2 n (0.05)^2} = 0.05/3 for nn:

n=ln⁡(2×3/0.05)2×0.052=ln⁡1200.005≈958.n = \frac{\ln(2 \times 3 / 0.05)}{2 \times 0.05^2} = \frac{\ln 120}{0.005} \approx 958 .

So 958 tries per shop, 2,874 in total, are enough. In general the count grows with the number of shops kk, with 1/d21/d^2 for accuracy dd, and only with ln⁡(1/δ)\ln(1/\delta) for the failure chance δ\delta. High confidence is cheap; high accuracy is expensive. Guarantees of this "probably approximately correct" form are called PAC guarantees.

DigressionWhy ln t? The Lai–Robbins boundNo strategy can beat logarithmic regret on every bandit, and UCB1 reaches it. · 2 min

In 1985, Tze Leung Lai and Herbert Robbins proved a limit on every bandit strategy. Take any strategy that does reasonably well on every bandit. Then on each bandit its regret must grow at least like ln⁡t\ln t. The constant in front depends on how hard the arms are to tell apart.

The reason: to be sure a worse arm is worse, you must keep sampling it, and the evidence you need grows like ln⁡t\ln t. Skip that, and on some bandit you'd miss the best arm and lose a fixed amount every night.

So regret that grows like ln⁡t\ln t is the best shape possible. Lai and Robbins also built strategies that reach it as tt grows. In 2002, Peter Auer, Nicolò Cesa-Bianchi and Paul Fischer studied the much simpler UCB1. They showed its regret is at most a constant times ln⁡t\ln t at every tt, not only in the long run. That holds for any rewards between 0 and 1.

Thompson sampling: act on a sample of your beliefs

UCB adds a bonus. The second method keeps a full belief about each shop's chance, and explores by sampling from it.

A belief about one shop: the Beta distribution

The maximum likelihood and MAP lesson already built this belief. Before any pizzas, suppose every chance from 0 to 1 is equally plausible: a flat prior. After ss good and ff bad pizzas, Bayes' rule multiplies the prior by the Bernoulli likelihood. The posterior is

belief(p)  ∝  p s(1−p)f.\text{belief}(p) \;\propto\; p^{\,s} (1 - p)^{f} .

That's the likelihood curve from that lesson, scaled to area 1.

The family of curves p a−1(1−p)b−1p^{\,a-1}(1 - p)^{b-1} on [0,1][0, 1], scaled to area 1, is the Beta distribution, written Beta(a,b)\text{Beta}(a, b). It's a density over chances. With a flat start, the belief after ss good and ff bad pizzas is

Beta(1+s,  1+f).\text{Beta}(1 + s,\; 1 + f) .

The 1s are the flat start. Beta(1,1)\text{Beta}(1, 1) is flat: no pizzas yet. Each good pizza adds 1 to the first number, and each bad pizza adds 1 to the second. In the MLE lesson's words, the flat start is "one pretend good pizza and one pretend bad one" folded into the curve's two numbers.

Its mean is a/(a+b)a / (a + b), and its peak is at (a−1)/(a+b−2)(a - 1)/(a + b - 2), the share of good pizzas.

Worked example

3 good pizzas and 1 bad

  1. The belief is Beta(1+3,1+1)=Beta(4,2)\text{Beta}(1 + 3, 1 + 1) = \text{Beta}(4, 2), with shape p3(1−p)p^3 (1 - p).

0.00.20.40.60.81.000.511.522.53chance of a good pizzadensity

Beta(4, 2): mean 0.67 (dashed), peak 0.75, standard deviation 0.178. The shaded middle 95% runs from 0.28 to 0.95.

The belief Beta(1 + good, 1 + bad) about one shop's chance of a good pizza. Shaded: the middle 95%. Dashed: the mean.

Things to notice:

  • The curve centres near the share of good pizzas.
  • More pizzas, narrower curve. Multiply both counts by 10 and the curve narrows by about 10≈3\sqrt{10} \approx 3, the 1/n1/\sqrt{n} again.
  • With 0 good and 0 bad, the curve is flat: every chance is equally plausible.

Thompson sampling

Each night:

  1. From each shop's belief, draw one random plausible chance.
  2. Order from the shop with the largest draw.
  3. Add the pizza to that shop's counts.

This is Thompson sampling.

Why does it explore well? A shop gets picked exactly as often as, by your current beliefs, it's the best one. A well-known bad shop has a narrow curve far to the left, so it almost never wins the draw. An unsure shop has a wide curve, so it sometimes draws high and gets tried. And as its curve narrows, its draws settle near its true value.

Predict first

Shop 3's belief is Beta(2, 1): one good pizza, nothing else. Shop 2's belief is Beta(51, 51): 50 good, 50 bad, a narrow curve at 0.5. How often does shop 3 win the draw against shop 2?

0.00.20.40.60.81.000.511.522.53chance of a good pizzabelief (density)123
ShopGoodBadSample
1000.12
2000.23
3000.72

Night 1: the largest sample is shop 3's. Pizza: bad.

Step 0 of 99
Thompson sampling night by night. Curves: each shop's belief (thicker for the shop picked). Marks on the axis: tonight's draws, labelled by shop. The largest draw wins.

Things to notice:

  • On night 1 all three curves are flat, so each shop is equally likely to win.
  • Unsure shops sometimes win the draw. A wide curve can throw a high draw even if its middle is lower.
  • Over the nights, shop 3's curve becomes the tallest and narrowest, near 0.7, and wins most draws. Shop 1's curve stays wide, because it's rarely picked once it looks bad. That's fine: it only needs to be clear that shop 1 is worse, not exactly how much worse.
DigressionAn idea from 1933, rediscoveredThompson proposed it for medical trials. It took until 2011 to become popular. · 1 min

William R. Thompson, at Yale, published the idea in 1933 in the journal Biometrika. The paper's title says what it computes: "On the likelihood that one unknown probability exceeds another in view of the evidence of two samples". His setting was two medical treatments: give each new patient the treatment that, by the evidence so far, has the best chance of being better.

For decades the idea got little attention, partly because there was no proof of how well it did. In 2011, Olivier Chapelle and Lihong Li tested it on simulated and real data and found it highly competitive with UCB-style methods. Analyses soon followed showing that it matches the Lai–Robbins bound for 0/1 rewards. It's now widely used.

The race

Now put the three methods side by side on the three shops: ε-greedy with ε = 0.1, UCB1, and Thompson sampling. Each plays 100 runs of 5,000 nights.

Predict first

After 5,000 nights, which method has the lowest average regret?

Playing the first runs…

Runs played: 0 of 100. After 5,000 nights: ε-greedy, ε = 0.1: 0.0; UCB1: 0.0; Thompson sampling: 0.0.

Average total regret over 100 runs of 5,000 nights (band: 95% confidence interval of the mean). The runs are played in small batches, so the curves fill in over a few seconds.

Things to notice:

  • ε-greedy's regret is a straight line. It adds about 0.1×0.17≈0.0170.1 \times 0.17 \approx 0.017 every night, forever, from its random nights.
  • UCB1's and Thompson's curves bend over. Their regret grows like ln⁡t\ln t: each doubling of the nights adds about the same amount.
  • UCB1 starts behind ε-greedy. Its bonus with c=2c = \sqrt{2} is cautious, so it explores a lot early. Its curve flattens, though, and it passes ε-greedy at about night 3,800.
  • Thompson sampling is lowest throughout: about 13 after 1,000 nights and 17 after 5,000.

UCB1's caution is the price of its guarantee: the bonus must work for every bandit with rewards between 0 and 1. With a smaller cc, UCB explores less. The PyTorch run below shows c=0.5c = 0.5 doing about as well as Thompson sampling on these shops. Too small a cc, though, and UCB can lock onto a worse shop, as greedy does.

In PyTorch

As in the last lesson, every tensor has one row per run. UCB first. It reuses argmax_random_ties and epsilon_greedy from the bandits lesson's file:

UCB, batched over runs
def ucb(
    runs: int = 1000,
    nights: int = 1000,
    c: float = math.sqrt(2),
    generator: torch.Generator | None = None,
    uniforms: torch.Tensor | None = None,
) -> dict[str, torch.Tensor]:
    """UCB: try each shop once, then pick the highest estimate + c·√(ln t / n).

    Two uniforms per run per night: a tie-break, then the pizza. Pass `uniforms`
    (runs, nights, 2) to replay given numbers.
    """
    k = SHOPS.shape[0]
    if uniforms is None:
        uniforms = torch.rand(runs, nights, 2, generator=generator, dtype=torch.float64)
    Q = torch.zeros(runs, k, 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):
        if t < k:
            shop = torch.full((runs,), t)  # first, one try each
        else:
            bonus = c * torch.sqrt(math.log(t) / N)  # (runs, k), big where N is small
            shop = argmax_random_ties(Q + bonus, uniforms[:, t, 0])
        reward = (uniforms[:, t, 1] < SHOPS[shop]).double()
        N[rows, shop] += 1
        Q[rows, shop] += (1 / N[rows, shop]) * (reward - Q[rows, shop])
        choices[:, t] = shop
    regret = (SHOPS.max() - SHOPS[choices]).cumsum(dim=1)  # (runs, nights)
    return {"choices": choices, "regret": regret, "estimates": Q, "counts": N}
  • c * torch.sqrt(math.log(t) / N) computes all the bonuses at once, for every run and every shop. math.log(t) is one number, and dividing by the (runs, k) tensor N broadcasts it.
  • SHOPS[choices] looks up each chosen shop's chance, giving a (runs, nights) tensor. Then cumsum(dim=1) adds up the regret.
  • Fed the figures' random numbers, this makes exactly the same choices as the TypeScript. The tests check it.

Thompson sampling uses torch.distributions. Beta accepts tensors of counts, so one object holds every run's beliefs about every shop:

Thompson sampling with torch.distributions.Beta
def thompson(runs: int = 1000, nights: int = 1000, generator: torch.Generator | None = None) -> dict[str, torch.Tensor]:
    """Thompson sampling: each shop's belief is Beta(1 + good, 1 + bad).

    Each night, draw one plausible chance per shop from its belief and pick the largest.
    """
    k = SHOPS.shape[0]
    good = torch.zeros(runs, k, dtype=torch.float64)
    bad = torch.zeros(runs, k, dtype=torch.float64)
    rows = torch.arange(runs)
    choices = torch.empty(runs, nights, dtype=torch.long)
    for t in range(nights):
        belief = Beta(1 + good, 1 + bad)  # a batch of runs × k Beta distributions
        draws = belief.sample()  # (runs, k) one plausible chance per shop
        shop = draws.argmax(dim=1)
        u = torch.rand(runs, generator=generator, dtype=torch.float64)
        reward = (u < SHOPS[shop]).double()
        good[rows, shop] += reward
        bad[rows, shop] += 1 - reward
        choices[:, t] = shop
    regret = (SHOPS.max() - SHOPS[choices]).cumsum(dim=1)
    return {"choices": choices, "regret": regret, "good": good, "bad": bad}
  • Beta(1 + good, 1 + bad) is a batch of runs × 3 Beta distributions. .sample() draws one value from each, a (runs, 3) tensor.
  • draws.argmax(dim=1) picks the largest draw in each run. Exact ties between continuous draws don't happen, so no tie-break is needed.
  • good[rows, shop] += reward and bad[rows, shop] += 1 - reward update the counts. That's all the learning there is.

The race, and the Beta numbers from the worked example:

The race
torch.manual_seed(0)  # Beta.sample uses the global generator
nights = 5000
g = torch.Generator().manual_seed(0)
results = {
    "epsilon-greedy 0.1": epsilon_greedy(0.1, runs=500, nights=nights, generator=g),
    "UCB1 (c = √2)": ucb(runs=500, nights=nights, generator=g),
    "UCB, c = 0.5": ucb(runs=500, nights=nights, c=0.5, generator=g),
    "Thompson sampling": thompson(runs=500, nights=nights, generator=g),
}
for name, res in results.items():
    at = res["regret"].mean(dim=0)  # average over runs
    print(f"{name:<19} regret after 500: {at[499]:5.1f}   1,000: {at[999]:5.1f}   5,000: {at[-1]:5.1f}")
epsilon-greedy 0.1  regret after 500:  19.9   1,000:  29.0   5,000:  96.0
UCB1 (c = √2)       regret after 500:  32.8   1,000:  47.5   5,000:  88.6
UCB, c = 0.5        regret after 500:   9.8   1,000:  11.6   5,000:  15.6
Thompson sampling   regret after 500:  11.3   1,000:  13.2   5,000:  17.7
Beta(4, 2)
belief = Beta(torch.tensor(4.0), torch.tensor(2.0))  # 3 good pizzas and 1 bad, plus the flat start
print(f"mean {belief.mean:.3f}, peak {belief.mode:.3f}, sd {belief.stddev:.3f}")
mean 0.667, peak 0.750, sd 0.178

These are 500 runs from PyTorch's own random numbers, so they differ a little from the figure's 100. The story is the same. Beta also gives the mean, peak (.mode) and standard deviation (.stddev) directly.

Putting it together

Take one night where the three shops stand like this, after t=20t = 20 nights:

ShopTriesGoodEstimate
1300
2630.5
31180.73
  • ε-greedy picks shop 3, the highest estimate, with chance 0.9+0.1/3≈0.930.9 + 0.1/3 \approx 0.93. Otherwise it picks at random. It ignores that shop 2 has had only 6 tries.
  • UCB1 adds bonuses 2ln⁡20/N\sqrt{2 \ln 20 / N}: 1.41, 1.00 and 0.74. The scores are 1.41, 1.50 and 1.47, so it picks shop 2.
  • Thompson sampling draws one value from each of Beta(1,4)\text{Beta}(1, 4), Beta(4,4)\text{Beta}(4, 4) and Beta(9,4)\text{Beta}(9, 4). Shop 3 usually wins, shop 2 sometimes does, and shop 1 rarely does.

Both smarter methods explore the shops whose value is still in doubt, and stop wasting nights on those that are already settled. That's why their regret grows like ln⁡t\ln t instead of in a straight line.

The UCB idea comes back in the MCTS lesson, where UCT uses it to choose which moves to explore in a game tree. Bandits return in depth in the Auctions and mechanism design course.

Common misconceptions

"UCB picks the shop with the highest estimate." It picks the highest estimate plus bonus. In the worked example, the shop with the highest estimate lost.

"A shop with lots of evidence beats an unsure shop with the same estimate." For exploring, it's the other way round. UCB gives the unsure shop the bigger bonus, and Thompson sampling gives it the wider curve. Both try it, because there's more to learn there.

"Thompson sampling picks the shop with the highest mean belief." That would be greedy. It picks the highest draw, which is random. That randomness is how it explores.

"The Beta distribution's peak and mean are the same." After 3 good and 1 bad, the peak is 0.75 and the mean is 0.67. The flat start pulls the mean toward 0.5. With many pizzas the two agree.

"UCB1 always beats ε-greedy." Over 1,000 nights on these shops, ε-greedy with ε = 0.1 has lower regret. UCB1's regret grows more slowly, so it wins in the long run, but its cautious bonus costs it early on.

Recap

  • Explore where you're unsure. An estimate after nn tries is uncertain by about 1/n1/\sqrt{n} times one reward's standard deviation.
  • Optimism under uncertainty: treat each option as good as it plausibly could be, and pick the best.
  • UCB picks the highest Q(a)+cln⁡t/N(a)Q(a) + c\sqrt{\ln t / N(a)}. UCB1 uses c=2c = \sqrt{2}, a bonus that comes from Hoeffding's bound.
  • The Beta distribution Beta(1+s,1+f)\text{Beta}(1 + s, 1 + f) is the belief about a chance after ss successes and ff failures, starting flat. Its mean is (1+s)/(2+s+f)(1 + s)/(2 + s + f).
  • Thompson sampling draws one value from each option's belief and picks the largest. Each option is picked as often as it's probably the best.
  • UCB and Thompson sampling have regret that grows like ln⁡t\ln t; ε-greedy's grows in a straight line. On the three shops, Thompson sampling did best.
  • PyTorch names in this lesson: torch.distributions.Beta with .sample(), .mean, .mode and .stddev; torch.sqrt, math.log with broadcasting, argmax(dim=1) and cumsum.