Movement III: Two Random Variables
EE 520: Random Processes (Fall 2026). Instructor: John Lipor.
Load a news site, and in the few milliseconds before the page appears an algorithm decides which of several ads to put in front of you. It is running a live experiment. Each candidate ad has a click-through rate , the probability that a viewer clicks it, and nobody knows these rates in advance: a new ad might be brilliant or dead on arrival. The only way to learn an ad’s rate is to show it and count clicks, and every impression spent on a weak ad is revenue a strong ad would have earned. The system must learn and earn at the same time. This is the multi-armed bandit problem, named for a row of slot machines (“one-armed bandits”) with unknown payout rates, and the same structure decides which headline a news site leads with and which thumbnail a video gets.
The textbook answer is the A/B test: split traffic evenly for two weeks, then declare a winner. It is clean, and it is wasteful. Half the traffic goes to the loser for the whole test, even after the data are overwhelming. Large platforms instead let traffic drift toward the winner as the evidence arrives, and one of the most widely used ways to do that, Thompson sampling, owes its modern revival to exactly this setting (display advertising and news recommendation at Yahoo, website experiments at Google). It is built from nothing beyond the machinery of this course: a prior, a likelihood, and a single random draw. In practice it crushes the obvious “always show the best ad so far.”
A note on scale before we start: real click rates are a few percent. Our examples use larger rates so the arithmetic stays readable. Nothing in the mathematics depends on the scale; small rates only make learning slower, and we will say exactly how much slower.
Today we build Thompson sampling. The road there has three stages: first, Bayes’ rule when the unknown is a probability living in (the posterior becomes a density); second, the one distribution, Beta, that makes such updating a two-integer bookkeeping exercise; third, Thompson sampling, which turns that posterior directly into a sequential decision. Then we ask how good these decisions are. We will prove that “best so far” can fail forever, prove why Thompson sampling cannot, and meet the classical answer to what the best possible strategy looks like.
Until now the unknown took finitely many values and the prior was a list of numbers. Let instead be a continuous quantity with a prior density , and let the data be discrete (clicks and non-clicks on an ad). Bayes’ rule reads exactly as before, with the density in place of the prior list: This is Session 2’s Bayes rule, now with densities: posterior prior likelihood, unchanged. Only two things are new. The evidence in the denominator is now an integral rather than a finite sum, and because that denominator is just the constant that makes the posterior integrate to one, the working style is -then-normalize: carry the shape , drop every factor that does not depend on , and fix the constant at the end by recognizing the result. The next two subsections show a family for which that recognition is immediate.
Definition 1 (Beta distribution). For shape parameters , has density on with mean . The constant is whatever it must be to integrate to one; we will almost never need its value.
The two parameters trade off shape and location. Figure 1 shows the range: is flat (the uniform prior, “I know nothing”); equal large parameters concentrate the mass near ; unequal parameters skew toward the larger one. Read as “how much the prior leans toward success” and as “toward failure.”
Now feed Bernoulli data through [eq:densitybayes]. Suppose each impression of an ad is clicked independently with probability , and we observe clicks (successes) in impressions.
Proposition 1 (Beta–Bernoulli conjugacy). If the prior is and the data are successes in independent Bernoulli trials, then the posterior is
Proof. The likelihood of successes and failures is (the binomial coefficient does not depend on , so -then-normalize discards it). Multiply by the prior and collect exponents: That is the shape of a density, and the normalizing constant is forced. No integral was evaluated. ◻
This is remarkable and worth naming: the posterior lands back in the prior’s own family (the family is conjugate to Bernoulli data), so the entire effect of observations is to advance two counters, and . Learning has become bookkeeping. Whether the observations arrive all at once or one at a time makes no difference: incrementing the counters after each trial gives the same posterior, which is exactly the sequential updating a live decision-maker needs.
The posterior mean is the single number we will hand to a decision, so it is worth dissecting.
Proposition 2 (Shrinkage form of the posterior mean). With posterior ,
Proof. The Beta mean gives . Split the numerator and multiply each piece by one: which is [eq:shrinkage] with and . ◻
Read [eq:shrinkage] as a weighted average of two estimates: the raw data frequency and the prior mean . The weight on the data climbs from (no data, pure prior) toward as grows, so with enough evidence the prior washes out. Equivalently, and act as pseudo-counts: the prior behaves exactly as if we had already seen imagined successes and imagined failures before the real trials began, and the posterior mean is just the overall success fraction including those imagined trials. A concrete instance is worked in the next section.
The mean says where belief sits. Every bandit strategy below also needs to know how spread out it is, because spread is what is left to learn.
Proposition 3 (Beta variance). If with mean , then
Proof. The mean in the definition is a ratio of normalizing constants: , so for every . Use that identity twice: Then , which is [eq:betavar] because . ◻
After trials the posterior has in the denominator, so for large the posterior standard deviation is about , with . Uncertainty shrinks like : four times the data buys half the width.
This is the promised price of realistic click rates. To pin a click rate to within (ten percent of its value) takes impressions per ad, while a rate near reaches the same relative precision in about . Small rates are expensive to learn, which is exactly why wasted impressions matter to an ad platform.
Two things to carry forward. First, width is the fuel of exploration; each algorithm below spends it differently. Second, from Session 12 on, posterior variance becomes a main character, and in the Gaussian world of Session 13 it will turn out not to depend on the observed values at all. Here it does, through .
AI corner: calibration is a conditional probability. Corner 2 was about how a model speaks, how it draws a token from a distribution; this one is about whether to believe it. A predictor is calibrated if a conditional probability, nothing more. Checking calibration is estimating a Bernoulli success rate within each confidence bucket, exactly this session’s machinery pointed at the model itself: collect all the claims it stamped “ sure,” count how many were right, and form the Beta posterior over that bucket’s true accuracy. Two honest caveats. First, a language model’s confidence score is not a posterior and is routinely miscalibrated, so treating “ sure” as is a modeling decision you must audit, not a given. Second, even a perfectly calibrated flag obeys Session 2: when the base rate is extreme, the posterior can stay small no matter how confident the flag sounds.
Return to the ads, now of them. In bandit language each ad is an arm, showing it is a pull, and a click is a reward: arm pays when pulled, the are unknown, and each round (one impression) we pull one arm and see its reward. We measure a strategy by its regret: the shortfall against an oracle that always pulls the best arm, where is the arm pulled at round . Low regret means we found and stuck with the best arm quickly.
The tempting strategy, greedy, pulls each arm a few times and thereafter always pulls the one with the best empirical mean. It has a fatal failure mode: an early unlucky streak on the genuinely best arm can leave its empirical mean below a worse arm’s, after which greedy never pulls it again and so never corrects the verdict. Greedy commits before it has looked, and one bad break is permanent. That story can be made a theorem with nothing beyond Sessions 3 and 9.
Proposition 4 (Greedy can lock in forever). Take two arms with and gap . Greedy pulls each arm times, then at every later round pulls the arm with the larger empirical mean (ties broken any way at all). Then for every , In particular, for every fixed the expected regret grows linearly in .
Proof. Let be the event that all forced pulls of the better arm 2 fail while at least one forced pull of arm 1 succeeds. On , after the forced phase, arm 2’s empirical mean is and arm 1’s is positive. Arm 1’s empirical mean can never return to , because its success count never decreases; arm 2’s stays at , because it is never pulled again. So on greedy pulls arm 1 at every round after and pays each time, which gives on every outcome in , and hence .
Now split the expectation over and (the tower property of Session 9, conditioning on whether occurred): Every term in the regret is nonnegative, so and the second product is nonnegative. Dropping it, Finally, because the pulls are independent (Session 3): the first factor is the chance that arm 2’s pulls all fail, the second that arm 1’s pulls do not all fail. ◻
The bound is crude on purpose. It counts only the most extreme lock-in, an all-failure start on the good arm, so its constant is small. For the demo arms below with a single forced pull each, and , about by round ; with the constant drops to . Milder lock-ins (arm 2 starting merely below arm 1, not at zero) are far more common and are ignored here, so the real damage is much larger, as the demo will show. The proposition’s job is the shape, not the constant: more forced pulls shrink the slope but never make it zero. No fixed amount of up-front exploration cures greedy.
Thompson sampling fixes this using only what this session already built.
Algorithm: Thompson sampling. Keep a posterior on each arm’s , starting from . Each round:
draw one sample from every arm’s current posterior;
pull the arm with the largest sample, ;
observe the reward and advance that arm’s counters (a success adds one to , a failure adds one to ); leave the other arms untouched.
Key idea. The algorithm’s entire intelligence is “sample from the posterior, then act as if the sample were the truth.” Exploration is not bolted on; it emerges from posterior width. An arm we know little about has a wide posterior, so its sample is sometimes high and it gets tried; as evidence accumulates the posterior narrows and the samples stop straying, so exploration dies exactly as fast as the uncertainty that justified it.
Posterior Action. Thompson sampling is a posterior handed straight to an action, once per round, with one intervening random draw. The draw in step 1 is where belief becomes decision: had we passed the posterior mean to the instead of a sample, the algorithm would be greedy in disguise (see the pitfall below). The single sample is what buys exploration.
Figure 2 runs the two-arm case with for rounds, averaging cumulative regret over seeds. Greedy (after ten forced pulls of each arm) accumulates regret roughly twice that of Thompson sampling, because on the seeds where it locks onto the weaker arm it pays the gap forever. The right panel is a film-strip of the better arm’s posterior at rounds , , and : a wide early, tightening onto the true as the counters grow. Watching that posterior narrow is watching exploration switch itself off.
Pitfall. Do not replace the posterior sample in Thompson’s step 1 with the posterior mean. Acting on the mean is greedy in disguise: it discards the width that was the whole source of exploration, and it can lock onto a wrong arm after an unlucky start, exactly the failure [eq:greedylock] quantifies and Thompson was built to avoid. The randomness is the feature, not a nuisance to average away.
Run Thompson sampling on arms with independent priors , and let be the history before round : which arms were pulled and whether each impression was clicked. We first need one fact about the posterior: given , the arms’ rates are independent, each with its own posterior. Write the likelihood of the history one round at a time. Round contributes two factors: the probability of choosing arm , and the probability of the observed reward given . The first depends only on earlier data and the algorithm’s own random draws, never on directly, so it drops out under -then-normalize. The second involves only the pulled arm’s rate. Grouping the surviving factors by arm, with clicks and non-clicks on arm so far, By conjugacy each factor is the shape of a density whose parameters are the prior’s plus , which are exactly the counters that Thompson’s algorithm box maintains. So the posterior is a product of one per arm. A joint density that factors this way is a joint density of independent variables. This is Session 3’s conditional independence, now given the data.
Proposition 5 (Probability matching). Under Thompson sampling, for every arm and round , Each arm is pulled with exactly the posterior probability that it is the best arm.
Proof. Two different sources of randomness appear in [eq:probmatch], and the whole proof is noticing that they have the same distribution. On the right, the random object is the true rate vector , random because we are uncertain about it, distributed according to the posterior. On the left, the random object is the algorithm’s own draw , random because Thompson flips coins.
Start with two arms, and write the posteriors as and , independent given by the factorization above.
Right side. The posterior probability that arm 2 is best is , an event about a pair of independent variables with those two distributions.
Left side. Thompson draws and independently and pulls arm 2 exactly when , so : the same event about a pair of independent variables with the same two distributions.
Two pairs of independent variables with the same marginals have the same joint density (the product of the marginals), and two random vectors with the same joint density give every event the same probability. Both sides therefore equal the same integral, obtained by conditioning on the first coordinate: with the density of and the CDF of .
For arms nothing changes except the event: “” becomes “coordinate is the largest.” The draw vector and the true vector (given ) are both independent variables with the same marginals, so they have the same joint density and give that event the same probability. Ties have probability zero for continuous draws, so “the largest” is well defined. ◻
In one sentence: Thompson draws one plausible world from your belief and acts on the best arm in that world, and the share of plausible worlds in which arm is best is, by definition, the posterior probability that arm is best. The worked example of Section 3.3 is this proof with numbers.
Greedy, by contrast, gives probability to the arm with the largest posterior mean and probability to every other arm, including one that is likely to be the best. Thompson pays that arm of its attention.
Probability matching also explains why the lock-in of [eq:greedylock] cannot happen. Suppose Thompson stopped pulling arm 2 forever. Arm 2’s posterior would freeze at some , which has positive density all the way up to , while arm 1’s posterior narrows onto . The posterior probability that arm 2 is best would then settle near , and by [eq:probmatch] arm 2 would keep being pulled with at least that probability every round, contradicting the supposition. (Making this airtight takes more limit theory than we have; the mechanism is the point.) It is Session 2’s failed search in another costume: an arm you stop looking at keeps its uncertainty, and an uncertain arm keeps getting looked at.
How well does Thompson sampling do? Two results from the research literature, stated for reference and not proved here:
Nobody beats (Lai and Robbins, 1985). Any strategy whose regret grows slower than every power of on every problem must still have for large , where depends on how hard the arms are to tell apart and blows up as the gaps shrink.
Thompson sampling achieves it (Agrawal and Goyal, 2012; Kaufmann, Korda, and Munos, 2012). With priors, Thompson sampling’s expected regret grows like , with the best possible constant .
So greedy’s regret grows like and Thompson’s like . Over a million rounds, : one strategy keeps paying for an early mistake on a fixed fraction of all rounds, and the other pays for a number of experiments that grows only with the number of digits in .
Thompson sampling is good. Is anything best? To ask that we must say best at what, and the classical answer (Bellman, 1956; Gittins and Jones, 1974) changes the objective in one honest way: instead of regret, maximize the discounted total reward under the prior, where the expectation is over both the prior on the and the rewards. The discount has a reading this course already owns. Suppose play stops after a random number of rounds , independent of everything else, so that . Writing the total as and taking expectations term by term (the indicator method) gives exactly [eq:discounted]. Discounting is just an uncertain horizon (a campaign that might end after any impression) with mean : rounds at , at .
Each arm’s state is its counter pair . Pulling arm moves it to with probability and to otherwise, because the predictive probability of a success is the posterior mean, (the tower property of Session 9). Arms that are not pulled do not move. So the optimal strategy can in principle be computed by backward induction (Bellman’s dynamic programming): Session 3’s expected utility, applied recursively to every posterior the future might hold. The catch is that the state is the counters of all arms jointly, and the number of joint states grows exponentially in .
Theorem 1 (Gittins index theorem; Gittins and Jones, 1974; Gittins, 1979). For each arm there is a number , depending only on that arm’s own posterior and on , such that the strategy maximizing [eq:discounted] is: at every round, pull the arm with the largest .
The coupled -arm planning problem falls apart into one-arm problems, a genuinely surprising fact whose proofs are beyond this course (the shortest are Whittle, 1980, and Weber, 1992; Mahajan and Teneketzis, 2008, survey the theory for sensor management). What we can do is say what means. Take one arm in state and offer it a retirement option: at any round you may stop for good and collect a fixed per round forever, worth . In ad terms: drop the ad for good in favor of a guaranteed sponsor who pays per impression. The index is the value of at which you are indifferent, at the start, between retiring now and pulling (keeping the option to retire later). It is the arm’s fair per-round price.
Proposition 6 (The index is at least the mean). .
Proof. Let and suppose . Retiring now is worth . Pulling once and then retiring is worth , and the difference is . So for every some way of pulling strictly beats retiring, you are not indifferent, and the indifference point satisfies . ◻
The gap is an exploration bonus, and it has a name from Session 7: it is the value of information. A pull does not just pay on average; it also reveals something about , and you may act on what it reveals (retire after bad news, keep going after good news). The pull is a measurement that happens to pay. Three consequences, all visible in Figure 3:
The bonus shrinks as grows (less is left to learn), and .
A longer horizon (larger ) means a bigger bonus, because there is more future in which to use what you learn.
At there is no future, information is worthless, and exactly: greedy is the optimal strategy precisely when there is no tomorrow. Greedy’s failure is a failure to value the future.
Computing for a arm is cheap: backward induction over one arm’s counter grid, with bisection on , takes a few lines of code and well under a second.
Pitfall. Gittins’ theorem is exact but fragile. It needs the discounted objective [eq:discounted], arms that stay frozen when not pulled, and no cost for switching between arms. Change any one (a fixed finite horizon, ads whose appeal drifts with the news cycle even while you are not showing them, a cost to switch) and the index strategy is in general no longer optimal. It also optimizes reward averaged over your prior, not regret on the true . This is why practice usually runs Thompson sampling, which needs none of these assumptions.
Every strategy in this session has the same skeleton: compute a score for each arm from that arm’s own posterior, then pull the . They differ only in the score, which is to say in how they price uncertainty.
| Strategy | Score of arm | Exploration comes from | Guarantee |
|---|---|---|---|
| Greedy | posterior mean | nowhere | regret linear in [eq:greedylock] |
| UCB | a bonus proportional to the posterior width | regret | |
| Thompson | a random draw | random excursions as wide as the posterior | regret , best constant |
| Gittins | the exact value-of-information bonus | optimal for discounted reward |
The one new row is UCB (upper confidence bound), whose motto is optimism under uncertainty: score each arm by how good it could plausibly be. An arm we know little about has a large posterior standard deviation from [eq:betavar], so its optimistic score is high and it gets tried; every pull shrinks like , and the arm is abandoned once even its optimistic score falls below a rival’s. The classical version (Auer, Cesa-Bianchi, and Fischer, 2002) uses the empirical mean plus , with the number of pulls of arm so far: the same shape. Its regret guarantee needs a concentration inequality beyond this course. Figure 3 suggests one way to read the family: Gittins computes the bonus that UCB guesses, and Thompson draws it at random.
Keep the middle column in mind. From Session 12 on, the posterior variance becomes a main character, and Session 18 meets a rule whose score is the width alone: when the goal is learning rather than reward, the mean drops out.
Before any data, we mildly doubt a new ad: prior (mean , leaning toward “not clicked”). We then observe clicks in impressions. By conjugacy the posterior is The shrinkage decomposition [eq:shrinkage] explains where comes from. The data weight is so the posterior mean sitting between the data frequency and the prior mean , pulled two-thirds of the way toward the data because already outweighs the pseudo-counts of prior conviction.
Because the posterior is a full distribution, we can answer a
decision-relevant question directly: is the ad’s click rate more likely
than not above one half? With
,
(one line of
scipy: beta.sf(0.5, 10, 5)). We would keep the
ad, and we can say how sure we are, which is more than a point estimate
can do.
How sure, in one number? By [eq:betavar] the posterior standard deviation is . Had we shown the ad times with the same click frequency (), the posterior would be with standard deviation about : four times the data, about half the width.
Suppose instead we had begun overconfident that the ad was excellent: (mean , worth pseudo-trials of conviction). If the ad is in fact mediocre and we observe clicks in (frequency ), the posterior is with mean , still far above the data, because ten trials cannot outvote twenty-five imagined ones. Had we started from the flat , the same data would give with mean , right at the evidence. The lesson is in the pitfall.
Pitfall. A Beta prior is not a harmless formality. Its parameters are pseudo-counts, so a confident wrong prior (large pointed the wrong way) needs a comparably large amount of data to overcome, and until then it visibly biases every estimate and decision. Choose to honestly reflect how much you know, and treat a strong prior as a claim you must be prepared to defend.
Two ads start from flat priors. Ad 1 has been clicked on of impressions, ad 2 on of . By conjugacy the posteriors are (mean ) and (mean ), independent given the data. Greedy compares means and shows ad 1 next, with probability . By [eq:probmatch], Thompson sampling shows ad 2 with probability . To compute it, condition on (Session 9’s tower property, ) and use independence: with the density and the CDF (one numerical integral; a Monte Carlo check with a million paired draws agrees to three decimals). This is the integral from the proof of [eq:probmatch]: it is at once the posterior probability that ad 2 is better and the probability that Thompson’s two draws put ad 2 on top. Ad 2 has been shown only twice; the data cannot rule out that it is the better ad, and Thompson spends about of the next impression on that doubt. Greedy spends nothing on it, today or ever, unless ad 1 stumbles.
A brand-new ad has a flat prior, , so its mean is , and . How large is its Gittins index? We do not need the optimal strategy to get a lower bound; any particular way of playing that beats retiring will do. Try the simplest strategy that uses information: show the ad once; after a click, keep showing it forever; after no click, retire it in favor of the sponsor.
Build its value. The first pull pays on average. With probability it succeeds, the posterior becomes , and every later pull pays on average (tower property), worth from round 2 on. With probability it fails and we retire from round 2 on, worth . Indifference with retiring immediately means At this is . For any smaller this strategy beats retiring, so . (Sanity check: at the formula returns , the mean. With no future, the look is worthless.)
The exact index, by computer, is . An untested ad that pays per impression on average is worth keeping over a sponsor paying up to per impression, and a single look already accounts for about two-thirds of that premium ( of ). The structure is Session 7’s buy-a-measurement problem: the first pull is the measurement, and its value is that you get to decide after seeing it.
(Mechanical.) An ad starts from prior and is clicked on of impressions. Give the posterior, its mean, and its standard deviation. Roughly how many more impressions, at the same click frequency, would halve the standard deviation? (Answers: ; mean ; variance , standard deviation . Halving needs to grow about fourfold, from to : roughly more impressions.)
(Conceptual.) A colleague accepts [eq:greedylock] but proposes greedy with forced pulls per arm “to be safe.” What does the proposition still say about the regret as , and what new cost has the colleague paid for certain? (Answer: the slope is tiny but positive, so regret is still linear in ; and the forced phase alone costs of regret on every run, needed or not. Fixed up-front exploration trades one waste for another.)
(Conceptual.) Two arms have the same posterior mean, one after pulls and one after . Which has the larger Gittins index, and why? How does your answer change as ? (Answer: the 4-pull arm, whose wider posterior leaves more to learn, so its value-of-information bonus is larger. As both indices fall to the common mean and the strategies tie: with no future, learning is worth nothing.)
A probability model answers three questions: what is uncertain, what is observed, and how should observation change belief and action? This session pushed all three into the hardest case yet, where the uncertain thing is itself a probability. The answer was the same Bayes’ rule, now producing a density. The Beta family made the update two counters, and its variance made the remaining doubt a number that shrinks like . Then the posterior went to work. Greedy hands the decision the posterior mean and, provably, can pay for one unlucky start forever. Thompson sampling hands it a sample, and so pulls every arm exactly as often as that arm is believed best. Gittins’ theorem shows that the truly optimal strategy for discounted reward is also a score per arm: the mean plus the value of what a pull would teach. The recurring lesson of Movement III holds once more: an estimate is a compression of a posterior, chosen for a purpose, and when the purpose is to keep deciding, the compression must keep the posterior’s width. Movement IV makes that width, the posterior variance, its main object.
After trials from a prior, what happens to the data weight in [eq:shrinkage] as , and at what rate does the posterior standard deviation shrink?
A colleague runs Thompson sampling but pulls the arm with the largest posterior mean each round. What have they built, which proposition says what can go wrong, and why would adding forced pulls not fix it?
Why is an arm’s Gittins index never below its posterior mean, and when does the gap vanish?