SStatistics, Built

Stage II · Bachelor's: Methods

Part 15 of 65

First Bayes

Bachelor'sstarts at this level53 min of film12 chaptersprerequisites: Part 9, Part 11

What should you believe after seeing the data?

The part opens with Bayes's essay of 1763 and his billiard table: a hidden ball W, twelve more balls of which 8 stop to its left, and a posterior for W's position that is Beta(9, 5). Laplace applies the same reasoning to the Paris births and to the sunrise. The machinery is prior times likelihood, proportional to the posterior, and updating one ball at a time gives the same answer as updating all at once. Conjugate pairs (beta-binomial, gamma-Poisson, normal-normal) make the prior read as imaginary data; summaries, predictive distributions and the choice of prior follow, and the normal model under the reference prior returns Part 8's t interval exactly. When the algebra gives out, the Challenger posterior is computed on a grid and then by a Metropolis walk. The part turns when the Coverage Board judges credible intervals by frequency: a confident wrong prior covers a fixed truth 0% of the time, yet coverage averaged over the prior is exactly 95%. It ends with Bayes factors, which can favour the null, and Lindley's warning.

What you need. Calculus (integrals of densities); the beta, gamma and normal distributions of Part 3.

Hook
Bayes's billiard table, 1763
Mathematics
conjugacy, priors, posteriors, credible and predictive intervals, grids, Metropolis by hand
Built
the billiard table

What you will be able to do

Bachelor's

  • Update a beta prior with binomial data, and read the prior as imaginary successes and failures.
  • Compute a posterior mean, a credible interval and the probability that the next trial succeeds.

Master's

  • Derive the gamma-Poisson and normal-normal updates, with precision weighting.
  • Compute a posterior on a grid, and by random-walk Metropolis with a sensible step size, and check that the two agree.
  • Compute a Bayes factor for a point null against a beta alternative.

PhD

  • Prove that an equal-tailed credible interval has exactly its nominal coverage on average over the prior, and show by example that it can have coverage 0 at a fixed truth.
  • State Lindley's paradox: at a fixed p-value the Bayes factor moves towards the null as n grows.

Practice

  • Choose a prior and defend it with a prior predictive check and a sensitivity analysis.
  • Report a posterior with its interval and predictive distribution, and say what the answer owes to the prior.

Contents

Each chapter has a home level. Choose a track to see what to read and watch: Bachelor's 25 min · Master's 48 min · PhD 53 min · Practice 30 min.

  1. 0The billiard table, 1763Bachelor's4 min
  2. 1The machineryBachelor's4 min
  3. 2ConjugacyBachelor's5 min
  4. 3SummariesBachelor's4 min
  5. 4PredictionBachelor's4 min
  6. 5PriorsPractice5 min
  7. 6The normal modelMaster's4 min
  8. 7GridsMaster's4 min
  9. 8When grids failMaster's6 min
  10. 9Bayes and frequencyPhD4 min
  11. 10Hypotheses, the Bayesian wayMaster's5 min
  12. Recap, problems, and the road aheadAll tracks3 min

Also on this page: Lecture · Key results · Try it · Lab · Problems · Notes and sources · Build the film.

Lecture

The text of each chapter is the film's narration, as it is spoken, so you can read along or revise without the film. The pictures are in the film.

The billiard table, 1763Bachelor's4 min

In 1763 the Royal Society published an essay by Thomas Bayes, a Presbyterian minister in Tunbridge Wells who had died two years earlier. His friend Richard Price had found it among his papers. Its problem: given the number of times an unknown event has happened and failed, find the chance that its probability lies between any two limits. Bayes was an amateur mathematician, a Fellow of the Royal Society, who published almost nothing in his lifetime. His question runs the other way from everything in Part 2. There we knew the probability and asked about the data. Here we have the data, and ask what to believe about the probability.

Bayes made the problem concrete with a table. Model a ball W as equally likely to stop anywhere on the table. The drawing uses one fixed illustrative hidden position. Its position from the left edge, as a fraction of the table's width, is p, and we aren't allowed to see it. Now roll twelve more balls, and for each one we're told only whether it stopped to the left or the right of W. Each ball lands left with probability p. Eight of the twelve land to the left. What should we believe about where W is?

Before the twelve balls, every position for W was equally likely: a flat line. Bayes showed that afterwards our belief should be proportional to p to the eighth times one minus p to the fourth: the chance of exactly what we saw, if W were at p. Normalized, it's a beta distribution, Part 3's, with parameters nine and five, centred near point six four. It puts ninety-five percent of its weight between point three nine and point eight six. The hidden ball was at point six two. That curve illustrates Bayes's early posterior calculation.

Eleven years later, Pierre-Simon Laplace found the same idea independently, and turned it into a working method for science. His most famous application was to births. In Paris from 1745 to 1770 there were two hundred and fifty-one thousand, five hundred and twenty-seven boys baptized, and two hundred and forty-one thousand, nine hundred and forty-five girls. With a uniform prior on the chance of a boy, the posterior is a beta distribution with these enormous parameters. The posterior probability that boys are no more likely than girls is about one in ten to the forty-two. Laplace concluded that the excess of boys was as certain as any truth of the moral sciences. Part 10's Arbuthnot reached a similar conclusion with a significance test; Laplace stated it as a probability about the hypothesis itself.

Laplace also asked how likely the next trial is to succeed, after s successes in n. Average the chance p over the posterior, and the answer is s plus one over n plus two: the rule of succession, under a uniform prior and conditionally independent Bernoulli trials with a common probability. His notorious example is the sunrise. Suppose the sun has risen every day for five thousand years, one million, eight hundred and twenty-six thousand, two hundred and thirteen days. The rule gives odds of one million, eight hundred and twenty-six thousand, two hundred and fourteen to one that it rises tomorrow. Laplace added at once that the probability is far greater for anyone who understands what makes the sun rise. A uniform prior is a specific assumption on this scale. The rule also assumes conditionally independent trials with one stable probability; physical knowledge belongs in the prior. That tension runs through this whole part.

Numbers: 8 of 12 left: Beta(9, 5), mean 0.64, 95% [0.39, 0.86], truth 0.62; Paris 251,527 boys and 241,945 girls, P(p ≤ ½) ≈ 1.15 × 10⁻⁴²; sunrise odds 1,826,214 to 1

1The machineryBachelor's4 min

The rule is Part 2's Bayes's rule, with the unknown parameter theta playing the role of the hypothesis: the posterior density of theta given the data equals the likelihood times the prior, divided by the probability of the data. That denominator averages the likelihood over the prior. It doesn't depend on theta at all. So the posterior is proportional to likelihood times prior, and we can normalize at the end, by making the area one. In words: the posterior is Part 9's likelihood, weighted by what you believed before. Fisher's likelihood said which parameter values make the data probable. Bayes turns that into a probability distribution for the parameter, at the price of a prior.

Here's the machinery at work. A prior: Beta two two, a mild belief that a probability p is somewhere near a half. The likelihood of seven successes in ten trials, drawn as a curve in p, peaking at point seven. Multiply the two curves point by point, and rescale so the area is one. The posterior sits between them, nearer the data, which carry more information than this mild prior. In symbols, the powers just add: p to the one times p to the seven gives p to the eight, and the posterior is Beta nine five.

Back to the billiard table, one ball at a time. Start flat. Each ball that lands left multiplies the curve by p, pushing belief to the right; each ball that lands right multiplies it by one minus p, pushing it left. After each ball, today's posterior becomes tomorrow's prior. Watch the curve sharpen, ball by ball, around the hidden position.

Updating on the first piece of data gives a posterior. Use it as the prior for the second piece. The result is the same as updating on both at once, whenever the pieces are independent given theta, because their likelihoods multiply. With dependent data, use the conditional likelihood of the next piece given the earlier data; coherent sequential updating still works. So it doesn't matter whether you learn from data one observation at a time, in batches, or all together, or in what order: you end in the same place. That's one sense in which Bayesian learning is coherent.

