Simple Algorithm
Reinforcement Learning · Bootstrapping · 22 min

Optimism: Upper Confidence Bounds

Optimism in the face of uncertainty, UCB1 and logarithmic regret.

Greedy play fails because it trusts its estimates; ε-greedy fails because it explores blindly forever. Optimism fixes both with one rule: act as if every arm is as good as the data still allow. Built from a concentration inequality, the rule becomes UCB1, whose regret grows only logarithmically, and the same rule reappears in tree search, in exploration of whole MDPs and in the bonuses of deep RL agents.

What you’ll learn

  • State Hoeffding's inequality and turn it into an upper confidence bound on an arm's mean.
  • Implement UCB1 and explain its index as optimism in the face of uncertainty.
  • Explain why each suboptimal pull shrinks its own bonus, and state UCB1's logarithmic regret bound, its conditions and its gap-free form.
  • Compare UCB1 with ε-greedy and Thompson sampling in simulation, and explain where its constants hurt.
  • Recognize the UCB rule in Monte Carlo tree search and in the exploration bonuses of reinforcement learning.

Optimism in the face of uncertainty

Every arm has a range of means that the data so far cannot rule out. Optimism in the face of uncertainty says: score each arm by the top of its range, and play the arm with the highest score. The rule is self-correcting. If the chosen arm really is as good as its optimistic score, playing it costs little. If it is not, playing it produces exactly the data that lower its score. Either you earn or you learn, and arms that are clearly bad stop being played because their optimistic scores fall below the best arm's.

Optimism is not wishful thinking: the top of the range is a calibrated confidence bound, so the score of the best arm sits above its true mean with high probability. That single property, the optimal arm is rarely underestimated, drives every analysis in this lesson.

Think first A confidence bound can fail in two directions. Which failure is dangerous for an optimistic algorithm: a suboptimal arm's upper bound that is too high, or the best arm's upper bound that is too low?

The second. A suboptimal arm whose bound is too high gets a few extra pulls, and those pulls bring its average and its bonus down: the error corrects itself. If the best arm's bound falls below a suboptimal arm's mean, the best arm can stop being played, and since it is not played its estimate does not improve. Its bonus does grow slowly, through the ln⁡t\ln t term, so it is eventually retried, but meanwhile regret accrues at a constant rate. This is why the confidence level must tighten over time, making such failures rarer as tt grows.

Confidence bounds from Hoeffding’s inequality

DerivationFrom a tail bound to UCB1’s bonus
  1. e−2nε2=δ⟺ε=ln⁡(1/δ)2n,Pr⁡(μ>μ^n+ln⁡(1/δ)2n)≤δe^{-2n\varepsilon^2}=\delta\quad\Longleftrightarrow\quad\varepsilon=\sqrt{\frac{\ln(1/\delta)}{2n}},\qquad\Pr\Big(\mu>\hat\mu_n+\sqrt{\tfrac{\ln(1/\delta)}{2n}}\Big)\le\delta

    Set the lower-tail probability equal to a confidence level δ\delta and solve for ε\varepsilon. With probability at least 1−δ1-\delta the mean lies below the upper confidence bound:

  2. ln⁡(t4)2n=2ln⁡tn\sqrt{\frac{\ln(t^4)}{2n}}=\sqrt{\frac{2\ln t}{n}}

    An algorithm consults the bound in every round, so the failure probability must shrink as rounds accumulate: a union bound over rounds, and over the possible sample counts, must stay summable. UCB1 takes δ=t−4\delta=t^{-4} in round tt:

  3. So UCB1's index is a Hoeffding upper confidence bound at confidence level t−4t^{-4}. Its bonus shrinks like 1/ni1/\sqrt{n_i} as an arm is played and grows like ln⁡t\sqrt{\ln t} while it is not.

Predict before you look

Rewards lie in [0,1][0,1]. After n=100n=100 pulls, how wide is the Hoeffding margin ln⁡(1/δ)/(2n)\sqrt{\ln(1/\delta)/(2n)} at confidence level δ=0.05\delta=0.05?

Show the answer

0.12

ln⁡20/200=2.996/200≈0.122\sqrt{\ln20/200}=\sqrt{2.996/200}\approx0.122. With probability at least 95%, the mean is at most the average plus 0.12. Quadrupling the data halves the margin (0.061 at n=400n=400), and asking for more confidence widens it only logarithmically (0.152 at δ=0.01\delta=0.01).

