Five slot machines, one hidden best. You see only the payout of the machine you pull. Pure greed locks onto a wrong machine in about 1 run in 4. UCB and Thompson sampling find the best one, and their regret stops growing.
Pick a strategy and watch it play 600 pulls. Compare the regret curves. Then we build, piece by piece, the scoreboard, three ways to explore, and a reward learned from "A beat B".
You need an average, what a probability is and a little Python. No reinforcement learning. We build the rest from zero.
Lecture 19 of 25 in Introduction to Robot Learning, CMU 16-831 (Spring 2024), taught by Guanya Shi. Slides on the course lectures page. Every idea is re-taught here in our own words and devices. Next: Lecture 20, Exploration.
Illustrative toy. Payout rates 0.20, 0.35, 0.80, 0.50, 0.40; each pull pays 1 or 0. Every strategy pulls each machine once first. ε = 0.1, UCB constant c = 0.5. Faint curves are each strategy's last full run.
Chapter 0
Pull machines whose payout rates are secret, and feel why every test pull costs you
You stand before five slot machines. Each pays a coin at its own secret rate. You have one evening and a stack of coins. Which machine do you keep pulling?
The only way to learn a rate is to pull and see. A pull on a weak machine is a coin you did not spend on the strong one. And a machine you skip tells you nothing.
Press a machine to pull it once. You see its coin, or nothing, and its running average. Pull 15 times, guess the best, then reveal.
Illustrative toy. The secret rates are 0.30, 0.60, 0.45, 0.15 and 0.50.
This is the multi-armed bandit: several actions, each with an unknown average reward, and you see only the reward of the action you take. A slot machine was once called a one-armed bandit. The lecture calls it the simplest reinforcement learning problem, with many open questions.
It is not only casinos. Which ad to show: the arms are ads, the reward is a click. Which treatment for the next patient: a wasted pull is a patient on the worse drug. Every pull must choose between exploit (pull what looks best) and explore (pull what you know too little about).
The symptom is a choice made on three lucky pulls. To measure it, count the pulls behind each estimate. The fix is a rule that decides when a count is enough: Chapters 3 to 6.
Chapter 1
Name the parts, estimate each arm by its average, and see how the pull count sets your trust
The setup has four parts, and nothing more.
There is no state. Pulling arm 3 does not move you anywhere, and the next round looks the same. That is why the bandit shows the explore and exploit tension alone, with nothing mixed in.
How good is an arm? Call the number of times you pulled arm a N(a), and the rewards it gave r-1 to r-N. The estimate Q(a) is their average.
Q of a equals one over N of a, times the sum over i of r-i.
Add up every reward r-i that arm a gave you. Divide by the count N of a. The result is Q of a.
With made-up numbers: five pulls gave 1, 0, 1, 1, 0. Q = 3 / 5 = 0.6.
Code keeps a running form, so it never stores old rewards. Each new reward moves Q a fraction 1/N of the way toward it.
Q ← Q + (r − Q) / N sixth pull pays 1: 0.6 + (1 − 0.6) / 6 = 0.667
The dashed line is the true mean, 0.60. The blue curve is Q after each pull. The band is the typical error. Raise the noise and draw a new run.
Illustrative toy with Gaussian rewards. The band is 2 × noise / √N.
The typical error falls like one over the square root of N. With noise 0.25 and N = 25, it is 0.25 / 5 = 0.05. Four times the pulls halves it. So N(a) is your trust in Q(a).
The symptom is an arm ranked first on two pulls. To measure it, print N next to every Q. The fix is to treat a small N as a wide error, which UCB does in Chapter 4.
Chapter 2
Subtract your reward from a genie's, and learn the one shape that marks a learner
Total reward is an unfair score: it depends on how generous the machines are. So the lecture compares you with a genie. The genie knows every mean and pulls the best arm, mean μ*, on every round.
Call the arm you pulled on round t a-t, and the horizon T. Your regret is what the genie expects to earn minus what you expect to earn.
Regret of T equals T times mu-star, minus the sum over t of mu of a-t.
Multiply the best mean mu-star by T: that is the genie's total. Add up the true means of the arms you pulled. Subtract. Each pull of a worse arm adds its gap, mu-star minus its mean.
With made-up numbers: means 0.8, 0.5 and 0.2, T = 10. You pull them 6, 3 and 1 times. Regret = 10 × 0.8 − (4.8 + 1.5 + 0.2) = 1.5. Gap form: 3 × 0.3 + 1 × 0.6 = 1.5.
Regret never goes down. The question is how fast it grows. A learner that never stops making the same mistake grows it like a constant times T. We want the average regret per round to fall to zero.
Regret of T over T goes to zero as T goes to infinity.
Divide the total regret by T. If that average per round shrinks toward zero, the agent is no-regret: its regret is sublinear, growing slower than T.
With made-up curves at T = 1,000,000: 0.035 × T = 35,000, so 0.035 per round forever. 15 × ln T = 207, so 0.0002 per round.
Red grows like T: a learner that keeps paying. Green grows like the square root of T and like log T: learners that bend over. Drag the horizon.
Illustrative constants: 0.035 × T, 2√T, 15 ln T. The shape, not the constant, decides who wins in the end.
The symptom is a regret curve that stays straight. To measure it, plot regret against T and check the slope over the last tenth. The fix is exploration that fades as estimates sharpen.
Chapter 3
Watch greed lock onto a wrong arm, then buy your way out with a few random pulls
The obvious rule is greedy: always pull the arm with the highest Q. Say the best machine pays nothing on its first pull and a weaker one pays a coin. Greedy now trusts the weaker one and never pulls the best one again. It never collects the data that would correct it.
ε-greedy (epsilon-greedy) adds a coin flip. With chance ε it pulls a random arm. Otherwise it pulls the greedy arm. Call the number of arms k and the chance of pulling arm a π(a).
pi of a equals one minus epsilon, plus epsilon over k, if a is the arg-max of Q; and epsilon over k otherwise.
Flip a coin that lands "explore" with chance epsilon. On explore, pick any of the k arms at random. Otherwise pull the arm with the largest Q. The greedy arm gets both shares.
With made-up numbers: k = 5, ε = 0.1. The greedy arm gets 0.9 + 0.02 = 0.92. Each other arm gets 0.02. Check: 0.92 + 4 × 0.02 = 1.
Five arms; the middle one is best. Each bar is the share of pulls an arm got, averaged over 200 runs of 600 pulls. Slide ε from 0 (pure greed) upward.
Illustrative toy: rates 0.20, 0.35, 0.80, 0.50, 0.40, each arm pulled once first. A run counts as stuck when its most-pulled arm is not the best.
In our runs, greed ends stuck on a wrong arm about 22 to 25 times in 100. At ε = 0.1 that falls to about 2, and regret nearly halves. At ε = 0.3 nothing gets stuck, but regret doubles: too many pulls go to losers.
A fixed ε never stops paying. Once the agent knows the best arm, it still explores ε of the time. Each random pull costs the average gap. With gaps 0.6, 0.45, 0, 0.3 and 0.4, the average is 0.35. So the cost is 0.1 × 0.35 = 0.035 per round, the red line of Chapter 2.
The symptom is a regret curve that keeps a steady slope after the agent knows the best arm. To measure it, compare the late slope with ε times the average gap. The fix is to shrink ε over time, or to explore where you are unsure, as UCB does.
Chapter 4
Give each arm the best value it could still have, pull the highest, and watch the windows shrink
From Chapter 1, an arm with a small count has a wide error. A concentration inequality makes that exact. The lecture uses Hoeffding's inequality: with high chance, the true mean lies within a window around Q, and the window narrows as N grows.
UCB, the upper confidence bound, acts on the top of that window. Call the round number t and the size of the optimism bonus c. Each arm gets a score.
UCB of a equals Q of a, plus c times the square root of log t over N of a.
For each arm, divide log t by its count N of a. Take the square root and multiply by c: that is the bonus. Add it to Q of a. Pull the arm with the largest total.
With made-up numbers: Q = 0.5, N = 4, t = 20, c = 0.5. ln 20 = 3.00; 3.00 / 4 = 0.75; √0.75 = 0.866; bonus 0.433. UCB = 0.933.
An arm wins for one of two reasons. Its Q is high, so it is good: exploit. Or its bonus is high, so it might be good: explore. One number does both, with no coin flip. This is optimism in the face of uncertainty.
Each blue dot is Q. The purple bar above it is the bonus; its top is the UCB. Press Pull and watch the chosen window shrink. Reveal the truth when you like.
Illustrative toy: true rates 0.45, 0.70, 0.55, c = 0.5. UCB pulls each arm once first.
Optimism corrects itself. If UCB keeps pulling a weak arm, its N grows and its top falls toward its low mean. The ignored good arm's bonus slowly rises with ln t. The good arm overtakes. For fixed gaps, UCB1's regret grows like log T (Auer, Cesa-Bianchi and Fischer, 2002).
The symptom is UCB that loses to ε-greedy on a short run. In our hero toy over 600 pulls, c = 1.41 lost about 63 to ε-greedy's 32; c = 0.5 lost about 14. To measure it, sweep c on logged data. The fix is to tune c for your horizon: too large over-explores, too small turns greedy.
Chapter 5
Push real counts through the bonus, and watch optimism pick the arm that does not look best
It is round t = 100, and c = 2. Three arms have these statistics.
| Arm | Estimate Q | Pulls N |
|---|---|---|
| A | 0.60 | 80 |
| B | 0.55 | 10 |
| C | 0.40 | 10 |
A looks best, and 80 pulls stand behind it. Which arm does UCB pull? First, ln 100 = 4.605.
bonus A = 2 × √(4.605 / 80) = 2 × 0.240 = 0.480 → UCB A = 0.60 + 0.480 = 1.080
bonus B = 2 × √(4.605 / 10) = 2 × 0.679 = 1.357 → UCB B = 0.55 + 1.357 = 1.907
bonus C = 1.357, the same count as B → UCB C = 0.40 + 1.357 = 1.757
UCB pulls B. Its estimate is 0.05 lower than A's, but its bonus is 0.877 higher. B also beats C: same bonus, higher estimate. Among arms with the same count, Q breaks the tie.
Blue is Q; purple is the bonus on top. UCB pulls the tallest stack, the one with the outline. Give B and C more pulls, or lower c, and A takes over.
The numbers at the start are the worked example. A gets the rest of the 100 pulls.
Now write the bonus yourself and confirm it picks B.
The symptom is a bonus that dwarfs the reward range: here 1.357 on rewards between 0 and 1. Then UCB explores almost blindly for a long time. To measure it, compare the largest bonus with the reward range. The fix is a smaller c, such as the square root of 2 for rewards in 0 to 1.
Chapter 6
Keep a belief curve per arm, draw one guess from each, and pull the largest
UCB keeps a range for each arm. Thompson sampling, also called posterior sampling, keeps a whole curve: a posterior, the belief over where the arm's mean lies. The idea is from 1933. Its regret proofs came around 2012.
For coin-or-nothing rewards, the belief is a Beta distribution, a curve on 0 to 1 set by two counts. Call the coins an arm paid S (successes), the blanks F (failures), and its unknown rate θ (theta). Start from a flat belief.
theta is distributed as Beta of one plus S, and one plus F.
Count the coins S and the blanks F. Add 1 to each. Those two numbers set the hump. Its mean is (1 + S) / (2 + S + F).
With made-up numbers: arm X paid 8 of 10, so Beta(9, 3), mean 0.75. Arm Y paid 1 of 2, so Beta(2, 2), mean 0.50. Y's draw beats X's draw 18 times in 100.
So Thompson pulls Y about 18 times in 100, though it believes X is better. Y's hump is wide, so a high draw is plausible. Wide belief buys exploration; a narrow belief draws near its mean and exploits.
Pink curves are beliefs; the warm ticks are the true rates. Pull an arm to feed its curve a reward. Press Draw to sample once from each curve.
Illustrative toy. We compute the pick chance on a grid of 400 points.
Now write the one line that makes a sampler Thompson.
The symptom is a sampler that keeps all its pulls on one arm from the start. To measure it, print the Beta counts per arm. The usual cause is a confident wrong prior, such as Beta(50, 1). The fix is a flat start, Beta(1, 1), unless you have real data.
Chapter 7
Run every strategy on one six-armed bandit, and read the shape of each regret curve
Six arms, one best at 0.85, one close behind at 0.75. Each strategy plays the same bandit 30 times. Each curve is its average regret over those runs.
Press Race. Lower is better. A curve that bends flat has found the best arm. Change the horizon or UCB's c and race again.
Illustrative toy: rates 0.30, 0.45, 0.50, 0.60, 0.75, 0.85; ε = 0.1; 30 runs per strategy; each arm pulled once first except by Thompson.
Read the late slopes. ε-greedy keeps climbing at a steady rate. Its cost per round is ε times the average gap: 0.1 × (0.55 + 0.4 + 0.35 + 0.25 + 0.1 + 0) / 6 = 0.0275. That is 27.5 regret per 1,000 rounds, forever.
UCB with a tuned c and Thompson bend over. Their late slope falls toward zero because their exploring fades as counts grow. The order of these two can swap between runs; both are no-regret.
| Strategy | How it explores | Late slope |
|---|---|---|
| Greedy | Never | Steady when stuck: linear |
| ε-greedy, fixed ε | At random, forever | ε × average gap: linear |
| UCB | Where the bonus is high | Falls toward 0: sublinear |
| Thompson | Where belief is wide | Falls toward 0: sublinear |
The symptom is a winner picked from one run. One run is noisy. To measure it, average many runs and look at the slope over the last tenth. The fix is to report the average and its spread, never a single curve.
Chapter 8
Read a clue before you choose, keep one estimate per clue, and beat the one-size-fits-all arm
A news feed picks a topic for each visitor. Sports fans click sports. Home cooks click recipes. A plain bandit learns one best topic for everyone. It cannot do better than the best compromise.
A contextual bandit sees a context s before it chooses: here, the visitor's type. It keeps an estimate Q(s, a) for each context and arm, and runs UCB, ε-greedy or Thompson inside each context.
| Click rate (made up) | Sports | News | Recipes |
|---|---|---|---|
| Sports fan | 0.60 | 0.25 | 0.10 |
| Home cook | 0.10 | 0.25 | 0.70 |
Work it with half the visitors of each type. One topic for all: Recipes is best, 0.5 × 0.10 + 0.5 × 0.70 = 0.40 clicks per visit. One topic per type: 0.5 × 0.60 + 0.5 × 0.70 = 0.65. Knowing the context is worth 0.25 clicks per visit.
Both learners run UCB for 3,000 visits. Grey ignores the visitor's type; teal keeps one estimate per type. Move the share of sports fans.
Illustrative toy with the click rates in the table; UCB with c = 0.5; curves are the running clicks per visit.
Q(s, a) looks like the action value in reinforcement learning, with s as the state. One thing is missing: the action does not change the next context. Add that, so actions move you to new states, and you have a full MDP. Bandit, contextual bandit, MDP: three rungs of one ladder.
The symptom is a learner that settles on a topic most visitors dislike. To measure it, split the click rate by context. The fix is to feed the context in, but only contexts that change which arm is best: each extra context splits your data.
Chapter 9
Replace the reward number with "A beat B", and fit a score for each option from the wins
How good was that robot grasp, from 0 to 100? People give unsteady scores. Ask "was A or B better?" and they answer fast and agree more. The lecture's example: a click on search result 2 says "2 beat 1" more surely than "2 is good".
The dueling bandit (Yue, Broder, Kleinberg and Joachims) shows two arms each round and sees only which one won. Good algorithms keep its regret growing like log T.
To turn wins into scores, give each option i a hidden score s-i. Call the chance that i beats j P. The Bradley-Terry model says the chance depends only on the score gap.
P of i beats j equals sigma of s-i minus s-j, which is one over one plus e to the minus s-i minus s-j.
Subtract s-j from s-i. Pass the gap through sigma. Equal scores give a coin flip; a large gap gives a near-sure win.
With made-up numbers: s-i = 2, s-j = 1. The gap is 1, and σ(1) = 0.731. Option i wins 73 times in 100.
We fit the scores to the comparisons we saw. For each comparison, call the winner's score s-w and the loser's s-l. The loss L adds up how surprised the model is.
L equals minus the sum over comparisons of log sigma of s-w minus s-l.
For each comparison, find the model's chance that the winner wins. Take its log and flip the sign. Add them all. Gradient descent moves s-w up and s-l down by (1 − that chance).
With made-up numbers: s-w = 2, s-l = 1 costs −log 0.731 = 0.313. An upset, the 1 beating the 2, costs −log 0.269 = 1.313, and pushes each score by 0.731 times the step size.
Warm bars are the hidden true scores; pink bars are the fitted ones. Add comparisons and watch the fit lock onto the truth.
Illustrative toy: true scores 2, 1, 0, −1, shown with their mean removed. Scores are fixed only up to a shared shift, so the fit pins their mean to 0.
This is the reward model of RLHF. Show a person two answers, record which one wins, fit a network's score by this loss, then train the policy to raise that score. The Reward Learning lesson follows that pipeline in full.
The symptom: fitted scores drift apart without end. The cause is an option that won every comparison, so its score can rise forever. To measure it, look for options with no losses. The fix is a small penalty on large scores, or more comparisons.
Chapter 10
Keep the strategies, the numbers, a checklist and the core code in one place
A bandit is one decision, repeated, under doubt. Regret keeps score. Greedy locks in; ε-greedy pays forever; UCB and Thompson explore where they are unsure, and stop. Preferences replace the reward number when people cannot score.
| Term | One line | Number to remember |
|---|---|---|
| Estimate | Q(a) is the average reward of arm a. | 1, 0, 1, 1, 0: Q = 0.6 |
| Regret | T · μ* minus the means you pulled. | 6, 3, 1 pulls of 0.8, 0.5, 0.2: 1.5 |
| No-regret | Regret / T goes to 0. | 15 ln T at T = 106: 0.0002 per round |
| ε-greedy | Random arm with chance ε. | k 5, ε 0.1: greedy arm 0.92 |
| Fixed ε cost | ε times the average gap, every round. | 0.1 × 0.35 = 0.035 |
| UCB | Q + c √(ln t / N); pull the largest. | A 1.080, B 1.907, C 1.757: pull B |
| Thompson | Draw from Beta(1 + S, 1 + F); pull the largest. | Beta(2, 2) beats Beta(9, 3) 18 in 100 |
| Contextual | Q(s, a): one estimate per context. | 0.65 against 0.40 clicks per visit |
| Bradley-Terry | P(i beats j) = σ(s-i − s-j). | Gap 1: 0.731 |
pythonimport numpy as np rng = np.random.default_rng(0) def ucb_pick(Q, N, t, c=0.5): if (N == 0).any(): return int(np.argmin(N)) # pull every arm once first return int(np.argmax(Q + c * np.sqrt(np.log(t) / N))) # optimism def thompson_pick(S, F): return int(np.argmax(rng.beta(1 + S, 1 + F))) # one draw per arm def update(Q, N, a, r): N[a] += 1; Q[a] += (r - Q[a]) / N[a] # running average def bt_step(s, pairs, lr=0.05): # pairs: (winner, loser) g = np.zeros_like(s) for w, l in pairs: p = 1 / (1 + np.exp(-(s[w] - s[l]))) g[w] += 1 - p; g[l] -= 1 - p s += lr * g; s -= s.mean() # pin the shared shift return s
This lesson follows Lecture 19, Bandits and Preference-Based Learning, of CMU 16-831 Introduction to Robot Learning, Spring 2024, taught by Guanya Shi. The slides are on the lectures page. UCB1 is from Auer, Cesa-Bianchi and Fischer (2002); dueling bandits from Yue, Broder, Kleinberg and Joachims. The race and contextual toys are ours.
Now press Present or Teach and explain from memory: regret, why greed locks in, the UCB bonus, and why a wide belief explores. Then go back to the five machines, press Greedy a few times, and say why it sometimes ends on the wrong one.