A little history. Through the nineteenth century, Laplace's method, then called inverse probability, was simply how inference was done, in astronomy, geodesy and the social sciences. George Boole and John Venn attacked its weak point: where does the prior come from, and why should ignorance be uniform? Fisher, in 1922, built likelihood as an alternative and declared that the theory of inverse probability must be wholly rejected. Frank Ramsey, Bruno de Finetti and Leonard Savage rebuilt the foundations, with probability as the coherent degree of belief of a person who acts on it. And from about 1990, Markov chain Monte Carlo, popularized in applied Bayesian statistics by Alan Gelfand and Adrian Smith, made a wider range of models practical. Earlier MCMC methods and applications predate their paper. Part 26 picks up the modern story.

What has changed? Since Part 8, the parameter has been a fixed number and the data random. A ninety-five percent confidence interval was a promise about a procedure, over repeated samples. In the Bayesian view, the parameter is unknown, so it gets a probability distribution that expresses what we know about it. A ninety-five percent credible interval then says, of these data, that theta lies inside with probability point nine five: the statement people usually think a confidence interval makes. The price is a prior; the reward is a direct answer. And de Finetti's theorem from Part 5 says the prior isn't arbitrary decoration: an infinitely extendible exchangeable Bernoulli sequence has an IID mixture representation. Finite exchangeability alone does not guarantee it.

Numbers: Beta(2, 2) × 7 of 10 → Beta(9, 5)

2ConjugacyBachelor's5 min

Why did the posterior come out as a beta distribution? A Beta a b prior is proportional to p to the a minus one times one minus p to the b minus one. The binomial likelihood has the same shape: p to the s times one minus p to the n minus s. Multiply, and the exponents add. So the posterior is again a beta, with a plus the successes and b plus the failures. When the posterior stays in the prior's family, the prior is called conjugate, a term from Howard Raiffa and Robert Schlaifer's 1961 book. Updating becomes bookkeeping.

The posterior mean is a plus s over a plus b plus n. Rearranged, it's a weighted average of the prior mean and the sample proportion, with weights a plus b and n. For this posterior-mean weighting, the prior acts like a plus b trials with a successes and b failures. This is not a unique literal data history: relative to a uniform baseline, the density exponents correspond instead to a minus one and b minus one. A Beta two two prior is worth four imaginary trials. With seven successes in ten, the posterior mean is nine over fourteen, point six four three: between the prior's half and the data's point seven, much nearer the data. As n grows, the data's weight goes to one, and the prior is forgotten.

Other likelihoods have conjugate priors too. For Poisson counts, the gamma distribution: a gamma alpha beta prior on the rate, with beta a rate rather than a scale, updated to alpha plus the total count, and beta plus the number of observations. Part 3's horse kicks: a hundred and twenty-two deaths in two hundred corps-years of the Prussian army. Start from a gamma one one prior, an exponential rate prior with mean one, and the posterior is gamma one hundred and twenty-three, two hundred and one, with mean point six one two deaths per corps per year, and a ninety-five percent credible interval from point five one to point seven two. The prior counts as one corps-year with one death, against two hundred real ones, so it hardly matters.

The third classic case is a normal mean. Put a normal prior on mu, centred at m zero with standard deviation s zero. With n normal observations of known standard deviation sigma, the likelihood depends on the data only through the sample mean, and is a normal curve in mu. Multiply the two exponentials and complete the square. The posterior is normal, and its precision, one over its variance, is the sum of the two precisions: the prior's, and the data's, n over sigma squared. Its mean is the average of the prior mean and the sample mean, weighted by their precisions. Information adds, and the more precise source pulls harder.

On the World: someone guesses that the mean adult height is about a hundred and seventy centimetres, give or take ten. Ten adults are measured, with a mean of a hundred and sixty-nine point two; assuming the Gaussian model with known sigma nine, the data's standard error is two point eight five. The posterior is normal, centred at a hundred and sixty-nine point three, with standard deviation two point seven four, a little narrower than the data alone. The data's precision is ten over eighty-one, the prior's one over a hundred, so the data get ninety-two and a half percent of the weight. The World's true mean is a hundred and sixty-nine point five.

The conjugate pairs in one table. Binomial data with a beta prior; Poisson counts with a gamma prior; a normal mean with a normal prior; and multinomial counts with a Dirichlet prior, the beta's many-category cousin. In each case the prior is worth a definite number of imaginary observations. Regular exponential families admit natural conjugate families with suitable hyperparameters. Closed-form normalizing constants are not always available. These were once among the few posteriors readily computed by hand; now they're building blocks for the larger models of Part 26.

Numbers: posterior mean 0.643; horse kicks Gamma(123, 201), mean 0.612, 95% [0.509, 0.725]; heights N(169.3, 2.74²), data weight 92.5%, truth 169.5

3SummariesBachelor's4 min

The posterior is the full answer, but we usually want summaries. Take two successes in thirteen trials with a uniform prior: Beta three twelve, skewed to the right. Its peak, the mode, is at point one five four; that's also the maximum-likelihood estimate's Bayesian twin, since with a flat prior the posterior is the likelihood. The median, splitting the probability in half, is at point one eight six. The mean, the balance point, is at point two. For a skewed posterior the three differ. Which one should you report?

The answer depends on what an error costs. Choose the estimate that minimizes the expected loss under the posterior. If the loss is the squared error, as in Part 9's mean squared error, the best estimate is the posterior mean. If it's the absolute error, the posterior median, by the same argument that made the median minimize absolute deviations in Part 1. And if you only care about being within a shrinking symmetric tolerance, a regular posterior mode is the limiting choice. Exact zero-one loss is uninformative for a continuous posterior, since every single point has probability zero. That limiting choice is the maximum a posteriori estimate. The posterior is shared; the summary is a decision.

Intervals. The simplest ninety-five percent credible interval cuts two and a half percent of the posterior probability from each tail: from point oh four seven to point four two eight. But for a skewed posterior, that interval includes values in the long right tail that are less plausible than values it excludes on the left. The highest posterior density interval fixes this: lower a horizontal line until the region above it holds ninety-five percent. Every point inside is more plausible than every point outside, and it's the shortest ninety-five percent interval: from point oh two nine to point three nine five. Here it's about four percent shorter.

There's a trade-off. Quantiles pass through any increasing transformation, so the equal-tailed interval for the odds is just the equal-tailed interval for p, with its endpoints transformed. Here, odds from point oh four nine to point seven four nine. The HPD interval doesn't transform that way: densities pick up a Jacobian, Part 5's, so the most plausible region for the odds isn't the image of the most plausible region for p. Equal-tailed intervals are the usual default for reporting; HPD intervals minimize length for this unimodal posterior on the scale you care about. Either way, say which.

One more summary, Laplace's own. Expand the log posterior to second order around its peak: a quadratic, with curvature J. Then the posterior is approximately normal, centred at the mode, with variance one over the curvature: Part 9's observed information, now as a posterior variance. For Beta three twelve the approximating normal has standard deviation point one oh, matching the exact posterior's, though it misses the skew and puts some mass below zero. Under Bernstein-von Mises regularity, including local identifiability and a suitable prior near the truth, the posterior approaches a normal centred near the maximum-likelihood estimate, with the inverse information as its variance. That's why Bayesian and likelihood intervals agree in large samples.

A credible interval reads the way people want an interval to read: given these data and this prior, the probability that p lies between point oh four seven and point four two eight is ninety-five percent. It's conditional on what was actually observed, not on imagined repetitions. A confidence interval's ninety-five percent describes the procedure that made it. They're different promises, and yet they often nearly agree, numerically; chapter nine checks when, on the Coverage Board. Under regular finite-dimensional identifiable models with a prior positive near the truth, posterior width typically shrinks like one over root n. Boundaries, nonidentification and other irregular cases can differ.

Numbers: Beta(3, 12): mode 0.154, median 0.186, mean 0.200; equal-tailed [0.047, 0.428], HPD [0.029, 0.395]; Laplace approximation SD 0.100

4PredictionBachelor's4 min

