Bandits and Preference-Based Learning

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.

Let a strategy play five machines

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

A Row of Slot Machines

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.

Pull the machines

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 failure, as symptom, measurement and fix

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.

The road

  1. The bandit, made precise: arms, means, and the estimate Q.
  2. Regret: the score against a genie, and what sublinear means.
  3. ε-greedy: why greed locks in, and a little random exploring (the hero's first two buttons).
  4. UCB: pull the arm with the highest plausible value (the hero's third button).
  5. UCB by hand: three arms, real counts, one surprising choice.
  6. Thompson sampling: act on one random guess from your beliefs (the fourth button).
  7. The race: all strategies, one bandit, regret side by side.
  8. Contextual bandits: the best arm depends on who is in front of you.
  9. Preferences: learn a score from "A beat B", the root of RLHF.
  10. The field guide: terms, numbers, code, links and credit.
What makes the bandit problem hard, so that some pulls must look wasteful?

Chapter 1

The Bandit, Made Precise

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.

  1. There are k arms. For the casino, k machines.
  2. Each arm a has a fixed, unknown mean reward μ(a). The best mean is μ* (mu-star).
  3. On each round t, from 1 to T, the agent picks one arm a-t and gets a random reward r-t with average μ(a-t).
  4. It sees only that reward. This is bandit feedback.

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.

Say it aloud

Q of a equals one over N of a, times the sum over i of r-i.

Q(a)
Q of a the agent's estimate of arm a's mean reward, between 0 and 1 here.
N(a)
N of a how many times the agent pulled arm a so far.
Σi
the sum over i add one term for each pull of arm a, from the first to the N-th.
ri
r-i the reward from the i-th pull of arm a: 1 for a coin, 0 for nothing.
In plain words

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 numbers

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

Watch an average settle

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.

0.25

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 failure, as symptom, measurement and fix

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.

How does an arm's pull count N(a) relate to how much you should trust Q(a)?

Chapter 2

Regret: Keeping Score Against a Genie

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.

Say it aloud

Regret of T equals T times mu-star, minus the sum over t of mu of a-t.

Regret(T)
regret of T the expected reward lost to not knowing the best arm, over T rounds.
T
T the number of rounds played.
μ*
mu-star the mean reward of the best arm.
Σt
the sum over t add one term for each round, from 1 to T.
μ(at)
mu of a-t the true mean of the arm the agent pulled on round t.
In plain words

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 numbers

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.

Say it aloud

Regret of T over T goes to zero as T goes to infinity.

Regret(T)
regret of T the total regret after T rounds, from the equation above.
T
over T divide by the rounds: the average regret per round.
→ 0
goes to zero gets as small as you like.
T → ∞
as T goes to infinity if you play long enough.
In plain words

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 numbers

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.

Stretch the horizon

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.

10,000

Illustrative constants: 0.035 × T, 2√T, 15 ln T. The shape, not the constant, decides who wins in the end.

The failure, as symptom, measurement and fix

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.

An algorithm's total regret grows like log T. Is it no-regret?

Chapter 3

Epsilon-Greedy: Explore a Little on Purpose

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).

Say it aloud

pi of a equals one minus epsilon, plus epsilon over k, if a is the arg-max of Q; and epsilon over k otherwise.

π(a)
pi of a the chance that this round's pull is arm a.
1 − ε
one minus epsilon the chance of exploiting: pulling the greedy arm on purpose.
ε / k
epsilon over k the explore chance, shared out evenly over all k arms.
argmax Q
arg-max of Q the arm whose estimate Q is the largest.
In plain words

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 numbers

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.

Slide the explore rate

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.

0.00

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 failure, as symptom, measurement and fix

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.

Why does pure greedy (always pull the highest Q) often fail?

Chapter 4

UCB: Optimism in the Face of Uncertainty

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.

Say it aloud

UCB of a equals Q of a, plus c times the square root of log t over N of a.

UCB(a)
U-C-B of a the upper confidence bound: the best mean arm a could plausibly have. UCB pulls the arm with the largest one.
Q(a)
Q of a the average reward of arm a so far.
c
c how much to value exploring. UCB1 uses the square root of 2, about 1.41.
√( )
the square root of so four times the pulls halves the bonus.
ln t
log t the natural log of the total pulls so far. It grows slowly, so a neglected arm slowly gains bonus.
N(a)
N of a the pulls of arm a. More pulls, smaller bonus.
In plain words

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 numbers

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.

Pull the highest top

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 failure, as symptom, measurement and fix

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.

What does the bonus c √(ln t / N(a)) do?

Chapter 5

UCB by Hand

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.

ArmEstimate QPulls N
A0.6080
B0.5510
C0.4010

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.

Move the counts, watch the choice

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.

10 each
2.00

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 failure, as symptom, measurement and fix

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.

With Q = 0.60, 0.55, 0.40, N = 80, 10, 10, t = 100 and c = 2, why does UCB pull B and not A?

Chapter 6

Thompson Sampling: Act on One Guess From Your Beliefs

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.

  1. Keep a belief curve for each arm.
  2. Draw one random guess of the mean from each curve.
  3. Pull the arm with the largest guess. Update its curve with the reward.

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.

Say it aloud

theta is distributed as Beta of one plus S, and one plus F.

θ
theta the arm's unknown payout rate, between 0 and 1.
~
is distributed as our belief about theta has this shape.
Beta
Beta a hump on 0 to 1. Its mean is the first number over the sum of both. Bigger numbers make it narrower.
S
S the coins this arm paid so far.
F
F the pulls of this arm that paid nothing.
In plain words

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 numbers

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.

Sharpen two beliefs

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 failure, as symptom, measurement and fix

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.

In Thompson sampling, why does a barely pulled arm get explored with no bonus term?

Chapter 7

The Race

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.

Race the strategies

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.

2,000
0.50

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.

StrategyHow it exploresLate slope
GreedyNeverSteady when stuck: linear
ε-greedy, fixed εAt random, foreverε × average gap: linear
UCBWhere the bonus is highFalls toward 0: sublinear
ThompsonWhere belief is wideFalls toward 0: sublinear

The failure, as symptom, measurement and fix

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.

UCB and Thompson bend flat while fixed ε-greedy keeps climbing straight. What is this difference?

Chapter 8

Contextual Bandits

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)SportsNewsRecipes
Sports fan0.600.250.10
Home cook0.100.250.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.