Pulls nnδ=0.05\delta=0.05δ=0.01\delta=0.01UCB1 at t=1000t=1000, 2ln⁡t/n\sqrt{2\ln t/n}
250.2450.3030.743
1000.1220.1520.372
4000.0610.0760.186
Confidence margins for rewards in [0,1][0,1]. UCB1's bonus is much wider than a 95% interval: at t=1000t=1000 its level t−4=10−12t^{-4}=10^{-12} is extremely conservative, the price of a guarantee that holds uniformly over all rounds and counts.

UCB1

python
import numpy as np

def ucb1(pull, k, T):
    """pull(i) returns a reward in [0, 1] from arm i. Runs UCB1 for T >= k rounds."""
    n = np.zeros(k)                      # pulls per arm
    mean = np.zeros(k)                   # sample averages
    for t in range(1, T + 1):
        if t <= k:
            i = t - 1                    # play every arm once
        else:
            i = int(np.argmax(mean + np.sqrt(2 * np.log(t) / n)))
        r = pull(i)
        n[i] += 1
        mean[i] += (r - mean[i]) / n[i]  # incremental average
    return n, mean

UCB1 (Auer, Cesa-Bianchi & Fischer, 2002), adapted from an index policy of Agrawal (1995). It is deterministic given the rewards, needs no parameter and no horizon, and costs O(K)\order K per round.

Check your understanding

An arm has not been pulled for a long time while the others have. What happens to its UCB1 index?

  1. It stays fixed, because its average and count do not change
  2. It rises slowly, because ln⁡t\ln t grows while its count stays fixed, so the arm is eventually pulled again
  3. It falls, because the other arms' indices rise
  4. It becomes infinite after a fixed number of rounds
Show the answer

B. It rises slowly, because ln⁡t\ln t grows while its count stays fixed, so the arm is eventually pulled again

The bonus 2ln⁡t/ni\sqrt{2\ln t/n_i} grows with tt when nin_i is frozen, so no arm is ever abandoned for good. Because the growth is only logarithmic, a clearly bad arm is retried rarely: its count grows like ln⁡t\ln t, which is exactly the logarithmic regret.

Why the regret is logarithmic

DerivationA back-of-the-envelope count
  1. μ^i+2ln⁡tni ≥ μ⋆\hat\mu_i+\sqrt{\frac{2\ln t}{n_i}}\ \ge\ \mu^\star

    Suppose every confidence bound holds. Then the best arm's index is at least μ⋆\mu^\star, so a suboptimal arm ii is played in round tt only if its own index reaches μ⋆\mu^\star:

  2. μi+22ln⁡tni ≥ μ⋆⟺ni ≤ 8ln⁡tΔi2\mu_i+2\sqrt{\frac{2\ln t}{n_i}}\ \ge\ \mu^\star\quad\Longleftrightarrow\quad n_i\ \le\ \frac{8\ln t}{\Delta_i^2}

    Its average is also at most its mean plus the margin, μ^i≤μi+2ln⁡t/ni\hat\mu_i\le\mu_i+\sqrt{2\ln t/n_i}. Combine the two and use μ⋆−μi=Δi\mu^\star-\mu_i=\Delta_i:

  3. RT=∑iΔi E[Ni(T)] ≲ ∑i:Δi>08ln⁡TΔiR_T=\sum_i\Delta_i\,\E[N_i(T)]\ \lesssim\ \sum_{i:\Delta_i>0}\frac{8\ln T}{\Delta_i}

    So arm ii stops being played once it has about 8ln⁡T/Δi28\ln T/\Delta_i^2 pulls, and each pull costs Δi\Delta_i. The failures of the bounds have probability about t−4t^{-4} for each round and each pair of counts, which sums to a constant. Regret, by the decomposition of Multi-Armed Bandits & Regret:

Predict before you look

On the regret lab's 'easy' preset the best arm pays 0.9 and the runner-up 0.7 (Δ=0.2\Delta=0.2). At T=2,000T=2{,}000, how many pulls of the runner-up does the leading term 8ln⁡T/Δ28\ln T/\Delta^2 allow?

Show the answer

1520

8ln⁡2000/0.04=8×7.6/0.04≈1,5208\ln2000/0.04=8\times7.6/0.04\approx1{,}520: three quarters of the horizon. At this horizon the guarantee says almost nothing, although UCB1 does far better in practice: in the regret lab it puts about 86% of its 2,000 pulls on the best arm, so all four suboptimal arms together get about 280. The factor 8 comes from the worst case of the analysis; the asymptotic analysis of The Regret of UCB, Proved brings it down to 2, and KL-UCB further to the Lai–Robbins constant.