To predict new data, don't plug in a single estimate. Average the data model over the posterior: the posterior predictive distribution. For binomial data with a beta posterior, the average can be done exactly, and gives the beta-binomial distribution. For a single new trial, the predictive chance of success is just the posterior mean. With a uniform prior, that's s plus one over n plus two: Laplace's rule of succession is the simplest posterior predictive.

After seven successes in ten, with the Beta two two prior, how many successes will the next ten trials bring? Plugging in the posterior mean, nine fourteenths, gives a binomial distribution in grey, with standard deviation one point five two. Both forecasts now have the same mean. The posterior predictive, in orange, is wider, with standard deviation one point nine two, and its peak is lower. The plug-in forecast pretends we know p exactly. The predictive admits we don't.

Why wider? Part 5's law of total variance: the predictive variance is the average sampling variance, plus the variance of the mean across the posterior. For the binomial, that's the familiar m p one minus p, averaged, plus m squared times the posterior variance of p. The plug-in variance at the posterior mean exceeds the first term by m times the posterior variance of p; the predictive adds m times m minus one times that variance beyond the plug-in. For one new Bernoulli trial the predictive and plug-in coincide. A forecast must carry both the noise of the next data and our uncertainty about the parameter. The second shrinks as the data grow, but with ten trials it's large: it multiplies by m squared.

Contrast the horse kicks of chapter two. A gamma posterior for a Poisson rate makes the predictive distribution of next year's count a negative binomial, the gamma-mixed Poisson of Part 14. The predictive probability that a given corps has no deaths next year is two hundred and one over two hundred and two, to the power one hundred and twenty-three: point five four three. Plugging in the estimated rate gives e to the minus point six one, also point five four three. With two hundred corps-years of data, the uncertainty about the rate is negligible next to the Poisson noise. The difference is small for this one-year prediction, though it can matter for longer prediction horizons even with substantial data.

For normal data with the reference prior of chapter six, the predictive distribution of one new observation is a t distribution centred at the sample mean, with scale s times the square root of one plus one over n. That's exactly Part 11's prediction interval, now read as a probability statement about the next value. The one under the root is the new observation's own noise; the one over n is our uncertainty about mu. Same two ingredients.

The predictive distribution has a second use: checking the model. Simulate many replicated datasets from it, datasets the fitted model says could have happened. Then compare some feature of the real data, its largest value, say, or its number of runs, with the same feature in the replicates. If the real data look unlike all of them, the model is missing something. These posterior predictive checks, developed by Donald Rubin in 1984 and by Andrew Gelman and colleagues since, are a core part of the Bayesian workflow in Part 26.

Numbers: next 10 trials: SD 1.92 (predictive) vs 1.52 (plug-in at the same posterior mean); P(no horse-kick death) 0.543 either way

5PriorsPractice5 min

Where does a prior come from, and does it matter? Take four. The uniform, Bayes's and Laplace's. Jeffreys's Beta a half, a half, which we'll meet properly in a moment. A sceptic, Beta twenty twenty, confident that p is close to a half: worth forty imaginary trials. And a pessimist, Beta two eight, who thinks p is probably low. Now give all four the same data.

With seven successes in ten trials, the four posteriors disagree. The uniform and Jeffreys priors give means near point seven, close to the data. The sceptic is dragged to point five four, and the pessimist to point four five. With ten trials, a prior worth forty imaginary trials dominates. That's not a flaw: if the sceptic really had forty trials' worth of earlier evidence, ten new ones shouldn't overturn it. The danger is a prior that claims knowledge nobody has.

Now seventy successes in a hundred. The uniform and Jeffreys posteriors are indistinguishable, at point seven. Even the sceptic and the pessimist have moved most of the way, to point six four and point six five, and all four intervals overlap heavily. In regular identifiable finite-dimensional models, with a suitable prior positive near the truth, the likelihood eventually dominates locally. That is the Bernstein-von Mises setting, which Part 53 proves: with enough data, Bayesian and likelihood answers converge.

Flat priors have a trap. Suppose you know nothing about p, so you make it uniform. Then what do you believe about the odds? Not that they're uniform: by Part 5's change of variables, a uniform p gives the odds the density one over one plus o, squared, piled up near zero. Half the prior has odds below one. A prior that's flat on one scale is informative on another, and "knowing nothing" doesn't pick out a scale. This bothered Laplace's critics for a century, Boole and Venn among them.

Harold Jeffreys found a way out in 1946. Make the prior proportional to the square root of Part 9's Fisher information. Under a change of parameter, the information changes by the square of the derivative, so its square root picks up exactly the Jacobian a density needs. Jeffreys's rule gives the same answer whichever scale you start on. For a binomial probability, the information is n over p times one minus p, and the Jeffreys prior is Beta a half, a half, heavier at the ends than the uniform. It's the prior behind Part 11's Jeffreys interval. Invariance is an attractive property, but it isn't a guarantee of coverage, and chapter nine will find this prior falling short near the edge.

How can a prior be checked? Simulate data from it: draw a parameter from the prior, then data from the model. That's the prior predictive distribution, what the prior expects to see. The pessimist's Beta two eight, with ten trials, expects seven or more successes only about one and a half percent of the time. We saw seven. The pessimist should be surprised. Investigate the prior and sampling model, and report sensitivity; replacing a prior after seeing the data and presenting it as pre-data information would reuse the evidence. George Box proposed prior predictive checks in 1980, and they're now a routine first step: if a prior predicts data that are absurd, like adult heights of five metres, fix the prior before seeing any data.

In practice there are several kinds of prior. Informative priors encode real earlier evidence, a previous trial or a physical law, and should be stated and defended like any other assumption. Weakly informative priors rule out the absurd without claiming more, for instance a Cauchy prior with scale two and a half on standardized logistic coefficients, which makes enormous effects unlikely, as Andrew Gelman and colleagues recommended in 2008. Reference priors, Jeffreys's among them, try to let the data speak. Improper priors, which don't integrate to one, require a proper posterior for parameter inference; ordinary Bayes factors also require proper within-model priors or special treatment; with separated logistic data, as in Part 14, a flat prior gives an improper posterior. And always do what we just did: a sensitivity analysis, reporting how the conclusion moves across reasonable priors.

Numbers: n = 10: means 0.45–0.68; n = 100: 0.64–0.70; Beta(2, 8) predicts ≥ 7 of 10 with probability 0.015

6The normal modelMaster's4 min

Eight of the World's adults, their heights in centimetres. In chapter two the standard deviation was known. Usually it isn't. Model the heights as normal with unknown mean and variance. For the prior, take the standard reference choice: flat in mu, and flat in the log of sigma, which is one over sigma squared. It's improper, but with at least two nonidentical observations, the posterior is proper. The displayed density is with respect to mu and sigma squared; in mu and sigma coordinates it is proportional to one over sigma.

Multiply the likelihood by the prior. The exponent contains Part 8's split of the sum of squares: n minus one times s squared, plus n times the squared distance from mu to the sample mean. We care about mu, so integrate sigma squared out. It's a gamma integral, and what's left is a power of one plus a squared distance. That's Student's t density: mu minus x bar, over s over root n, has a t distribution with n minus one degrees of freedom. The same pivot as Part 8, with the roles reversed: there the data were random and mu fixed; here mu is uncertain and the data fixed. And the variance's posterior gives Part 8's chi-squared.

For the eight heights: a sample mean of a hundred and seventy point five, a standard error of two point two nine. Here's the t posterior for mu, with the normal plug-in normal curve obtained by setting sigma equal to s, for comparison: the t has heavier tails, paying for the unknown variance. The ninety-five percent credible interval runs from a hundred and sixty-five point oh six to a hundred and seventy-five point eight nine. Part 8's t-interval, from the same data: exactly the same numbers. The World's true mean, a hundred and sixty-nine point five, is inside both.

The sample standard deviation is six point five cm. The posterior for sigma gives a ninety-five percent credible interval from about four point three to thirteen point two: wide, with eight observations, and skewed to the right. And again it's numerically identical to the chi-squared interval of Part 8.