Learn a feed, with and without the clue

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.

50%

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 failure, as symptom, measurement and fix

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.

What separates a contextual bandit from a full MDP?

Chapter 9

Learning From Preferences

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.

Say it aloud

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.

P(i beats j)
P of i beats j the chance a person prefers option i over option j.
σ
sigma the logistic curve: it squeezes any number into 0 to 1, with σ(0) = 0.5.
si
s-i the hidden score of option i. In RLHF, the reward model's output.
sj
s-j the hidden score of option j.
e−x
e to the minus x about 2.718 raised to minus the gap. A large gap makes it tiny.
In plain words

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 numbers

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.

Say it aloud

L equals minus the sum over comparisons of log sigma of s-w minus s-l.

L
L the loss, the negative log-likelihood. Lower is a better fit.
−
minus logs of chances are negative, so the minus makes the loss positive.
Σ
the sum over comparisons one term for each "winner beat loser" record.
log
log the natural log. A chance near 1 costs near 0; a chance near 0 costs a lot.
sw
s-w the score of the option that won this comparison.
sl
s-l the score of the option that lost it.
In plain words

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 numbers

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.

Fit scores from wins

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 failure, as symptom, measurement and fix

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.

Why does RLHF ask people for comparisons, not quality scores?

Chapter 10

The Field Guide

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.

Terms and numbers

TermOne lineNumber to remember
EstimateQ(a) is the average reward of arm a.1, 0, 1, 1, 0: Q = 0.6
RegretT · μ* minus the means you pulled.6, 3, 1 pulls of 0.8, 0.5, 0.2: 1.5
No-regretRegret / T goes to 0.15 ln T at T = 106: 0.0002 per round
ε-greedyRandom 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
UCBQ + c √(ln t / N); pull the largest.A 1.080, B 1.907, C 1.757: pull B
ThompsonDraw from Beta(1 + S, 1 + F); pull the largest.Beta(2, 2) beats Beta(9, 3) 18 in 100
ContextualQ(s, a): one estimate per context.0.65 against 0.40 clicks per visit
Bradley-TerryP(i beats j) = σ(s-i − s-j).Gap 1: 0.731

Before you ship a bandit

  1. Is there a state that your action changes? If yes, you need RL, not a bandit.
  2. Do you see a reward number you trust? If not, collect comparisons.
  3. Does the best arm depend on who is asking? If yes, use a contextual bandit.
  4. Pick UCB or Thompson over fixed ε. Tune c for your horizon.
  5. Judge it by regret averaged over many runs, never one curve.

The core in code

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

Keep going on this site

The takeaway. You cannot explore and exploit on the same pull, and you must do both. Explore where you are unsure, and let it fade as you learn.

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.

Introduction to Robot Learning · CMU 16-831 · Lecture 19: Bandits and Preference-Based Learning
Next: Exploration · Back to Gleams