DerivationGap-free: order √(KT log T)
  1. RT ≤ TΔ+8Kln⁡TΔ+(1+π23)∑jΔjR_T\ \le\ T\Delta+\frac{8K\ln T}{\Delta}+\Big(1+\frac{\pi^2}{3}\Big)\sum_j\Delta_j

    The bound 8ln⁡T/Δi8\ln T/\Delta_i blows up for tiny gaps, but a tiny gap also makes each mistake cheap. Fix a threshold Δ>0\Delta>0. Arms with Δi<Δ\Delta_i<\Delta cost at most Δ\Delta per pull, at most TΔT\Delta in total; the others obey the theorem with 1/Δi≤1/Δ1/\Delta_i\le1/\Delta:

  2. RT ≤ 28KTln⁡T+(1+π23)∑jΔj = O(KTlog⁡T)R_T\ \le\ 2\sqrt{8KT\ln T}+\Big(1+\frac{\pi^2}{3}\Big)\sum_j\Delta_j\ =\ \order{\sqrt{KT\log T}}

    Balance the first two terms at Δ=8Kln⁡T/T\Delta=\sqrt{8K\ln T/T}:

  3. No algorithm can beat order KT\sqrt{KT} on every instance (Regret Lower Bounds), so UCB1 is within a log⁡T\sqrt{\log T} factor of the best worst-case guarantee, while also being logarithmic on every fixed instance.

UCB in practice, and beyond bandits

Tuning the bonus. Practitioners often scale the bonus, cln⁡t/nic\sqrt{\ln t/n_i}, and tune cc (Sutton and Barto use c=2c=2 on their testbed); a smaller cc explores less and can win at short horizons, at the cost of the guarantee. UCB1-Tuned replaces the range bound by the arm's empirical variance, (ln⁡t/ni)min⁡{1/4, Vi}\sqrt{(\ln t/n_i)\min\{1/4,\,V_i\}} with ViV_i the sample variance plus a correction; Auer et al. found it substantially better than UCB1 in essentially all their experiments but could not prove a regret bound. UCB-V (Audibert, Munos & Szepesvári, 2009) obtains a provable variance-adaptive index from an empirical Bernstein inequality. KL-UCB and MOSS sharpen the constant and remove the log⁡T\sqrt{\log T} (The Regret of UCB, Proved).

Optimism versus posterior sampling. On the bandit widget above Thompson sampling beat UCB1 by a factor of three, and this is common in experiments. Both have logarithmic regret; they differ in constants and in how they explore: UCB's bonus is a worst-case width that must hold for every plausible instance, while a posterior sample is wide only where the data leave real doubt.

Tree search. UCT (Kocsis & Szepesvári, 2006) treats every node of a search tree as a bandit over its children and selects the child maximizing Qˉ+cln⁡Nparent/Nchild\bar Q+c\sqrt{\ln N_{\text{parent}}/N_{\text{child}}}, which turns Monte Carlo rollouts into a focused, asymptotically consistent search (Monte Carlo Tree Search). AlphaZero's PUCT rule descends from it, with a learned prior shaping the bonus.

Reinforcement learning. In an MDP the same idea becomes an exploration bonus added to the reward, r(s,a)+β/N(s,a)r(s,a)+\beta/\sqrt{N(s,a)} as in MBIE-EB (Strehl & Littman, 2008), or confidence sets over whole models, as in UCRL2 and UCBVI. Deep RL agents replace the counts N(s,a)N(s,a) by pseudo-counts and prediction errors.

Check your understanding

Why can't UCB1's regret theorem be applied verbatim at an internal node of a Monte Carlo search tree?

  1. Because tree nodes have more than two children
  2. Because rewards in games are not in [0,1][0,1]
  3. Because UCB1 needs to know the horizon
  4. Because a child's returns are not i.i.d.: they drift as the search below that child improves its own choices
Show the answer

D. Because a child's returns are not i.i.d.: they drift as the search below that child improves its own choices

The value observed through a child depends on the policy used deeper in the tree, which keeps changing as statistics accumulate, so each node faces a nonstationary bandit. Kocsis and Szepesvári analyzed UCT under this drift, showing that the bias at the root vanishes as the number of simulations grows.

Key takeaways

  • Optimism in the face of uncertainty plays the arm with the highest plausible mean: either the guess is right and you earn, or it is wrong and the pull corrects it.
  • Hoeffding's inequality gives the upper confidence bound μ^n+ln⁡(1/δ)/(2n)\hat\mu_n+\sqrt{\ln(1/\delta)/(2n)} for rewards in [0,1][0,1]; UCB1's bonus 2ln⁡t/ni\sqrt{2\ln t/n_i} is this bound at level δ=t−4\delta=t^{-4}.
  • A suboptimal arm stops being played once its bonus is about Δi/2\Delta_i/2, after about 8ln⁡T/Δi28\ln T/\Delta_i^2 pulls; UCB1's regret is at most 8∑iln⁡T/Δi+O(1)8\sum_i\ln T/\Delta_i+\order{1} for rewards in [0,1][0,1], and O(KTlog⁡T)\order{\sqrt{KT\log T}} in the worst case.
  • The guarantee fixes the rate, not the constant: at short horizons UCB1's conservative bonus can lose to tuned ε-greedy and often loses to Thompson sampling; variance-aware and KL-based indices narrow the gap.
  • The UCB rule reappears as UCT in tree search and as exploration bonuses and optimistic models in reinforcement learning.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