How much does not knowing sigma cost? With sigma known, the interval is plus or minus one point nine six standard errors. With eight observations and sigma unknown, integrating sigma out gives the t multiplier, two point three six: a twenty percent larger multiplier at the same standard error; the actual known-sigma and estimated-sigma widths need not have that ratio. With thirty observations, two point oh five. The price of the unknown variance fades as the data grow, Gosset's point in Part 8, arrived at from the Bayesian side: the extra width is the posterior's honest uncertainty about sigma.

So in the normal model, the reference prior reproduces the classical intervals exactly. The numbers agree; the interpretations don't. One is a probability statement about mu given these data, the other a promise about a procedure over repeated samples. Harold Jeffreys, in his 1939 Theory of Probability, and Fisher, with his fiducial argument of 1930, reached these same intervals by different roads, and argued about it for decades. Put real prior information in, and the two part company. Chapter nine measures how.

Numbers: 8 adults: 95% [165.06, 175.89] = the t-interval; σ ∈ [4.28, 13.19]

7GridsMaster's4 min

Conjugacy is a lucky accident. For most models, the posterior has no formula. With one or two parameters there's a simple remedy. Lay a fine grid over the plausible values. At each point, compute the likelihood times the prior, working with logarithms so that tiny numbers don't underflow. Divide by the sum to normalize. Any summary, a mean, a probability, a quantile, is then a weighted sum over the grid. No conjugacy, no algebra: just arithmetic.

Bring back Part 14's Challenger model: logistic regression of O-ring distress on temperature, now with an improper flat prior on both coefficients. For these nonseparated data the posterior is proper; the finite grid is a numerical approximation to it. The posterior is the likelihood, normalized. Natural conjugate forms exist for exponential families, but logistic posterior normalization is generally not available in a convenient closed form. Evaluate it on a grid of over three hundred thousand points, with wider and finer grids checking truncation and discretization. The picture is Part 14's long diagonal ridge, but now it's a probability distribution over the coefficients, and we can ask it questions directly.

Add up the grid over the intercept, and you have the posterior for the slope alone. Its mean is minus point two nine one, a little more negative than the maximum-likelihood minus point two three two, because the posterior is skewed. The probability that the slope is negative, the red sliver being the rest, is point nine nine eight nine. In words: given the twenty-three flights and a flat prior, colder launches are worse with probability about ninety-nine point nine percent. Part 14's likelihood-ratio test could only say that data like these would be rare if temperature didn't matter.

Each point of the grid implies a probability of distress at thirty-one degrees, so the posterior for the coefficients becomes a posterior for that probability. Its median is point nine nine nine nine. The posterior probability that the chance of distress exceeded ninety percent is point nine seven. Its lower two and a half percent point is about point nine oh, a little above Part 14's profile-likelihood interval, which started at point eight oh. And the caveat is exactly the same: all of this rests on the logistic curve's shape below fifty-three degrees, where there are no data. A posterior doesn't cure an extrapolation.

Grids free the prior too. Suppose you believe a coin is probably fair, but you're not sure: half your belief is a tight bump at one half, Beta fifty fifty, and half is complete ignorance, uniform. This finite mixture updates analytically too: update each component and its marginal-likelihood weight. A grid provides a convenient cross-check. On a grid of a thousand points, seven heads in ten is no harder than before. The posterior has two humps: one near point five two, from the "fair" component, and a broad one near point seven, from the "no idea" part. The posterior probability that p is between point four and point six is still about two thirds. The data have shifted belief toward an unfair coin without abandoning the fair one; ten tosses can't do more.

The catch is dimension. With a hundred points per parameter, a grid in k dimensions has a hundred to the k points. Two parameters: ten thousand, easy. Eight parameters: ten to the sixteen, far beyond any computer. Worse, almost all those points sit where the posterior is negligible: in high dimensions the posterior occupies a vanishing fraction of any box around it. What we need is a method that visits only the places where the probability is, in proportion to how much there is. That's the next chapter.

Numbers: Challenger: E[β₁] ≈ −0.291, P(β₁ < 0) ≈ 0.9989; p(31): median 0.9999, P(> 0.9) ≈ 0.976; mixture prior P(0.4 < p < 0.6) = 0.65

8When grids failMaster's6 min

Part 7 built a Markov chain whose long-run distribution is any target we like. Here's the target: the posterior. From the current point, propose a random step. Compute the ratio of the posterior at the proposal to the posterior here. The unknown normalizing constant, the integral we couldn't do, cancels: only likelihood times prior is needed. If the proposal is more probable, move there; if it's less probable, move there only with probability equal to the ratio. Record where you are, even if you stayed. That's the Metropolis algorithm of 1953, invented to simulate molecules at Los Alamos.

Why does it work? With a symmetric proposal, the probability flow from theta to theta prime, in equilibrium, is the smaller of the two posterior values times the proposal density. That's symmetric, so it equals the flow back. Detailed balance, from Part 7: the posterior is the chain's stationary distribution. With irreducibility, appropriate recurrence and integrability, averages along the chain converge to posterior expectations, though successive draws are correlated, which is the price.

The step size matters, and trace plots show why. These are three chains on the Challenger posterior, each fifteen hundred steps of the slope. With tiny steps, nearly every proposal is accepted, but the chain creeps, wandering slowly: the five thousand retained draws, beyond the burn-in and longer than this displayed trace, have an estimated slope effective sample size of about twelve. With good steps, about forty-five percent are accepted and the trace looks like noise, the fuzzy caterpillar you want: an effective sample size of over two hundred. With huge steps, nearly every proposal lands somewhere improbable and is rejected; the chain sits still for long stretches. The theory of Roberts, Gelman and Gilks gives about 0.234 in a particular high-dimensional random-walk limit, not a universal target. In low dimensions, tune for function-specific Monte Carlo efficiency rather than acceptance alone.

The Challenger posterior hides a second trap. In the original coordinates, intercept and slope, it's the long diagonal ridge of Part 14. A random walk with independent steps in each coordinate can't follow a ridge: steps along it are rare, and steps across it are rejected. This selected proposal gives an effective sample size of twelve. Centre the temperature at seventy degrees, so the intercept becomes the log-odds at seventy, and the ridge becomes a less correlated hill, through a shear rather than a rotation. The same algorithm, the same step budget, the same posterior: an effective sample size of over two hundred. Choosing coordinates in which the posterior is roughly round is the single most useful trick in practical MCMC, and Part 27 goes much further, with Hamiltonian Monte Carlo.

A chain must also find the posterior before it can explore it. This one starts at a slope of zero, no temperature effect at all, and takes a few dozen steps to drift into the region of high probability. Those early draws reflect the starting point, not the posterior, so they're thrown away: the burn-in, or warm-up. In practice you run several chains from scattered starting points and check that they end up agreeing, with diagnostics like the R-hat statistic of Part 27. A single chain that looks fine can still be stuck.

Run a longer chain: twenty thousand steps, the first two thousand discarded. Here are its draws of the two coefficients, a round cloud in the centred coordinates. Compare with the grid. The posterior mean of the slope: close estimates within Monte Carlo error; the grid is about minus point two nine one. The median probability of distress at thirty-one degrees: point nine nine nine nine both ways. The probability it exceeds ninety percent: point nine seven, both ways. The chain's eighteen thousand correlated draws are worth about five hundred independent ones, for the slope mean. Other summaries need their own effective sample sizes and Monte Carlo errors. The walk reproduces the grid, and unlike the grid it scales: in Part 27 the same idea handles models with thousands of parameters.

One more reason to like posterior draws. The chain gives a list of parameter values. Apply any function to each draw, and you have draws from that function's posterior: no delta method, no new derivation. The odds ratio for ten degrees colder is e to the minus ten beta one: its posterior median is about fifteen, with a ninety-five percent interval from about two to about three hundred and thirty, wider at the top than Part 14's profile interval, because a flat prior leaves the steep slopes plausible. And practical questions get direct answers: the posterior probability that ten degrees of cold multiplies the odds of distress by more than five.

Numbers: ESS of 5,000 draws: 12 (tiny), 212 (good), 48 (huge); raw coordinates 12; long-chain slope ESS 510; summaries agree with the expanded grid within Monte Carlo error; OR per 10 °F median 15 (all retained draws)

9Bayes and frequencyPhD4 min

Credible intervals make a promise about belief. The Coverage Board asks a frequentist question of them anyway. Fix the truth: a probability of five percent, fifty trials. Repeat the experiment ten thousand times, each time building the ninety-five percent credible interval from that sample's posterior. How often does the interval contain the fixed truth? Nothing in Bayes's theorem promises ninety-five percent here. The Bayesian promise is conditional on the data, for every possible outcome; the frequentist one averages over outcomes, for a fixed truth. It's a fair question whether they coincide.

Start with an extreme case. A confident prior, Beta eighteen two, says the probability is about point nine, and it's worth twenty imaginary trials. The truth is point oh five, so fifty real trials typically produce two or three successes. The posterior lands between the prior and the data, with an interval around point two to point four. It never contains point oh five. Ninety-five percent credible, zero percent coverage. With fifty trials, a twenty-trial prior that is badly wrong can't be overcome.

But there's a theorem in the other direction. Suppose the truth itself is drawn from the prior: the world really works the way the prior says. Then the coverage, averaged over truths and data, can be computed by conditioning on the data first. And for every possible dataset the posterior puts ninety-five percent on its interval, so the average is exactly ninety-five percent. Credible intervals are perfectly calibrated on average over the prior, whatever the prior is, as long as it's the right one. That fact is the basis of simulation-based calibration, a standard check on Bayesian software.

The averaging theorem gives a powerful check on Bayesian software. Simulate a truth from the prior and data from the model. Compute the posterior however you like, grid or Markov chain, and obtain effectively independent posterior draws. Correlated MCMC draws need suitable handling; for discrete parameters randomize ties. Record the rank of the truth among the draws. If the computation is right, the truth is just another draw from the posterior, so its rank is uniform. Repeat a few hundred times; systematic nonuniformity can reveal a computational problem, after allowing for simulation noise and dependence. A flat histogram alone cannot prove correctness; even ignoring the data can pass some rank checks. Sean Talts and colleagues systematized this simulation-based calibration in 2018.

The Coverage Board's six new rows. At p equals point oh five with fifty trials, the Jeffreys credible interval covers eighty-nine percent: broken, the same shortfall Part 11 found for the Jeffreys interval, because the discrete sampling distribution produces undercoverage at this fixed probability. The uniform prior covers ninety-six percent: conservative. The confident, wrong prior: zero. The same prior when the truth is point nine, near the prior mean: ninety-eight and a half percent here. A fixed truth near a prior mean does not guarantee conservative coverage in general. The same prior when the truth is drawn from it: ninety-four point six, kept, as the theorem says. And the reference-prior interval for the World's mean height, which is Part 8's t-interval: ninety-four point eight, kept.

So: with vague priors, credible and confidence intervals nearly coincide, with similar coverage and the same weak spots near boundaries. An informative prior can shorten intervals, but pointwise coverage can be high or low even when the truth is plausible under it. A wrong one is confident and wrong, until enough data outweigh it. Averaged over a prior that really describes the world, credible intervals are exactly calibrated. The prior is a strong assumption, as strong as any model. Treat it like one: justify it, check it against the data, and report how much the answer depends on it.

Numbers: the six board rows above

10Hypotheses, the Bayesian wayMaster's5 min

Can a Bayesian test a hypothesis? Use Part 2's odds form of Bayes's rule, with two hypotheses instead of two diseases: the posterior odds of H one against H zero equal the ratio of how well each predicted the data, times the prior odds. That ratio is the Bayes factor, the factor by which the data multiply the odds, whatever they were. For a hypothesis that leaves a parameter free, how well it predicted the data means its likelihood averaged over its own prior: the marginal likelihood. Harold Jeffreys built a whole theory of testing on this, in 1939.

Is a coin fair? H zero says p is exactly a half; H one says it could be anything, uniformly. Toss it a hundred times and get sixty heads. Part 10's two-sided p-value is point zero five seven: nearly significant. The Bayes factor is the beta function's average of the likelihood under H one, over the likelihood under H zero: point nine one. The data barely move the odds, and in fact very slightly favour the fair coin. Starting from even odds, the fair coin keeps a posterior probability of point five two. A nearly significant p-value and a nearly neutral Bayes factor, from the same tosses.

Now hold the p-value fixed at about point oh five and let the number of tosses grow: a hundred, a thousand, ten thousand, a hundred thousand, with just enough heads each time to be on the edge of significance. The p-value stays at point oh five. The Bayes factor falls from point nine to point oh three, and the posterior probability of the fair coin climbs to ninety-seven percent. With a hundred thousand tosses, fifty point three percent heads is just significant, and a bias that small is better explained by a fair coin than by a coin whose bias could be anywhere. Dennis Lindley pointed this out in 1957; Part 26 takes up what it means for testing.

The other extreme. Test Laplace's question as a pair of hypotheses: boys and girls exactly equally likely, or a chance of a boy that could be anything. With the Paris births, the Bayes factor is about ten to the thirty-eight. It overwhelms ordinary prior odds within this IID binomial model; arbitrary prior odds or a different sampling model can change the conclusion. When the data are overwhelming, the p-value, the posterior and the Bayes factor all say the same thing; it's in the borderline cases, like sixty heads in a hundred, that they part company, and that's where the care is needed.

Is that just the uniform prior's fault? Thomas Sellke, Maria Bayarri and James Berger showed in 2001 that, for a continuous p-value uniform under the null, with alternative p-value densities that are mixtures of Beta a one for zero less than a at most one, the Bayes factor in favour of the null can't fall below minus e times p times the log of p. At p equals point oh five, that's point four one: the data can make the alternative at most two and a half times more likely relative to the null. Starting from even odds, the null keeps a posterior probability of at least twenty-nine percent. A p-value of point oh five is much weaker evidence than it sounds, within that model class. This is not a universal bound over all alternatives or a direct exact calibration for discrete binomial p-values. That's the quantitative version of Part 10's warnings.

Jeffreys offered a scale for reading Bayes factors: up to three, barely worth mentioning; three to ten, substantial; then strong, very strong, and above a hundred, decisive. Two cautions. Unlike posteriors for parameters, Bayes factors stay sensitive to the alternative's prior however much data there are: a very vague prior spreads H one's predictions over everything, and so penalizes it. That's an automatic Occam's razor, simpler hypotheses win unless the data demand more, but it means the prior must be chosen with care. Part 26 returns to priors for testing, and Part 28 to choosing between models.

Numbers: 60 of 100: p = 0.057, BF₁₀ = 0.91, P(H₀ | y) = 0.52; at fixed p ≈ 0.05: BF₁₀ = 0.91, 0.27, 0.086, 0.027 for n = 10², …, 10⁵; Sellke bound BF₀₁ ≥ 0.41 in its continuous p-value model class; births log₁₀ BF ≈ 38

Recap, problems, and the road aheadAll tracks3 min

Part fifteen in thirteen lines. Bayes's billiard table gave the first posterior, and Laplace used one to make the excess of boys a near certainty. The posterior is proportional to likelihood times prior, and updating step by step gives the same answer as updating at once. Conjugate priors make it bookkeeping, and the prior acts like imaginary data. The posterior's mean, median and mode answer different loss functions, and its intervals can be equal-tailed or highest-density. Predictions average over parameter uncertainty; in the binomial example with more than one future trial, they are wider than plug-ins at the same mean. Priors matter with little data, so check sensitivity; Jeffreys's prior is invariant. The normal model's reference posterior is Student's t. Grids compute any small posterior, and a Metropolis walk handles larger ones, if the steps and coordinates are right. Credible intervals are exactly calibrated on average over a true prior, but not at every fixed truth. And Bayes factors, unlike p-values, can favour the null.