UCB1's bonus 2ln⁡t/ni\sqrt{2\ln t/n_i} equals the Hoeffding margin ln⁡(1/δ)/(2ni)\sqrt{\ln(1/\delta)/(2n_i)} for which confidence level?

  1. δ=0.05\delta=0.05 in every round
  2. δ=1/t\delta=1/t
  3. δ=t−4\delta=t^{-4}
  4. δ=e−t\delta=e^{-t}
Show the answer

C. δ=t−4\delta=t^{-4}

ln⁡(1/δ)/(2n)=2ln⁡t/n\ln(1/\delta)/(2n)=2\ln t/n gives ln⁡(1/δ)=4ln⁡t\ln(1/\delta)=4\ln t, so δ=t−4\delta=t^{-4}. The failure probability shrinks fast enough that, summed over all rounds and sample counts, failures contribute only a constant to the regret.

Question 2

Which statement about UCB1 on a fixed stochastic bandit is true?

  1. It never stops pulling a suboptimal arm entirely, but pulls it only O(log⁡T)\order{\log T} times
  2. It stops pulling a suboptimal arm after exactly 8ln⁡T/Δi28\ln T/\Delta_i^2 pulls
  3. It needs to know the horizon TT to set its bonus
  4. Its regret on a fixed instance grows like T\sqrt T
Show the answer

A. It never stops pulling a suboptimal arm entirely, but pulls it only O(log⁡T)\order{\log T} times

The ln⁡t\ln t in the bonus keeps every arm's index creeping up while it is idle, so every arm is retried forever, but ever more rarely: about log⁡T/Δi2\log T/\Delta_i^2 pulls in total, hence logarithmic regret on any fixed instance.

Question 3

UCB1's bound 8∑iln⁡T/Δi8\sum_i\ln T/\Delta_i is huge when some gap is tiny. Why does that not make UCB1's worst-case regret huge?

  1. Because tiny gaps never occur in practice
  2. Because each pull of an arm with a tiny gap costs only that gap, so such arms contribute at most TΔT\Delta; balancing the two regimes gives O(KTlog⁡T)\order{\sqrt{KT\log T}}
  3. Because UCB1 eliminates arms with tiny gaps
  4. Because the bound holds only for gaps above 0.1
Show the answer

B. Because each pull of an arm with a tiny gap costs only that gap, so such arms contribute at most TΔT\Delta; balancing the two regimes gives O(KTlog⁡T)\order{\sqrt{KT\log T}}

Split the arms at a threshold Δ\Delta: below it regret is at most TΔT\Delta, above it at most 8Kln⁡T/Δ8K\ln T/\Delta. Choosing Δ=8Kln⁡T/T\Delta=\sqrt{8K\ln T/T} gives O(KTlog⁡T)\order{\sqrt{KT\log T}} on every instance.

Question 4

Why does UCB add the confidence bonus to the average instead of subtracting it?

  1. Because rewards are nonnegative
  2. Because adding makes the index unbiased
  3. Because subtracting would make the algorithm randomized
  4. Because subtracting would make rarely tried arms look worse, so they would never be tried and greedy lock-in would become systematic
Show the answer

D. Because subtracting would make rarely tried arms look worse, so they would never be tried and greedy lock-in would become systematic

Optimism sends the learner to the arms it knows least about, where the information is. Pessimism (a lower bound) is right only when no more data can be collected, as in offline RL.

Go deeper

Further reading

  • P. Auer, N. Cesa-Bianchi & P. Fischer, "Finite-time analysis of the multiarmed bandit problem," Machine Learning 47, 235–256 (2002).
  • W. Hoeffding, "Probability inequalities for sums of bounded random variables," Journal of the American Statistical Association 58(301), 13–30 (1963).
  • T. Lattimore & C. Szepesvári, Bandit Algorithms, ch. 5, 7 and 8 (Cambridge University Press, 2020).
  • L. Kocsis & Cs. Szepesvári, "Bandit based Monte-Carlo planning," European Conference on Machine Learning (2006).