Where it comes back. Part 16's bootstrap gives a frequentist cousin of a posterior. Bayesian computation returns in Parts 21 and 27, with EM, Hamiltonian Monte Carlo and variational inference. Hierarchical models and shrinkage, the place Bayes shines brightest, come in Part 25, and the full Bayesian workflow in Part 26. Model choice is Part 28; the Bernstein–von Mises theorem and nonparametric Bayes, Part 53; decision theory, Part 45; and betting and e-values, a different bridge between belief and evidence, Part 58.

Six problems, with full solutions in the README. A small beta posterior; the gamma–Poisson update; one normal observation; the prior as imaginary data; Laplace's rule; and a Bayes factor for a coin. Pause here if you want to try them.

The books and papers this part follows: Gelman and colleagues' Bayesian Data Analysis, Hoff's first course, McElreath's Statistical Rethinking, Jeffreys, Stigler's history and McGrayne's popular one, with the papers from Bayes and Laplace to Sellke, Bayarri and Berger.

Fifteen parts of sixty-five, the fifth of Stage II. We can now say what to believe after seeing data, and compute it. But every method so far, Bayesian or not, has leaned on a model for the data: normal, binomial, Poisson. What can we learn under weaker distributional assumptions? In 1979 Bradley Efron showed how to resample the data themselves, and rank tests had long reduced dependence on parametric distributional models while retaining sampling assumptions. Part 16: without assumptions.

Where it goes next. Bayesian computation returns in Parts 21 and 27, hierarchical models and shrinkage in Part 25, the Bayesian workflow and priors for testing in Part 26, model choice in Part 28, decision theory in Part 45, and the Bernstein-von Mises theorem in Part 53.

Key results

The part's results in one place, for revision.

Bayes's rule for a parameter\(\displaystyle \pi(\theta\mid y)=\frac{\pi(\theta)\,p(y\mid\theta)}{\int\pi(t)\,p(y\mid t)\,dt}\ \propto\ \pi(\theta)\,p(y\mid\theta)\)
Beta-binomial\(\displaystyle p\sim\operatorname{Beta}(a,b),\ s\text{ successes }\allowbreak \text{in }n\ \Longrightarrow\ p\mid s\sim\operatorname{Beta}(a+s,\,b+n-s),\quad\allowbreak \mathbb{E}[p\mid s]=\frac{a+s}{a+b+n}\)
Rule of succession\(\displaystyle P(\text{next }\allowbreak \text{success}\mid s\text{ of }n,\ \text{uniform }\allowbreak \text{prior})=\frac{s+1}{n+2}\)
Normal-normal\(\displaystyle \frac{1}{\tau_n^2}=\frac{1}{\tau_0^2}+\frac{n}{\sigma^2},\qquad\allowbreak \mu_n=\tau_n^2\Bigl(\frac{\mu_0}{\tau_0^2}+\frac{n\bar x}{\sigma^2}\Bigr)\)
Calibration over the prior\(\displaystyle \int P_\theta\bigl(\theta\in C(Y)\bigr)\,\pi(\theta)\,d\theta=0.95\quad\allowbreak \text{when } P\bigl(\theta\in C(y)\mid y\bigr)=0.95\text{ for }\allowbreak \text{every }y\)
Bayes factor, binomial\(\displaystyle BF_{10}=\frac{B(a+s,\,b+n-s)/B(a,b)}{p_0^{\,s}(1-p_0)^{n-s}}\)

Try it

Lab 15 · Credible intervals on the Coverage Board

For a binomial with n = 50 and three beta priors, compute how often the 95% credible interval contains a fixed truth, exactly and by simulation; then draw the truth from the prior and check that the coverage is 95%.

Figure produced by Lab 15: Credible intervals on the Coverage Board
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.stats.labs 15 needs numpy, scipy, matplotlib · download lab15.py · source on GitHub
uniform Beta(1, 1), truth fixed at 0.05               exact 96.22%   simulated 96.16%
uniform Beta(1, 1), truth fixed at 0.9                exact 97.03%   simulated 96.92%
Jeffreys Beta(1/2, 1/2), truth fixed at 0.05          exact 88.53%   simulated 88.77%
Jeffreys Beta(1/2, 1/2), truth fixed at 0.9           exact 94.17%   simulated 94.07%
confident Beta(18, 2), truth fixed at 0.05            exact 0.00%   simulated 0.00%
confident Beta(18, 2), truth fixed at 0.9             exact 98.55%   simulated 98.42%
confident Beta(18, 2), truth drawn from the prior     simulated 94.56%   (theory 95.00%, Monte Carlo SE 0.22%)
confident Beta(18, 2), truth drawn uniformly instead  simulated 47.91%

A credible interval's 95% is a statement given the data. Averaged over truths drawn from the prior it is also a frequency; at one fixed truth it can be anything, and a confident wrong prior makes it 0.
The code (85 lines; it asserts its own result)
"""Lab 15: judge 95% credible intervals by frequency, at a fixed truth and on average over the prior."""

import numpy as np
from scipy import stats

from videos.coursekit import labs
from explainer.stats.kit import bayes

TITLE = "Credible intervals on the Coverage Board"
GOAL = ("For a binomial with n = 50 and three beta priors, compute how often the 95% credible interval contains a "
        "fixed truth, exactly and by simulation; then draw the truth from the prior and check that the coverage "
        "is 95%.")
TASKS = [
    "Draw the truth from Beta(2, 18) but keep the Beta(18, 2) prior in the analysis. What is the average coverage now?",
    "Replace bayes.credible by bayes.hpd. Is the HPD interval's coverage over the prior still 95%? Is its curve against p the same?",
    "Raise n from 50 to 500 with the Beta(18, 2) prior. How large must n be before coverage at p = 0.05 passes 90%?",
]


def run(seed=0):
    rng = np.random.default_rng(seed)
    n, reps = 50, 10_000
    priors = (("uniform Beta(1, 1)", 1.0, 1.0, labs.BLUE), ("Jeffreys Beta(1/2, 1/2)", 0.5, 0.5, labs.GREEN),
              ("confident Beta(18, 2)", 18.0, 2.0, labs.RED))
    ks = np.arange(n + 1)
    ps = np.linspace(0.005, 0.995, 199)

    def table(a, b):  # the 95% equal-tailed interval after each possible count
        return np.array([bayes.credible(stats.beta(*bayes.beta_update(a, b, k, n - k))) for k in ks])

    def exact(tab, p):  # coverage at a fixed p: a sum over the n + 1 outcomes
        p = np.atleast_1d(p)
        inside = (tab[None, :, 0] <= p[:, None]) & (p[:, None] <= tab[None, :, 1])
        return (stats.binom.pmf(ks[None, :], n, p[:, None]) * inside).sum(1)

    lab = labs.Lab()
    curves, tabs = {}, {}
    for name, a, b, _ in priors:
        tabs[name] = tab = table(a, b)
        curves[name] = exact(tab, ps)
        for p0 in (0.05, 0.9):
            x = rng.binomial(n, p0, reps)
            sim = float(np.mean((tab[x, 0] <= p0) & (p0 <= tab[x, 1])))
            ex = float(exact(tab, p0)[0])
            assert abs(sim - ex) < 4 * np.sqrt(max(ex * (1 - ex), 1e-4) / reps), "simulation agrees with the exact sum"
            lab.row(f"{name}, truth fixed at {p0}", f"exact {ex:.2%}   simulated {sim:.2%}")

    # the truth drawn from the prior the analyst uses
    name, a, b, _ = priors[2]
    p = rng.beta(a, b, reps)
    x = rng.binomial(n, p)
    hit = (tabs[name][x, 0] <= p) & (p <= tabs[name][x, 1])
    avg, se = float(hit.mean()), float(np.sqrt(0.95 * 0.05 / reps))
    lab.row(f"{name}, truth drawn from the prior", f"simulated {avg:.2%}   (theory 95.00%, Monte Carlo SE {se:.2%})")
    wrong = rng.uniform(0, 1, reps)  # the world does not follow the prior
    xw = rng.binomial(n, wrong)
    avg_wrong = float(np.mean((tabs[name][xw, 0] <= wrong) & (wrong <= tabs[name][xw, 1])))
    lab.row(f"{name}, truth drawn uniformly instead", f"simulated {avg_wrong:.2%}")
    lab.note = ("A credible interval's 95% is a statement given the data. Averaged over truths drawn from the prior "
                "it is also a frequency; at one fixed truth it can be anything, and a confident wrong prior makes it 0.")
    assert abs(avg - 0.95) < 4 * se, "calibrated on average over the prior"
    assert float(exact(tabs[name], 0.05)[0]) < 0.001, "Beta(18, 2) never covers a truth of 0.05 at n = 50"
    assert float(exact(tabs[name], 0.9)[0]) > 0.97 and avg_wrong < 0.85, "right for the truths it expects, wrong for the rest"
    assert abs(curves[priors[0][0]].mean() - 0.95) < 0.01 and abs(curves[priors[1][0]].mean() - 0.95) < 0.01

    fig, ax = labs.figure(2, size=(11, 4.2))
    for name, a, b, color in priors:
        ax[0].plot(ps, curves[name], color=color, lw=1.2, label=name)
    ax[0].axhline(0.95, color=labs.MUTED, ls="--", lw=1)
    ax[0].set(title="Coverage of the 95% credible interval at a fixed truth, n = 50", xlabel="true proportion p",
              ylabel="coverage", ylim=(-0.03, 1.03))
    ax[0].legend(loc="center left", bbox_to_anchor=(0.02, 0.62))
    grid = np.linspace(0.001, 0.999, 500)
    post = stats.beta(*bayes.beta_update(1, 1, 8, 4))
    lo, hi = bayes.credible(post)
    ax[1].plot(grid, np.ones_like(grid), color=labs.MUTED, label="prior: uniform")
    ax[1].plot(grid, post.pdf(grid), color=labs.GOLD, label="posterior Beta(9, 5)")
    ax[1].fill_between(grid, post.pdf(grid), where=(grid >= lo) & (grid <= hi), color=labs.GOLD, alpha=0.25,
                       label=f"95% credible [{lo:.2f}, {hi:.2f}]")
    ax[1].axvline(bayes.rule_of_succession(8, 12), color=labs.BLUE, ls=":", label="mean 9/14 (rule of succession)")
    ax[1].set(title="Bayes's table: 8 of 12 balls stop to the left", xlabel="position p of the hidden ball", ylabel="density",
              ylim=(0, 4.6))
    ax[1].legend(loc="upper left")
    lab.fig = fig
    return lab

Now change it

  1. Draw the truth from Beta(2, 18) but keep the Beta(18, 2) prior in the analysis. What is the average coverage now?
  2. Replace bayes.credible by bayes.hpd. Is the HPD interval's coverage over the prior still 95%? Is its curve against p the same?
  3. Raise n from 50 to 500 with the Beta(18, 2) prior. How large must n be before coverage at p = 0.05 passes 90%?

Problems, with solutions

Try each problem before opening its solution.

1. A small beta posterior. Uniform prior, 3 successes in 5 trials: the posterior, its mean, and \(P(p > \tfrac12 \mid \text{data})\).

Solution

The posterior is Beta(1 + 3, 1 + 2) = Beta(4, 3), with mean 4/7 = 0.571.

P(p > ½) = 1 − I½(4, 3). For integer parameters this is a binomial sum: P(at least 4 successes in 6 fair trials) = (15 + 6 + 1)/64 = 22/64 = 0.344. So P(p > ½) = 1 − 0.344 = 0.656.

2. Gamma–Poisson. Show that a Gamma\((\alpha, \beta)\) prior and Poisson counts \(y_1, \ldots, y_n\) give a Gamma\((\alpha + \sum y_i, \beta + n)\) posterior.

Solution

π(λ) ∝ λ^(α−1) e^(−βλ) and the likelihood ∝ ∏ λ^(yᵢ) e^(−λ) = λ^(Σyᵢ) e^(−nλ). Their product is λ^(α+Σyᵢ−1) e^(−(β+n)λ), the kernel of Gamma(α + Σyᵢ, β + n).

3. One normal observation. Prior \(\mu \sim N(0, 1)\), one observation \(x = 2\) with \(\sigma = 1\): the posterior for \(\mu\).

Solution

The precisions add, 1 + 1 = 2, so the posterior variance is ½. The posterior mean is (0 · 1 + 2 · 1)/2 = 1. The posterior is N(1, ½): halfway between prior and data, because they are equally precise.

4. The prior as imaginary data. Show the Beta–binomial posterior mean is a weighted average of \(a/(a + b)\) and \(s/n\), and give the weights.

Solution

(a + s)/(a + b + n) = [(a + b)/(a + b + n)] · a/(a + b) + [n/(a + b + n)] · s/n. The weights, (a + b)/(a + b + n) and n/(a + b + n), sum to 1, and the data's weight tends to 1 as n grows.

5. The rule of succession. Derive Laplace's rule of succession, \((s + 1)/(n + 2)\).

Solution

With a uniform prior the posterior is Beta(s + 1, n − s + 1). P(next success) is its mean, (s + 1)/((s + 1) + (n − s + 1)) = (s + 1)/(n + 2).

6. A Bayes factor. 9 heads in 10 tosses: the Bayes factor for \(p \sim U(0, 1)\) against \(p = \tfrac12\), and Jeffreys's verdict.

Solution
  • Under H₁: p(y | H₁) = C(10, 9) ∫p⁹(1 − p) dp = C(10, 9) B(10, 2) = 10/110.
  • Under H₀: p(y | H₀) = C(10, 9) 2⁻¹⁰ = 10/1024.
  • The ratio: BF₁₀ = 1024/110 = 9.31, "substantial" on Jeffreys's scale.

The two-sided p-value is 22/1024 = 0.021.

Notes and sources

Where it comes back

Idea Returns in
resampling distributions, the bootstrap 16
EM and optimization; MCMC in depth, HMC, variational inference 21, 27
hierarchical models and shrinkage 25
the Bayesian workflow, priors for testing 26
model choice, marginal likelihoods 28
decision theory, admissibility 45
Bernstein–von Mises, nonparametric Bayes 53
e-values: a betting view of evidence 58
the Coverage Board every part; 65

Sources

  • The founders.
    • T. Bayes, Phil. Trans. 53 (1763).
    • P.-S. Laplace, "Mémoire sur la probabilité des causes par les événements" (1774); Essai philosophique sur les probabilités (1814).
    • H. Jeffreys, Theory of Probability (1939); Proc. R. Soc. A 186 (1946).
  • Priors and testing.
    • H. Raiffa & R. Schlaifer, Applied Statistical Decision Theory (1961).
    • D. Lindley, Biometrika 44 (1957).
    • G. Box, JRSS A 143 (1980); D. Rubin, Ann. Stat. 12 (1984).
    • T. Sellke, M. Bayarri & J. Berger, Am. Stat. 55 (2001).
    • A. Gelman, A. Jakulin, M. Pittau & Y.-S. Su, Ann. Appl. Stat. 2 (2008).
  • Computation and calibration.
    • N. Metropolis, A. Rosenbluth, M. Rosenbluth, A. Teller & E. Teller, J. Chem. Phys. 21 (1953).
    • A. Gelfand & A. Smith, JASA 85 (1990); G. Roberts, A. Gelman & W. Gilks, Ann. Appl. Prob. 7 (1997).
    • S. Cook, A. Gelman & D. Rubin, JCGS 15 (2006); S. Talts et al., arXiv:1804.06788 (2018).
  • Books and history.
    • A. Gelman et al., Bayesian Data Analysis (3rd ed., 2013); P. Hoff, A First Course in Bayesian Statistical Methods (2009); R. McElreath, Statistical Rethinking (2nd ed., 2020).
    • S. Stigler, The History of Statistics (1986); S. McGrayne, The Theory That Would Not Die (2011).
About this partfrom its README

Part 15 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), in Stage II, Bachelor's: Methods. Parts 8–14 treated parameters as fixed and data as random. This part asks what to believe about a parameter after seeing the data.

It opens with Bayes's essay of 1763 and his billiard table: a hidden ball, and twelve more balls of which 8 land left. The posterior is Beta(9, 5), against a truth of 0.62. Then Laplace's Paris births (P(p ≤ ½) ≈ 1.15 × 10⁻⁴²) and his sunrise.

From there the part covers:

  • The machinery. Bayes's rule for parameters, drawn as prior × likelihood ∝ posterior. The billiard balls update one at a time, and sequential updating equals batch updating. The meaning of the shift, and a short history from inverse probability to MCMC.
  • Conjugacy. Beta–binomial, the prior as imaginary data, gamma–Poisson on the horse kicks, and normal–normal precision weighting on the World's heights.
  • Summaries. Mean, median and mode as decisions; equal-tailed vs HPD intervals; invariance; the Laplace approximation.
  • Prediction. The beta-binomial predictive vs a plug-in, the law of total variance, the horse-kick predictive, the normal predictive (Part 11's prediction interval) and posterior predictive checks.
  • Priors. Four priors at n = 10 and n = 100. A flat prior is not flat on the odds. Jeffreys's invariant prior, prior predictive checks, and the kinds of prior.
  • The normal model. The reference prior gives Part 8's t and χ² intervals exactly.
  • Grids. The Challenger posterior on 325,141 points: P(β₁ < 0) and the posterior of p(31 °F). A mixture prior, and the curse of dimension.
  • Metropolis. Detailed balance; step sizes on trace plots; the ridge and the cure of centring; burn-in; agreement with the grid; functions of the draws.
  • Bayes and frequency. Credible intervals' coverage at a fixed truth (the Board), exact calibration on average over the prior, and simulation-based calibration.
  • Hypotheses. Bayes factors, a coin with 60 heads in 100, Lindley's warning at fixed p = 0.05, Sellke–Bayarri– Berger's bound, Laplace's births and Jeffreys's scale.

Every number on screen is computed in compute.py or inline in a scene:

  • the Paris births, the horse kicks and the Challenger flights come from the Museum;
  • heights are the World's (seed 1662);
  • the billiard table is a seeded simulation.

Built in this part:

  • statkit.bayes (I) (explainer/stats/kit/bayes.py), checked in tests/test_stats_kit_bayes.py:
    • conjugate updates (beta, gamma, normal, and the normal model with unknown variance);
    • equal-tailed and HPD intervals;
    • the beta-binomial predictive and the rule of succession;
    • 1-D and 2-D grid posteriors;
    • random-walk Metropolis with an effective sample size;
    • binomial Bayes factors.
  • The billiard table (BilliardTable in explainer/stats/viz.py): Bayes's table seen from above. A hidden ball's line, with balls rolled to their spots.

The Coverage Board gains six rows, all 95% credible intervals, R = 10,000.

Method Setting Achieved Verdict
credible, Jeffreys prior binomial, n = 50, p = 0.05 89.31% broken
credible, uniform prior binomial, n = 50, p = 0.05 95.96% conservative
credible, Beta(18, 2) prior binomial, n = 50, p = 0.05 0.00% broken
credible, Beta(18, 2) prior binomial, n = 50, p = 0.9 98.49% conservative
credible, Beta(18, 2) prior binomial, n = 50, p drawn from the prior 94.55% kept
credible, reference prior the World's heights, n = 10 94.81% kept

The Challenger grid approximates the proper posterior under an improper flat coefficient prior; its finite rectangle is numerical truncation, checked against wider and finer grids. Grid probabilities use trapezoidal weights, and transformed summaries integrate those weights rather than adding independent coordinate jitter. The predictive comparison uses the posterior mean in both forecasts. Normal reference results assume IID Gaussian data and positive sample variance; the World height sample is an illustration of that model. The Sellke calibration is not universal over all alternatives or an exact bound for arbitrary discrete p-values. SBC rank uniformity needs independent conditional posterior draws and randomized ties; flat ranks alone do not prove correctness.

Chapter notes
# Chapter Numbers
0 The billiard table, 1763 8 of 12 left: Beta(9, 5), mean 0.64, 95% [0.39, 0.86], truth 0.62; Paris 251,527 boys and 241,945 girls, P(p ≤ ½) ≈ 1.15 × 10⁻⁴²; sunrise odds 1,826,214 to 1
1 The machinery Beta(2, 2) × 7 of 10 → Beta(9, 5)
2 Conjugacy posterior mean 0.643; horse kicks Gamma(123, 201), mean 0.612, 95% [0.509, 0.725]; heights N(169.3, 2.74²), data weight 92.5%, truth 169.5
3 Summaries Beta(3, 12): mode 0.154, median 0.186, mean 0.200; equal-tailed [0.047, 0.428], HPD [0.029, 0.395]; Laplace approximation SD 0.100
4 Prediction next 10 trials: SD 1.92 (predictive) vs 1.52 (plug-in at the same posterior mean); P(no horse-kick death) 0.543 either way
5 Priors n = 10: means 0.45–0.68; n = 100: 0.64–0.70; Beta(2, 8) predicts ≥ 7 of 10 with probability 0.015
6 The normal model 8 adults: 95% [165.06, 175.89] = the t-interval; σ ∈ [4.28, 13.19]
7 Grids Challenger: E[β₁] ≈ −0.291, P(β₁ < 0) ≈ 0.9989; p(31): median 0.9999, P(> 0.9) ≈ 0.976; mixture prior P(0.4 < p < 0.6) = 0.65
8 When grids fail ESS of 5,000 draws: 12 (tiny), 212 (good), 48 (huge); raw coordinates 12; long-chain slope ESS 510; summaries agree with the expanded grid within Monte Carlo error; OR per 10 °F median 15 (all retained draws)
9 Bayes and frequency the six board rows above
10 Hypotheses 60 of 100: p = 0.057, BF₁₀ = 0.91, P(H₀ | y) = 0.52; at fixed p ≈ 0.05: BF₁₀ = 0.91, 0.27, 0.086, 0.027 for n = 10², …, 10⁵; Sellke bound BF₀₁ ≥ 0.41 in its continuous p-value model class; births log₁₀ BF ≈ 38
11 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: Bayes's billiard table (1763). The Beta posterior; Laplace's rule of succession; Laplace's Paris births (figures (verify)).
  2. The machinery. Prior × likelihood ∝ posterior (BayesUpdate); sequential = batch updating.
  3. Conjugacy. Beta–binomial, gamma–Poisson, normal–normal (precision weighting derived).
  4. Summaries. Posterior mean, median and mode; credible intervals; HPD.
  5. Prediction. Posterior predictive distributions; the beta-binomial.
  6. Priors. Informative and weakly informative; flat priors and their traps; sensitivity analysis.
  7. The normal model. Unknown μ and σ² give a t posterior, matching Part 8's t-interval.
  8. Grids. Computing any one- or two-parameter posterior on a grid.
  9. When grids fail. A Metropolis walk by hand (Part 7), with trace plots.
  10. Bayes and frequency. Credible intervals' coverage at fixed θ (Board); when they agree.
  11. Hypotheses, the Bayesian way. Posterior odds and Bayes factors, first look (Part 26).
  12. Outro.

Built: the billiard table; statkit.bayes (I).

Build the film

python -m videos.stats.stats15.compute        # the part's numbers, into .cache/stats15
python tools/build.py stats15                  # render and assemble the film
EXPLAINER_TTS=silent python tools/qa_scene.py stats15 Hook   # one chapter, silent, with a contact sheet

Scenes: videos/stats/stats15. Setup: see the course page. Source of these notes: the README and the scenes' narration.

Build it
python -m videos.stats.stats15.compute         # once (a few minutes; cached in .cache/stats15)
python tools/build.py stats15 -q l             # fast 480p preview
python tools/build.py stats15                  # 1080p30 -> renders/stats15.mp4
python tools/qa_scene.py stats15 Metropolis
python tools/lecture_length.py stats15 --floor 50