SStatistics, Built

Stage III · Master's

Part 26 of 65

Bayesian Data Analysis

Master'sstarts at this level53 min of film15 chaptersprerequisites: Part 15, Part 25

How do you build, fit and check a Bayesian model with many parameters, honestly?

Rubin's eight schools open the part: eight SAT coaching experiments with estimated effects from -3 to 28 points and standard errors of 9 to 18. No pooling believes each estimate, complete pooling gives one effect of 7.7, and Part 25's empirical Bayes estimates a spread of zero and collapses to the second. The hierarchical model, justified by exchangeability and de Finetti's theorem, averages over the spread tau instead: its posterior is computed on a grid, and the tau explorer shows every school's estimate fanning out as tau grows. The part then asks what the prior on tau does (four priors, eight schools and three), states Bernstein-von Mises and where it fails, and computes Bayes factors until Lindley's paradox appears in the PEAR data: p = 0.0003 and a posterior probability of 0.92 for the null. It turns to practice with decisions and the value of information, posterior and prior predictive checks, and simulation-based calibration, which catches a halved variance. It ends with the argument between the schools of inference stated honestly, and a first look at the Dirichlet process.

What you need. Part 15's one-parameter Bayes (conjugate updates, credible intervals) and Part 25's empirical Bayes; multivariate calculus for the Gaussian integrals.

Hook
the eight schools, 1981
Mathematics
hierarchical Bayes, priors, Bernstein–von Mises, Bayes factors, Lindley's paradox, checking, workflow
Built
statkit.bayes

What you will be able to do

Bachelor's

  • Explain no pooling, complete pooling and partial pooling on the eight schools, and say why school A's 28 becomes about 10.
  • Read a posterior for tau and a posterior predictive check, and say what each does and does not show.

Master's

  • Derive the marginal posterior of tau in the hierarchical normal model and draw from the joint posterior by tau, then mu, then the effects.
  • Compute the normal point-null Bayes factor, show Bartlett's and Lindley's paradoxes with it, and state the Sellke-Bayarri-Berger bound.
  • Derive Jeffreys's prior and prove its invariance under reparametrization.

PhD

  • State the conditions of Bernstein-von Mises and explain each of the part's failures (a mode on the boundary, Neyman-Scott, nonparametric priors) as a condition dropped.
  • State what de Finetti's theorem gives and what it does not: infinite extendibility, and no normal population.

Practice

  • Run a Bayesian workflow: a prior predictive check, a fit, a posterior predictive check on a feature the model was not built to match, and a sensitivity analysis over the prior on tau.
  • Validate posterior code by simulation-based calibration and say what uniform ranks cannot detect.

Contents

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

  1. 0The eight schools, 1981Bachelor's2 min
  2. 1Upgrade: what Part 15 assumedBachelor's3 min
  3. 2Hierarchical modelsMaster's4 min
  4. 3PriorsMaster's3 min
  5. 4Conjugate and exponential familiesMaster's4 min
  6. 5Bernstein-von MisesMaster's4 min
  7. 6Bayes factorsMaster's4 min
  8. 7Lindley's paradoxMaster's4 min
  9. 8Occam's razor, built inMaster's3 min
  10. 9DecisionsMaster's4 min
  11. 10CheckingPractice3 min
  12. 11WorkflowPractice4 min
  13. 12The argument, honestlyBachelor's4 min
  14. 13Bayesian nonparametrics, first lookPhD3 min
  15. 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 eight schools, 1981Bachelor's2 min

In the late 1970s the Educational Testing Service studied coaching for the verbal SAT. In each of eight high schools, a separate randomized experiment compared students who took a short coaching course with students who did not. In 1981 Donald Rubin used the results to show what a Bayesian analysis could do. The SAT was designed to resist short-term coaching, so large effects would be surprising. And each experiment was small, so every estimate is noisy.

Here are the eight estimated effects, in SAT points, with their standard errors. The thick bars are one standard error each way; the thin bars two. School A's estimate is twenty-eight points; school C's is minus three. But the standard errors run from nine to eighteen points, and every interval overlaps every other.

Two obvious answers. No pooling: use each school's own noisy estimate, twenty-eight points at A and minus three at C, with its uncertainty. Complete pooling: the schools are alike, so combine all eight into one precision-weighted average, seven point seven points, with a standard error of four. The band is an approximate ninety-five-percent interval under the common-effect model. A test of equal effects doesn't come close to rejecting them: the scatter of the eight estimates is no larger than their standard errors predict. Yet telling school A, whose own experiment showed twenty-eight, that its effect was seven point seven, feels wrong too.

Both answers are extreme choices of one unknown, tau, the standard deviation of the true effects across schools. No pooling takes tau to be infinite. Complete pooling takes it to be zero. A plug-in empirical-Bayes analysis estimates tau at the zero boundary for these data, so empirical Bayes collapses to complete pooling. The Bayesian answer treats tau itself as unknown, with a prior, and averages over everything the data leave uncertain.

Numbers: pooled 7.7 ± 4.1; Q 4.7, p 0.70; τ̂_EB = 0

1Upgrade: what Part 15 assumedBachelor's3 min

Part 15 laid down Bayes's machinery: choose a prior, multiply by the likelihood, normalize, and the posterior is the answer. It quietly assumed one parameter at a time, a prior picked by hand, and a model taken on trust. This part removes all three: many related parameters whose prior is partly learned from the data, priors chosen for reasons, and the tests, decisions and checks that make a Bayesian analysis a complete one.

What justifies a prior that ties the schools together? Part 5's exchangeability: our beliefs about the eight true effects don't change if we shuffle the schools' labels. Before seeing any data, we have no reason to expect school A to differ from school E. Exchangeable doesn't mean independent: if we learned that coaching worked wonders at A, we'd expect more of it at B too, and that is exactly how the schools borrow strength. Effects drawn independently from a common distribution are exchangeable.

An infinitely exchangeable sequence can be represented as draws that are independent and identically distributed given a random population distribution. Eight exchangeable effects alone do not guarantee this infinite extension. We additionally choose a normal population described by mu and tau. Normality is a modelling assumption, not de Finetti's conclusion. A hyperprior describes uncertainty about these population parameters. Exchangeability motivates sharing information; the population family and hyperprior still require justification.

Exchangeability is a judgement, and it can be conditional. If schools differed in a known way, say in the hours of coaching offered, we would make them exchangeable given that, by putting the covariate into the population model, as the radon counties got their uranium in Part 25. A university's programme would not belong in the same exchangeable group at all. This is where judgement enters a Bayesian analysis, and it should be stated openly.

Hierarchical models are everywhere this judgement fits. Hospitals, schools and counties, Part 25's league tables and small areas. Election forecasts that estimate opinion in every state from one national poll, by multilevel regression and post-stratification. Thousands of genes whose effects share one prior, Part 33's subject. Players' skills in sport, and trials in a medical meta-analysis. Wherever many related units each have little data, the hierarchy lets them inform each other.

Numbers: exchangeability; de Finetti

2Hierarchical modelsMaster's4 min

The model has three levels. Each school's estimate is its true effect plus noise of known size. The true effects come from a normal population with mean mu and spread tau. And mu and tau get a prior, here flat, a choice chapter three examines. Bayes's rule then gives one joint posterior for all ten unknowns: eight effects, a mean and a spread.

Ten dimensions sound hard, but the posterior factors. Integrating out the effects and the mean leaves a one-dimensional posterior for tau, which a wide nonuniform grid approximates, checked against adaptive integration to infinity. Given tau, the mean is normal, centred at a precision-weighted average of the schools. Given both, each school's effect is Part 15's normal update: a weighted average of its own estimate and the population mean. Draw tau, then mu, then the effects, and the conditional normal steps are exact, while tau uses a checked numerical approximation. These independent draws need no Markov chain.

This is the tau explorer. The top panel shows each school's estimate given tau. At tau equal to zero, every school sits at the pooled mean, seven point seven. As tau grows, each school is trusted more, and the lines fan out towards the schools' own estimates: A's climbs towards twenty-eight. The bottom panel is the posterior for tau. It is highest at zero and falls slowly: the data can't rule out identical schools, but can't rule out differences of fifteen or twenty points either. Its median is five, and its ninety-five percent interval runs from nearly zero to twenty. The Bayesian answer averages the top panel over the bottom one.

What does a draw from this posterior look like? Each line is one independent numerical draw of all eight effects together, coloured by its value of tau. Draws with small tau are nearly flat: in those worlds the schools barely differ. Draws with large tau zigzag: in those worlds coaching worked very differently from school to school. The posterior is the whole collection, and every summary that follows is a summary of draws like these.

The result, school by school. In blue, each school's own estimate. In green, its posterior median and ninety-five percent interval. School A's twenty-eight becomes ten, with an interval from minus two to about thirty-two: probably a positive effect, probably much smaller than its own experiment suggested. C's minus three becomes six and a half. All are pulled towards the population mean of about eight: further than no pooling allows, not as far as complete pooling forces.

The posterior draws answer any question directly, with no new theory. The probability that coaching helped more at A than at C is point six eight: suggestive, far from certain. The probability that A had the largest effect of all eight is a quarter. If we knew nothing it would be one in eight; the data have doubled it, no more. Rankings of noisy units, Part 25's league tables, come out of the posterior honestly.

Compare Part 25. Empirical Bayes plugs in an estimate of tau; here the estimate is zero, so every school would be told seven point seven, with intervals that omit uncertainty about the variance estimate. Full Bayes averages over tau's posterior, which still gives real weight to differences of fifteen points, and widens the intervals accordingly. With eight groups the difference is large. With many informative groups and a suitable model, tau can be tightly estimated and the approaches can agree closely. Group count alone is not a guarantee.

Numbers: τ median 5.2 [0.2, 20.8]; A 10.2 [−2.2, 31.6]; P(A > C) 0.68; P(A best) 0.25

3PriorsMaster's3 min

Part 15 met the problem: a flat prior on a probability isn't flat on its log odds, so 'knowing nothing' depends on the scale you happen to write the parameter in. Harold Jeffreys's 1946 answer: take the prior proportional to the square root of the Fisher information. Under any change of variables, the information transforms with exactly the Jacobian that a density needs, so the rule gives the same prior whichever scale you start from. For a binomial proportion it's the beta of a half and a half.

On the left, priors for a proportion; on the right, the same priors seen on the log-odds scale. The flat prior on p, in blue, becomes a hump on the log odds, quite confident that the odds are moderate. Jeffreys's prior, in purple, piles up at zero and one on the p scale and is broader on the log-odds scale; it is the same rule applied to either, and the two pictures are the same distribution. No prior is uninformative on every scale; Jeffreys's is at least consistent.

José Bernardo's reference priors of 1979 ask for the prior from which the data are expected to teach the most, measured by expected posterior-to-prior Kullback–Leibler information in a regular repeated-sampling limit. For one regular parameter, that is Jeffreys's prior again. With nuisance parameters, Bernardo and James Berger handle them in order of interest, avoiding the cases where Jeffreys's rule misbehaves in many dimensions. For a normal mean and variance, Jeffreys's joint rule gives one over sigma squared; the reference prior gives one over sigma, and its posterior interval for the mean is exactly Student's t interval, so the frequentist and Bayesian answers coincide.

Andrew Gelman's 2006 paper argued for weakly informative priors: priors that rule out the absurd without ruling out the plausible. For tau, a half-Cauchy with scale twenty-five points: most of its mass is below fifty, since a coaching course that moves SAT scores by a hundred points between schools is absurd, but it has a long tail. The popular inverse-gamma with tiny parameters on tau squared looks vague and isn't: its density can peak near a tiny positive variance while retaining an extremely heavy tail. That is not a neutral prior; in this example it pushes the posterior towards zero. The test of any prior is whether the answer changes when the prior does.

An improper prior is acceptable only if the posterior comes out proper. Take the 'scale-invariant' prior that is flat on log tau. As tau goes to zero, the likelihood doesn't vanish; it tends to the likelihood of complete pooling. So the posterior of log tau stays flat all the way to minus infinity, and has infinite area: there is no posterior at all. A sampler can produce plausible-looking output while drifting towards zero; it need not diagnose an improper target. Check propriety, or use a proper prior.

Numbers: medians 5.2 / 4.8 / 1.2 / 0.6 (eight), 23.0 / 10.9 / 1.2 / 1.0 (three)

4Conjugate and exponential familiesMaster's4 min

Part 15's conjugate pairs all come from one source. Write the model as an exponential family, with natural parameter theta, sufficient statistic T and cumulant function A. Now choose a prior with the same shape in theta, governed by two numbers, chi and nu. Multiplying by the likelihood keeps that shape. So updating is bookkeeping: add the data's sufficient statistics to chi and the sample size to nu. The natural-parameter prior has a pseudo-data interpretation through chi and nu, provided the parameters define a proper prior.

For a regular natural exponential family with a proper conjugate prior and suitable boundary conditions, Diaconis and Ylvisaker obtain a linear posterior mean of the mean parameter. The displayed fraction weights the prior mean and the observed sufficient-statistic mean. Under their characterization conditions, linearity for all sample sizes identifies this conjugate family. This is not a converse for every imaginable model. The weight n over nu plus n tends to one as the sample grows.

The table that follows from it. A beta prior for a proportion is worth a plus b trials; a gamma prior for a Poisson rate is worth b periods of observation; a normal prior for a mean is worth nu observations. Variances, category probabilities and failure rates work the same way. Reading a prior as pseudo-data is the quickest way to tell whether it is strong or weak.

An example: the mean number of doctor visits a year in the World, with a Poisson model and a gamma prior whose mean is four visits, worth a single adult. With one adult, the posterior mean is halfway between the prior's four and the adult's three. With five, the data get five-sixths of the weight; with a thousand, almost all of it, and the posterior mean is two point one five against the World's two point two four. But look at the sample of a hundred: its interval, two and a half to three point two, misses the truth. One missed ninety-five-percent interval does not diagnose a model. We also know the World's visits are overdispersed, which motivates the predictive checks in chapter ten. Conjugacy makes the arithmetic easy; it doesn't make the model right. Chapter ten catches this.

Conjugacy also gives the predictive distribution for a new observation in closed form. A new adult's visits are Poisson given the rate, and the rate has its gamma posterior. Average the Poisson over that posterior, and the result is a negative binomial, Part 24's gamma mixture of Poissons arising for a new reason. The predictive has greater variance than a Poisson with the same predictive mean because it carries the uncertainty about the rate. But with a thousand adults that uncertainty is tiny, and the predictive is still far narrower than the World's real spread of visits: parameter uncertainty is not a substitute for the right model.

Conjugacy goes further than it seems. Under suitable approximation conditions, mixtures of conjugate priors can represent many useful prior shapes, retaining tractable component updates. Inside bigger models, conjugate pieces make Gibbs sampling possible, as Part 27 shows. Normal priors for logistic coefficients are not conjugate. Formal conjugate families can exist, but their normalizers and summaries can still require numerical integration. Most useful hierarchies need approximation or simulation. And a prior's convenience is never a reason to believe it.

Numbers: 3.50 → 2.15; the n = 100 interval misses 2.24

5Bernstein-von MisesMaster's4 min

In a correctly specified regular model, the Bernstein–von Mises theorem gives a posterior approaching a normal centered at the maximum likelihood estimate, with inverse-information variance. The total-variation error tends to zero in probability. Conditions include fixed finite dimension, identifiable interior truth, nonsingular information, posterior concentration and a prior positive and continuous near the truth. Usual regular credible intervals then have asymptotically matching confidence coverage. The posterior width is of order one over root n. The general theorem does not promise that exact rate for every prior's influence or total-variation error.

Why it works, in Laplace's own argument. The log posterior is the log prior plus the log likelihood. Near the maximum likelihood estimate, the log likelihood is close to a quadratic whose curvature is n times the Fisher information, so it grows with every observation. The log prior doesn't grow at all; its share shrinks to nothing, provided it is smooth and positive near the truth. A log density that is a quadratic is a normal. The hard part of the proof, Part 53's, is showing that the regions far from the estimate don't matter.

A Poisson rate of two, observed three, thirty and three hundred times. In orange, the posterior from Jeffreys's prior; in dashed blue, the likelihood-based normal uncertainty approximation, centered on the observed estimate. With three observations they visibly differ, a total variation distance of point oh eight. With thirty, point oh three. With three hundred, about point oh oh eight: the curves nearly coincide. The distance includes the full tails, including negative support of the approximating normal.

Bernstein–von Mises also predicts frequentist coverage. Take the ninety-five percent credible interval for a Poisson rate from Jeffreys's prior, and compute exactly how often it would cover a true rate of two. Even with one observation it covers ninety-eight percent of the time; by a hundred, ninety-five point two, wobbling with the discreteness of the counts. Judged by the other school's standard, this Bayesian interval passes. Priors chosen by Jeffreys's rule are often called probability matching for this reason.

The eight schools show the theorem failing in practice. Tau is learned from eight numbers, and its posterior peaks at zero, exactly on the boundary. A normal curve centred at the peak would put half its mass on negative standard deviations; no normal approximation fits this shape. That is why chapter two checked a numerical grid against infinite-range integration, and why Part 27 needs samplers that respect the geometry.

But the truce has borders. The eight schools' tau is learned from eight numbers, and its posterior is far from normal for these data. Eight groups are not a large-group asymptotic limit. A true value on a boundary, like a variance of zero, breaks the theorem's conditions. When parameters multiply with the data, as in Part 22's Neyman–Scott problem, the prior keeps mattering. And with infinite-dimensional priors, David Freedman, and later Persi Diaconis with him, showed posteriors that converge to the wrong answer, the story Part 53 begins with. These are settings where the basic theorem need not apply. Some high-dimensional or nonparametric functionals still have positive results under additional conditions; the prior and the target both matter.

Numbers: TV 0.084 / 0.028 / 0.008; coverage 98.3% → 95.2%

6Bayes factorsMaster's4 min

Bayes's rule for two hypotheses says the posterior odds are the prior odds times a factor the data supply. That factor, the Bayes factor, is the ratio of how probable the data were under each hypothesis, Harold Jeffreys's tool, met briefly in Part 15. Each probability is a marginal likelihood: the likelihood averaged over the hypothesis's own prior. So a Bayes factor compares predictions. A hypothesis that spreads its bets thinly over many possible results is penalized when the result is one it barely predicted.

Robert Kass and Adrian Raftery's 1995 review gave the scale most people quote, a tidier version of Jeffreys's own. A factor below three is barely worth mentioning; three to twenty is positive evidence; twenty to a hundred and fifty, strong; beyond that, very strong. Twice the log Bayes factor sits on the same scale as a likelihood-ratio statistic, which makes comparisons with Part 22 easy.

The workhorse case: is a normal mean zero, or drawn from a normal of spread tau? Under each hypothesis the sample mean is simply normal, with a larger variance under the alternative. So the Bayes factor is a ratio of two normal densities, in closed form. Take a z-statistic of two and a half from fifty observations: a p-value of point oh one two, conventionally significant. With tau equal to sigma, the Bayes factor for the null is point three three: the data favour the alternative by three to one. Positive evidence, on Kass and Raftery's scale, but far weaker than 'p below point oh five' sounds.

But that number depends on tau, the alternative's prior spread, and not weakly. Here is the Bayes factor for the same data as tau ranges over five orders of magnitude. Within this zero-centered normal-prior family, the smallest null Bayes factor is point one eight, at a tau of a third. Make the prior vague, tau of a thousand, and the Bayes factor is three hundred in favour of the null, from data with a p-value of point oh one. Maurice Bartlett pointed this out in 1957. For these fixed data, making this alternative arbitrarily vague increasingly favors the null, because it decides how thinly the alternative spreads its predictions.

In regular fixed-dimensional models, Laplace approximation gives maximized log likelihood minus half k log n, plus terms of order one that depend on the prior and model. BIC omits those terms; it is not an exact prior-free Bayes factor. Negative twice the leading expression is Schwarz's criterion. In this normal example its Bayes-factor approximation is point three one. The specified zero-centered normal prior with one observation's information gives point three three. The close agreement is example-specific.

With several models, Bayes factors give each a posterior probability. Then any quantity of interest can be averaged across models, weighted by those probabilities: Bayesian model averaging. It answers a real weakness of choosing one model and reporting it as if it had been known all along, a problem Part 28 takes up as inference after selection. But the weights inherit every Bayes factor's sensitivity to priors; Part 28's stacking chooses weights using predictive performance. Its component predictions can still depend on their priors.

The lessons. Bayes factors need genuine, proper priors on whatever is being tested; improper priors make them arbitrary. Report them with the prior used, and how they move as it changes. Ask whether a point null is even the question: an effect of exactly zero is rarely plausible, and an interval estimate may say more. For estimating sizes, use the posterior; for choosing models to predict with, Part 28's cross-validation.

Numbers: BF₀₁ 0.33, min 0.18, 311 at τ = 1,000; BIC 0.31

7Lindley's paradoxMaster's4 min

At Princeton in the 1980s, the Engineering Anomalies Research laboratory sat volunteers in front of an electronic random event generator and asked them to push its output towards ones, by intention alone. Over years of sessions the machine produced a hundred and four million, four hundred and ninety thousand binary events. The share of ones was point five zero zero one seven seven, against the point five that chance predicts.

Treating the recorded binary events as independent Bernoulli trials with a fixed probability, the excess is three point six one null standard errors. Its two-sided normal-approximation p-value is about point oh oh oh three. This tail area is not posterior odds or a causal test of intention. Compare the point null p equals a half with the specified uniform alternative. The data favor this null over that alternative by about twelve to one. Equal prior model odds then give a null posterior probability of point nine two, conditional on those models and sampling assumptions.

Why? With a hundred million trials, the likelihood is extremely narrow, a few ten-thousandths wide around point five zero zero one eight. The null puts all its probability at exactly a half, close by: near the likelihood's edge, but near it. The alternative spreads its probability over every proportion from zero to one, so only a couple of parts in ten thousand of it fall anywhere near the data. Judged as predictions, the null did far better: it said 'very close to a half', and that is what happened. The alternative said 'anything at all'.

Dennis Lindley's 1957 paper made the point in general. Hold the test result fixed at exactly p equals point oh five, and let the sample size grow, with a fixed normal prior under the alternative. The Bayes factor for the null grows like the square root of n, without bound. At ten observations a p of point oh five mildly favours the alternative; by a thousand it favours the null; by ten million, hundreds to one. A fixed significance level means very different evidence at different sample sizes.

A useful Sellke–Bayarri–Berger calibration has explicit conditions: a continuous uniform null p-value and alternatives whose p-value densities are mixtures of Beta distributions with shape xi and one, where xi lies between zero and one. In that class the null Bayes factor is at least minus e p log p for p below one over e. At point oh five that lower bound is point four one; equal prior model odds give a null posterior probability of at least twenty-nine percent. This is a calibration within a specified alternative class, not a universal conversion of any p-value into a probability that the null is true.

Neither answer is a mistake; they answer different questions. The p-value asks whether the data would be surprising if the null were exactly true. The Bayes factor asks which hypothesis predicted the data better, and depends on what the alternative predicted. For PEAR, both readings are compatible with a third story: a real but tiny bias, two parts in ten thousand, that could come from the equipment rather than the operators. Which is why the size of an effect, with its interval, should always be reported alongside any test.

Numbers: PEAR p 0.0003, BF₀₁ 11.9, P(H₀) 0.92; 0.58 → 464; SBB 0.29

8Occam's razor, built inMaster's3 min

Bayes factors carry a built-in Occam's razor, as David MacKay explained in 1992. Line up every data set that could possibly occur. Each model's predictions must sum to one over them. A simple model makes few, confident predictions: a tall narrow curve. In this illustration the flexible model's prior spreads its predictions more widely. Flexibility alone does not determine a model's prior predictive distribution. If the data land where the simple model predicted, it wins, even though the flexible one could fit them just as well, because it committed to them in advance. No penalty term was added: the razor is in the arithmetic of probability.

A concrete case: twenty noisy points from a cubic curve. The gold dashed line is the truth. Fit Bayesian polynomial regressions, with each coefficient given a standard normal prior. A straight line misses the bends. A cubic follows them. A degree-eight polynomial follows them too, and wiggles a little more between the points. Which degree do the data support?

The best-fitting log likelihood, in red, rises with every added degree, as it must. The log evidence, in green, the probability of the data averaged over each model's prior, behaves differently. It jumps at degree three, the truth, and peaks there. Beyond three it declines, but only gently: degree eight is about half a unit of log evidence lower. The razor is gentle here because the standard normal prior already keeps the extra coefficients small, so those models barely spread their predictions further. With a vaguer prior on the coefficients, the penalty would be steeper: Bartlett's effect again.

Evidence averages the likelihood over a proper prior. Dividing it by the maximum likelihood gives an exact factor no larger than one. For a concentrated unimodal posterior and a broad, locally flat prior, Laplace approximation interprets this as a posterior-to-prior volume ratio. A single width ratio is a heuristic in that setting; posterior standard deviation is not always smaller than prior standard deviation. Correlated parameters require a joint volume calculation. In regular fixed-dimensional models, widths of order one over root n yield the leading BIC penalty, with prior-dependent terms of order one omitted.

The evidence is also a tool for tuning. Maximizing it over hyperparameters, like the prior precision or the noise level, is empirical Bayes once more, called type two maximum likelihood; REML has a related fixed-design interpretation through error contrasts or integration over beta. Its improper-flat-prior constant cannot compare different fixed-effect spaces. Gaussian processes choose their length scales the same way, in Part 39. And because the evidence averages over the prior, it judges the prior as well as the model: the choice of prior is part of the prediction being judged. Tuning hyperparameters also leaves uncertainty that plug-in estimates do not propagate.

Numbers: the evidence peaks at degree 3

9DecisionsMaster's4 min

Statistics is often done to decide something. Write down the actions available, and a utility saying how good each action is if the truth is theta. The Bayesian rule is to choose the action with the highest expected utility under the posterior. Leonard Savage's 1954 theorem says preferences satisfying Savage's full axioms have an expected-utility representation with a subjective probability, which is one of the deepest arguments for being Bayesian. The posterior is an input to decisions, not the end of the analysis.

Even a point estimate is a decision. Under squared-error loss the best estimate is the posterior mean; under absolute error, the posterior median; under zero-one loss for a discrete parameter, a value with maximum posterior mass. For a continuous parameter, exact-match zero-one loss is one for every action and does not select a mode. And when overestimating costs differently from underestimating, as when a baker must not run out of bread, the best estimate is a quantile, the check loss of Part 23's quantile regression. 'Which estimate?' is answered by 'what does an error cost?'

Decision theory also links the two schools. A frequentist judges a rule by its risk, the expected loss over data for each fixed theta. Average that over a prior and you get the Bayes risk. The rule minimizing it is found case by case, by minimizing posterior expected loss for the data actually seen. Under appropriate regularity conditions, complete-class theorems relate admissible rules to Bayes rules and their limits. Admissible means no alternative has at most the risk everywhere and strictly less somewhere; this does not make every arbitrary Bayes rule admissible.

A ninth school is deciding whether to buy the coaching course. Its effect there, theta new, is a fresh draw from the population of schools, so the posterior predictive for it combines parameter uncertainty within the assumed exchangeable hierarchy: draw mu and tau from the posterior, then a new effect. Suppose the course is worth its cost if it raises scores by at least five points. The chance it does is two thirds. Measured in points above cost, the expected gain is about three. Under the stated linear utility, adopting maximizes expected gain. The model still assigns about a one-third chance of a negative gain; that is a posterior probability, not a demonstrated repeated-use rate.

What would it be worth to find out first? Deciding now, the expected gain is two point nine three points. If we could learn the school's true effect before deciding, we'd adopt only when it pays, and the expected gain would rise to five point one four. The difference, two point two zero points, is the expected value of perfect information. No study, however large, can be worth more than that, a ceiling on what to spend finding out, from Howard Raiffa and Robert Schlaifer's 1961 book.

Perfect information gives the outer limit on value in this specified utility model. A pilot with standard error ten is worth about one point two three points before subtracting its cost, a little over half the perfect-information value. Run it if its cost in the same utility units is less than that. We integrate over the pilot's possible results and the decision after each result. Direct normal-mixture integration replaces an earlier binned simulation estimate, avoiding its grouping and fitting error.

Numbers: P 0.66; gain 2.93; EVPI 2.20; EVSI 1.23

10CheckingPractice3 min

A posterior is only as good as its model, and Bayesian inference never says so on its own. Posterior predictive checking asks: if the fitted model were true, what data would it produce? Draw parameters from the posterior, then replicated data sets. Pick a feature of the data the model might get wrong. Compare the real data's value with the replicates': the posterior predictive p-value of Donald Rubin, and Andrew Gelman, Xiao-Li Meng and Hal Stern. A value near zero or one says the model doesn't reproduce that feature.

The eight schools, checked. Twenty thousand replicated sets of eight estimates from the fitted hierarchical model. The real largest estimate, school A's twenty-eight, is typical: about half the replicates have a larger maximum. The smallest, minus three, is a little high but unremarkable. And the spread of the eight is ordinary too. The model reproduces the features we'd worry about, including that one large effect at A.

In the sample of five hundred adults, forty-three percent reported no doctor visits. None of two thousand posterior-predictive Poisson replicates has as many zeros. That is zero simulated exceedances, not a mathematically zero tail probability. The discrepancy is strong evidence of a failure to reproduce this feature. A negative-binomial model reproduces the zero fraction. Its check now uses a proper joint numerical posterior for log mean and log shape, with stated normal priors, rather than substituting bootstrap parameter estimates for posterior draws. The sample variance is about five times its mean. Matching zeros is useful, but does not establish that every aspect of the negative-binomial model is correct.

One caution. These p-values use the data twice, once to fit and once to check, they generally are not uniform and often concentrate towards a half. Their behavior depends on the chosen discrepancy. A failed check, like the Poisson's, is real news. A passed check, like the schools', is weaker evidence than it looks. Held-out or cross-validated checks reduce data reuse. Their calibration still depends on the model, discrepancy and sampling scheme.

Prior predictive checks run the same idea before seeing data: simulate from the prior and the model, and ask whether the results are believable. A logistic regression with five standardized predictors. With 'vague' normal priors of standard deviation ten on every coefficient, the model predicts that eighty-three percent of people have a probability below one percent or above ninety-nine: it puts much prior mass on extreme conditional risks, without knowing which outcomes will occur. In fact symmetry gives a marginal prior-predictive probability of one half for each fixed predictor vector. Standard normal priors give about six percent extreme conditional risks in this standardized example. Which risk distribution is sensible depends on the application. Flat-looking priors on one scale can be strong beliefs on the scale that matters, chapter three's lesson, caught by simulation.

Numbers: p_B 0.48 / 0.17 / 0.78; zeros 43%: Poisson 0/2,000 exceedances, NB 0.47; 83% vs 6% extreme

11WorkflowPractice4 min

Andrew Gelman and colleagues set out a Bayesian workflow in 2020, the habits that turn a posterior into an analysis. First, write down a model of how the data arose. Check that the priors predict believable data. Fit the model to fake data simulated with known parameters, and see whether it recovers them. Only then fit the real data, and check that the computation worked. Check what the fitted model fails to reproduce. Then improve the model, compare the versions, and report the whole path, not just the last model standing.

Step three has a sharp form: simulation-based calibration. Draw a true parameter from the prior and fake data from the model. Run your posterior code on the fake data and take L draws. Record where the true value ranks among them. With a proper generative prior, a continuous parameter and independent correct posterior draws, prior-averaged ranks are uniform. Dependent draws or ties need separate treatment. Repeat thousands of times and look at the histogram.

Three versions of the posterior code for a normal mean with two observations, four thousand simulations each. The correct code gives a flat histogram. Code whose posterior variance is half what it should be gives a U: the truth too often falls outside all the draws, so its intervals would be too narrow. Code with a slip in the prior mean gives a slope: the posterior is systematically off-centre. Both bugs would produce plausible-looking posteriors on real data. These simulations expose the two bugs. A flat histogram can still miss other bugs; it is a necessary diagnostic, not a proof that all posterior calculations are correct.

With Markov chains, use multiple dispersed starts and modern rank-normalized R-hat; values below one point oh one are a useful screen, not proof of convergence. Check bulk and tail effective sample sizes and Monte Carlo errors for the quantities you report. Four hundred is a guideline, not universal adequacy. Hamiltonian divergences flag integration problems, but zero divergences do not establish that every mode was explored. Our numerical grid needs mesh and tail checks instead of chain diagnostics. Computation still requires verification.

The Board samples eight schools and ten pupils per school, repeating the complete experiment a thousand times. We estimate each finite school's mean score. No pooling covers about ninety-five percent. Complete pooling covers about thirty-two percent. Hierarchical numerical intervals cover about ninety-four percent and are narrower, but fall below the nominal level. The eight intervals within each experiment share a fitted model: the displayed Monte Carlo bands use variation across the thousand experiment-level coverage averages. Prior-average calibration is a theorem for a proper prior under its joint model, not a guarantee for our improper-hyperprior fit to the finite World.

Finally, sensitivity. Report the prior you used, and show what moves when you change it within reason. For the eight schools, the uniform and half-Cauchy priors on tau agree closely, as chapter three showed. When a conclusion flips between reasonable priors, the data simply haven't settled the question, and saying so is a finding, not a failure.

Numbers: SBC p 0.09 / 10⁻¹³⁷ / 10⁻²⁷⁰; Board 94.7 / 31.9 / 93.8%

12The argument, honestlyBachelor's4 min

A short history, as Sharon McGrayne tells it in The Theory That Would Not Die. For Bayes and Laplace, reasoning from data to causes was simply probability. In the 1920s Fisher dismissed inverse probability as founded upon an error, and Neyman and Pearson built a theory of tests and intervals that needed no prior. Harold Jeffreys kept the Bayesian approach alive, and Bruno de Finetti and Leonard Savage rebuilt it on coherence. For decades it remained a minority view, partly for a practical reason: high-dimensional nonconjugate integrals were difficult, though quadrature and analytic approximations existed. In 1990 Alan Gelfand and Adrian Smith showed that Gibbs sampling made many previously difficult models practical, subject to tractable updates and adequate mixing, Part 27's story, and Bayesian methods spread fast. Today both schools are in daily use, often by the same people.

Dutch-book arguments connect probabilistic coherence to avoiding sure-loss bets under specified betting assumptions. Cox obtains probability rules under additional regularity and richness axioms for plausibility. Consistency alone is not the full theorem. Savage similarly requires his full preference axioms for an expected-utility representation. Conditioning a specified joint probability model on new data gives Bayes's rule. These arguments do not select a unique prior or likelihood, or establish that a model is empirically correct.

A sharp difference between the schools, from Dennis Lindley and Lawrence Phillips. A coin gives nine heads and three tails. Is it biased towards heads? If the plan was to toss twelve times, the p-value is point oh seven three: not significant. If the plan was to toss until the third tail, the same tosses give point oh three three: significant. The p-value depends on what the experimenter would have done with data that didn't happen. The likelihood is p to the ninth times one minus p cubed either way, With the same fixed prior and an ignorable stopping or selection mechanism, proportional likelihoods give the same posterior. These two tail-area tests use different sampling plans; this example does not classify every frequentist or Bayesian procedure.

The objections are serious too. Whose prior? Two analysts with different priors reach different conclusions from the same data. Coherence guarantees consistency within one person's beliefs; it doesn't make them right. And a wrong model is updated, perfectly coherently, towards wrong answers: the Poisson model for doctor visits was coherent. The modern replies are this part's practical chapters: priors stated openly, sensitivity analysis, and model checking, which steps outside pure coherence.

A working compromise has grown up. Donald Rubin argued in 1984 for Bayesian answers whose behaviour in repeated use is checked by frequency calculations. George Box put it as Bayes for estimation within a model, frequentist reasoning for criticizing the model. Roderick Little calls it calibrated Bayes. It is what this series' Coverage Board does when it holds credible intervals to the standard of coverage.

Where the schools differ, side by side. To a frequentist, probability is long-run frequency and parameters are fixed; to a Bayesian, probability is a degree of belief and parameters are uncertain. The frequentist delivers a procedure with guarantees over repetitions; the Bayesian, a posterior for the data in hand. These are common emphases, not exclusive capabilities. Both traditions handle related parameters and decisions, both depend on modelling assumptions, and Bayesian procedures can also have frequentist guarantees. This series uses both, and the Board keeps both honest.

Numbers: 0.073 vs 0.033 under two stopping rules

13Bayesian nonparametrics, first lookPhD3 min

What if we don't want to assume the population of effects is normal, or any other shape? Thomas Ferguson's 1973 Dirichlet process is a prior on distributions themselves. A random distribution G is a Dirichlet process if, for every way of cutting the space into pieces, the probabilities G gives the pieces have a Dirichlet distribution. On average G is the base guess G nought, and alpha says how closely it follows that guess. For direct independent draws x from G it is conjugate: after those data, the posterior is another Dirichlet process, centred on a weighted average of the guess and the data's empirical distribution, chapter four's pseudo-data again, with alpha as the prior's sample size.

Jayaram Sethuraman's construction shows what such a G looks like. Take a stick of length one. Break off a random fraction, drawn from a beta of one and alpha, and keep it; break the remainder again, and again. Each piece is the probability of one point, drawn from G nought. With alpha of one, a few large pieces take almost everything; with alpha of five, the weight is spread over many. Either way, a draw from a Dirichlet process is a discrete distribution, a fact that makes it a natural prior for clusters.

Integrating G out gives the Chinese restaurant process, a story of Jim Pitman and Lester Dubins. Customers enter one at a time. Each new customer joins an occupied table with probability proportional to the number already seated there, or starts a new table with probability proportional to alpha. Thirty customers with alpha of two. Popular tables grow more popular: the rich get richer, and a few big clusters form with a tail of small ones.

How many tables? On average, the sum of alpha over alpha plus i, which grows like alpha times the log of the number of customers. With alpha of one, about ten tables for ten thousand customers; with alpha of five, about thirty-eight. A simulated restaurant of two hundred with alpha of two had twelve tables, against an expectation of about ten. The point for modelling: the number of clusters isn't fixed in advance. The model creates new clusters as the data demand them, slowly.

In practice the Dirichlet process sits inside mixture models, where each table is a cluster with its own parameters, with posterior uncertainty about the number of occupied components. The result also depends on alpha, the base distribution and the mixture kernel. Put one in place of the eight schools' normal population, and the effects could fall into groups instead. Gaussian processes, priors on whole functions, are the other workhorse, in Part 39. But in infinite dimensions, the basic finite-dimensional Bernstein–von Mises theorem need not apply. Consistency and functional limits require additional conditions; Part 53 takes up the theory.

Numbers: 5 tables of 30; 12 of 200 (9.8 expected)

Recap, problems, and the road aheadAll tracks3 min

Part twenty-six in fourteen lines. The eight schools' coaching effects were neither each school's own estimate nor one pooled number. Infinite exchangeability motivates a mixture representation; a normal population and its hyperprior remain additional choices. A checked wide-grid approximation to tau's posterior gave independent conditional draws, and school A's twenty-eight became ten, with an interval from minus two to about thirty-two. Jeffreys's rule, reference priors and weakly informative half-Cauchys replaced priors by habit. Conjugate priors act as pseudo-data. Bernstein–von Mises made posteriors and sampling distributions agree as data grew. Bayes factors compare predictions, and depend on the alternative's prior, as Bartlett warned. The PEAR data were significant at three in ten thousand, and favoured the null twelve to one. The evidence carries Occam's razor. Decisions maximize expected utility, and information has a price. Checks flagged the Poisson zero fraction; the negative binomial reproduced that chosen feature. Simulation-based calibration caught two bugs. Coherence is the Bayesian's case, and calibrated Bayes the working truce. And the Dirichlet process puts a prior on distributions themselves.

Where it comes back. Part 27 computes posteriors no grid can reach, with Markov chains and Hamiltonian dynamics, and returns to the eight schools in the shape of Neal's funnel. Part 28 chooses among models by cross-validation and information criteria. Part 32's horseshoe is a prior built for sparsity. Part 33 applies empirical Bayes to thousands of tests at once. Part 35 makes decisions about experiments. Part 39 puts Gaussian process priors on functions. Part 45 builds decision theory properly. And Part 53 proves Bernstein–von Mises and develops Bayesian nonparametrics.

Six problems, with full solutions in the README. The marginal posterior of tau; the invariance of Jeffreys's prior; the Poisson–gamma posterior mean as a weighted average; the normal Bayes factor and its limit; why the median minimizes absolute loss; and the expected number of tables in the Chinese restaurant. Pause here if you want to try them.

The books this part follows: Gelman and colleagues' Bayesian Data Analysis, McElreath's Statistical Rethinking, Robert's The Bayesian Choice, and McGrayne's history; with the papers from de Finetti to the Bayesian workflow.

Twenty-six parts of sixty-five. We can now build, fit on a grid, check and defend a Bayesian model. But a grid works in one dimension, not a hundred. In 1953, at Los Alamos, Nicholas Metropolis and colleagues computed the physics of hard disks with a random walk, and that walk became the engine of Bayesian statistics. Part 27: Bayesian computation.

Where it goes next. The posteriors that no grid can reach are computed in Part 27 (MCMC, HMC, Neal's funnel on these same schools); LOO, WAIC, BIC and stacking return in Part 28, shrinkage priors in Part 32, decision theory in Part 45, and Bernstein-von Mises is proved, with Bayesian nonparametrics, in Part 53.

Key results

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

The marginal posterior of tau\(\displaystyle p(\tau\mid y)\propto p(\tau)\,V_\mu^{1/2}\prod_j(\sigma_j^2+\tau^2)^{-1/2}\exp\Bigl\{-\frac{(y_j-\hat\mu)^2}{2(\sigma_j^2+\tau^2)}\Bigr\},\qquad\allowbreak \hat\mu=\frac{\sum_j w_jy_j}{\sum_j w_j},\ V_\mu=\frac{1}{\sum_j w_j},\ w_j=\frac{1}{\sigma_j^2+\tau^2}\)
Partial pooling\(\displaystyle \operatorname{E}(\theta_j\mid\mu,\tau,y)=\frac{\tau^2}{\sigma_j^2+\tau^2}\,y_j+\frac{\sigma_j^2}{\sigma_j^2+\tau^2}\,\mu\)
Jeffreys's prior\(\displaystyle p(\theta)\propto\sqrt{\det I(\theta)},\qquad\allowbreak \sqrt{I(\eta)}=\sqrt{I(\theta)}\,\Bigl|\frac{d\theta}{d\eta}\Bigr|\)
The normal point-null Bayes factor\(\displaystyle \mathrm{BF}_{01}=\sqrt{1+\frac{n\tau^2}{\sigma^2}}\;\exp\Bigl\{-\frac{z^2}{2}\,\frac{n\tau^2}{\sigma^2+n\tau^2}\Bigr\}\)
Sellke-Bayarri-Berger\(\displaystyle \mathrm{BF}_{01}\ \ge\ -e\,p\log p\qquad\allowbreak (p<1/e)\)
Tables in the Chinese restaurant\(\displaystyle \operatorname{E}K_n=\sum_{i=0}^{n-1}\frac{\alpha}{\alpha+i}\approx\alpha\log\Bigl(1+\frac{n}{\alpha}\Bigr)\)

Try it

Lab 26 · The eight schools: tau on a grid, then mu, then the effects

Compute the marginal posterior of tau for Rubin's eight schools with statkit's hier_normal, check it against direct numerical integration over mu, then draw from the joint posterior and read off the film's numbers.

Figure produced by Lab 26: The eight schools: tau on a grid, then mu, then the effects
Produced by the lab below, seed 0, in 0.2 s.
python -m videos.stats.labs 26 needs numpy, scipy, matplotlib · download lab26.py · source on GitHub
grid density against integration over mu       largest relative error 4.7e-06 at tau = 0, 2, 5, 10, 20
complete pooling (tau = 0)                     7.7 +/- 4.1   (film: 7.7 +/- 4.1)
tau: posterior median, 95% interval            5.2  [0.2, 20.8]   (film: 5.2 [0.2, 20.8])
school A (y = 28): posterior median, interval  10.2  [-2.2, 32.0]   (film: 10.2 [-2.2, 31.6])
school C (y = -3): posterior median            6.7   (film: 6.7)
P(theta_A > theta_C)                           0.678   (film: 0.68)
P(A is the best school)                        0.252   (film: 0.25; 1/8 a priori)

The posterior for tau peaks at zero but its median is 5: averaging over it pulls school A from 28 to about 10 without forcing all eight schools to one number.
The code (85 lines; it asserts its own result)
"""Lab 26: fit the eight schools' hierarchical model on a grid and check the grid against brute-force integration."""

import numpy as np
from scipy import integrate, stats

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

TITLE = "The eight schools: tau on a grid, then mu, then the effects"
GOAL = ("Compute the marginal posterior of tau for Rubin's eight schools with statkit's hier_normal, check it against "
        "direct numerical integration over mu, then draw from the joint posterior and read off the film's numbers.")
TASKS = [
    "Pass log_prior_tau=lambda t: -np.log1p((t / 25) ** 2) (a half-Cauchy with scale 25). How far does tau's median move?",
    "Keep only schools A, B and C. Where is tau's median now, and what does that say about a flat prior with three groups?",
    "Divide every standard error by 3. Watch the conditional means stop pooling and tau's posterior leave zero.",
]

TAU = np.r_[np.linspace(0, 0.1, 101), np.geomspace(0.101, 1e6, 10000)]  # the film's wide nonuniform grid


def quantile(h, q):
    cdf = integrate.cumulative_trapezoid(h.post_tau, h.tau, initial=0)
    return float(np.interp(q, cdf / cdf[-1], h.tau))


def run(seed=0):
    rng = np.random.default_rng(seed)
    names, y, s = museum.eight_schools()
    h = bayes.hier_normal(y, s, TAU)
    lab = labs.Lab()

    # Brute force: p(tau | y) is the integral over mu of prod_j N(y_j | mu, sigma_j^2 + tau^2), under flat priors.
    def brute(tau):
        f = lambda mu: np.exp(stats.norm.logpdf(y, mu, np.sqrt(s ** 2 + tau ** 2)).sum() + 30)
        return integrate.quad(f, -200, 200, points=[0, 8, 16], epsabs=0, epsrel=1e-10)[0]

    checks = np.array([0.0, 2.0, 5.0, 10.0, 20.0])
    kit = np.interp(checks, h.tau, h.post_tau)
    ref = np.array([brute(t) for t in checks])
    err = np.max(np.abs(kit / kit[0] - ref / ref[0]) / (ref / ref[0]))
    lab.row("grid density against integration over mu", f"largest relative error {err:.1e} at tau = 0, 2, 5, 10, 20")
    assert err < 1e-3, "the closed-form marginal agrees with brute-force integration"

    pooled, pooled_se = h.mu_hat[0], np.sqrt(h.v_mu[0])
    lab.row("complete pooling (tau = 0)", f"{pooled:.1f} +/- {pooled_se:.1f}   (film: 7.7 +/- 4.1)")
    assert abs(pooled - 7.7) < 0.05 and abs(pooled_se - 4.1) < 0.05

    med, lo, hi = (quantile(h, q) for q in (0.5, 0.025, 0.975))
    lab.row("tau: posterior median, 95% interval", f"{med:.1f}  [{lo:.1f}, {hi:.1f}]   (film: 5.2 [0.2, 20.8])")
    assert abs(med - 5.2) < 0.1 and abs(lo - 0.2) < 0.1 and abs(hi - 20.8) < 0.3
    assert h.post_tau.argmax() == 0, "the posterior mode of tau is on the boundary"

    d = bayes.hier_normal(y, s, TAU).draws(40000, rng)
    th = d["theta"]
    a_med, a_lo, a_hi = np.percentile(th[:, 0], [50, 2.5, 97.5])
    p_ac = np.mean(th[:, 0] > th[:, 2])
    p_best = np.mean(th.argmax(1) == 0)
    lab.row("school A (y = 28): posterior median, interval", f"{a_med:.1f}  [{a_lo:.1f}, {a_hi:.1f}]   (film: 10.2 [-2.2, 31.6])")
    lab.row("school C (y = -3): posterior median", f"{np.median(th[:, 2]):.1f}   (film: 6.7)")
    lab.row("P(theta_A > theta_C)", f"{p_ac:.3f}   (film: 0.68)")
    lab.row("P(A is the best school)", f"{p_best:.3f}   (film: 0.25; 1/8 a priori)")
    assert abs(a_med - 10.2) < 0.5 and abs(np.median(th[:, 2]) - 6.7) < 0.5
    assert abs(p_ac - 0.68) < 0.02 and abs(p_best - 0.25) < 0.02
    assert a_hi - a_lo < 2 * 1.96 * s[0], "partial pooling narrows A's interval"
    lab.note = ("The posterior for tau peaks at zero but its median is 5: averaging over it pulls school A from 28 "
                "to about 10 without forcing all eight schools to one number.")

    fig, ax = labs.figure(2, size=(11, 4.2))
    keep = h.tau <= 30
    mean, _ = h.cond_theta()
    for j, name in enumerate(names):
        ax[0].plot(h.tau[keep], mean[keep, j], color=labs.CYCLE[j], label=f"{name} (y = {y[j]:.0f})")
    ax[0].plot(h.tau[keep], h.mu_hat[keep], color=labs.MUTED, ls="--", label="mu")
    ax[0].axvline(med, color=labs.GREY, lw=0.8, ls=":")
    ax[0].set(title="Each school's estimate given tau", xlabel="tau (between-school sd)", ylabel="E(theta_j | tau, y)")
    ax[0].legend(ncol=3, fontsize=8, loc="upper left")
    ax[1].hist(d["tau"], bins=np.linspace(0, 30, 61), density=True, color=labs.BLUE, alpha=0.45,
               label="40,000 draws of tau")
    ax[1].plot(h.tau[keep], h.post_tau[keep], color=labs.GOLD, label="p(tau | y) on the grid")
    ax[1].axvline(med, color=labs.GREY, lw=0.8, ls=":", label=f"median {med:.1f}")
    ax[1].set(title="The posterior of tau: mode at 0, long tail", xlabel="tau", ylabel="density")
    ax[1].legend()
    lab.fig = fig
    return lab

Now change it

  1. Pass log_prior_tau=lambda t: -np.log1p((t / 25) ** 2) (a half-Cauchy with scale 25). How far does tau's median move?
  2. Keep only schools A, B and C. Where is tau's median now, and what does that say about a flat prior with three groups?
  3. Divide every standard error by 3. Watch the conditional means stop pooling and tau's posterior leave zero.

Problems, with solutions

Try each problem before opening its solution.

1. The marginal posterior of τ. Eight schools: show \(p(\tau \mid y) \propto p(\tau)\, V_\mu^{1/2} \prod_j (\sigma_j^2 + \tau^2)^{-1/2} \exp\{-(y_j - \hat\mu)^2/2(\sigma_j^2 + \tau^2)\}\).

Solution

Integrate the effects out first: y_j | μ, τ ~ N(μ, σ_j² + τ²) independently. So p(μ, τ | y) ∝ p(τ) Π_j (σ_j² + τ²)^{−1/2} exp{−(y_j − μ)²/2(σ_j² + τ²)}.

  • Complete the square in μ. With w_j = 1/(σ_j² + τ²), Σ w_j(y_j − μ)² = Σ w_j(y_j − μ̂)² + (Σ w_j)(μ − μ̂)², where μ̂ = Σ w_j y_j / Σ w_j.
  • Integrate μ out. The Gaussian integral gives (2π/Σ w_j)^{1/2} = (2π V_μ)^{1/2}.
  • The result. p(τ | y) ∝ p(τ) V_μ^{1/2} Π_j (σ_j² + τ²)^{−1/2} exp{−(y_j − μ̂)²/2(σ_j² + τ²)}.

2. Jeffreys's invariance. Show that Jeffreys's prior is invariant: if \(\eta = g(\theta)\), \(\sqrt{I(\eta)} = \sqrt{I(\theta)}\,|d\theta/d\eta|\).

Solution

With ℓ(θ) the log likelihood and θ = h(η), the score is dℓ/dη = (dℓ/dθ)(dθ/dη). Therefore I(η) = E{(dℓ/dη)²} = I(θ)(dθ/dη)², and √I(η) = √I(θ)|dθ/dη|. That is exactly the change-of-variables rule for a density: Jeffreys's prior for η is the transform of Jeffreys's prior for θ.

3. The Poisson–gamma posterior mean. Poisson–gamma: show the posterior mean is \(\tfrac{b}{b + n}\tfrac{a}{b} + \tfrac{n}{b + n}\bar x\).

Solution

The posterior is Gamma(a + Σx, b + n), whose mean is (a + nx̄)/(b + n) = {b/(b + n)}(a/b) + {n/(b + n)}x̄. That is a weighted average of the prior mean a/b and x̄, with the prior worth b observations.

4. The normal Bayes factor. Derive \(BF_{01}\) for \(\bar y \sim N(\mu, \sigma^2/n)\), \(H_0: \mu = 0\) vs \(\mu \sim N(0, \tau^2)\); its limit as \(\tau \to \infty\)?

Solution

Under H₀, ȳ ~ N(0, v) with v = σ²/n; under H₁, ȳ ~ N(0, v + τ²). So BF₀₁ = √{(v + τ²)/v} exp{−ȳ²/2v + ȳ²/2(v + τ²)} = √(1 + nτ²/σ²) exp{−(z²/2) nτ²/(σ² + nτ²)}, with z = ȳ/√v. As τ → ∞ the exponent tends to −z²/2 while the square root grows without bound, so BF₀₁ → ∞ for any fixed data: Bartlett's paradox.

5. The median and absolute loss. Show that the posterior median minimizes expected absolute loss.

Solution

E|a − θ| = ∫{θ<a} (a − θ)p(θ)dθ + ∫{θ>a} (θ − a)p(θ)dθ. Its derivative in a is P(θ < a) − P(θ > a), which is negative below the median and positive above it. So the expected loss is minimized at the posterior median.

6. The expected number of tables. CRP: show \(E K_n = \sum_{i=0}^{n-1} \alpha/(\alpha + i)\).

Solution

Customer i + 1 (i = 0, …, n − 1) opens a new table with probability α/(α + i), whatever happened before. K_n is the sum of these indicators, so E K_n = Σ_{i=0}^{n−1} α/(α + i). The sum behaves like ∫₀ⁿ α/(α + t) dt = α log(1 + n/α).

Notes and sources

Where it comes back

Idea Returns in
computing posteriors: MCMC, HMC, Neal's funnel 27
LOO, WAIC, BIC, stacking 28
shrinkage priors: the horseshoe 32
empirical Bayes for many tests 33
decisions in experiments 35
Gaussian processes 39
decision theory, admissibility 45
Bernstein–von Mises proved; Bayesian nonparametrics 53
the Coverage Board every part; 65

Glossary

  • Hierarchical model; hyperparameter; hyperprior: parameters drawn from a population whose parameters have their own prior.
  • Exchangeability; de Finetti's theorem: beliefs unchanged by relabelling; infinitely extendible exchangeable sequences admit mixtures of iid laws; a normal mixing population is an additional modelling choice.
  • Partial pooling; no pooling; complete pooling: estimates between the separate and the combined.
  • Jeffreys prior; reference prior; weakly informative prior; improper prior/posterior:
    • √det I(θ), invariant under reparametrization;
    • the prior maximizing expected information gain;
    • a prior that rules out only the absurd;
    • a non-normalizable density, acceptable only if the posterior normalizes.
  • Conjugate prior; Diaconis–Ylvisaker: a prior family closed under updating; linear posterior mean characterizations require regularity and boundary conditions.
  • Bernstein–von Mises theorem: posteriors become normal around the MLE with inverse-information variance.
  • Bayes factor; marginal likelihood (evidence); BIC; Bartlett's paradox; model averaging:
    • the ratio of evidences;
    • p(y | M);
    • −2ℓ̂ + k log n;
    • an arbitrarily diffuse specified alternative can favor the null for fixed data;
    • averaging over models by their posterior probabilities.
  • Lindley's paradox; Sellke–Bayarri–Berger bound: significant results that favour the null in large samples; BF₀₁ ≥ −e p log p for the specified continuous-p-value/Beta-mixture alternative class.
  • Occam factor; type II maximum likelihood: posterior width over prior width; maximizing the evidence over hyperparameters.
  • Expected utility; Bayes rule; Bayes risk; complete class; EVPI; EVSI; pre-posterior analysis:
    • the criterion for decisions and the rule it gives;
    • risk averaged over the prior;
    • admissible rules are (limits of) Bayes rules;
    • the value of perfect and of sample information;
    • deciding by simulating the study.
  • Posterior predictive check; p_B; prior predictive check: comparing data with replicates from the fitted (or prior) model.
  • Simulation-based calibration; R̂; effective sample size; divergence: necessary prior-averaged rank checks, which can miss some coding errors; MCMC diagnostics.
  • Dutch book; coherence; likelihood principle; calibrated Bayes:
    • sure-loss bets;
    • consistency with the probability rules;
    • inference depends on the data only through the likelihood;
    • Bayesian models judged by frequency properties.
  • Dirichlet process; stick-breaking; Chinese restaurant process: a prior on distributions; its atoms' weights; its partition of the data.

Sources

  • History.
    • D. Rubin, J. Educational Statistics 6 (1981); D. Alderman & D. Powers, American Educational Research J. 17 (1980).
    • R. Jahn, B. Dunne & R. Nelson, J. Scientific Exploration 1 (1987); W. Jefferys, J. Scientific Exploration 4 (1990). Some later sources print 52,263,471 successes.
    • S. B. McGrayne, The Theory That Would Not Die (2011).
  • Foundations.
    • B. de Finetti (1931, 1937); E. Hewitt & L. Savage, Trans. AMS 80 (1955); R. Cox, Am. J. Physics 14 (1946); L. Savage, The Foundations of Statistics (1954).
    • A. Birnbaum, JASA 57 (1962); D. Lindley & L. Phillips, The American Statistician 30 (1976); A. Wald (1950).
  • Priors.
    • H. Jeffreys, Proc. R. Soc. A 186 (1946) and Theory of Probability (1939); J. Bernardo, JRSS B 41 (1979); J. Berger & J. Bernardo (1992); A. Gelman, Bayesian Analysis 1 (2006).
    • P. Diaconis & D. Ylvisaker, Ann. Stat. 7 (1979); S. Dalal & W. Hall, JRSS B 45 (1983).
  • Asymptotics. L. Le Cam (1953); D. Freedman, Ann. Math. Stat. 34 (1963); P. Diaconis & D. Freedman, Ann. Stat. 14 (1986).
  • Testing and models.
    • R. Kass & A. Raftery, JASA 90 (1995); M. Bartlett, Biometrika 44 (1957); D. Lindley, Biometrika 44 (1957).
    • T. Sellke, M. J. Bayarri & J. Berger, The American Statistician 55 (2001); G. Schwarz, Ann. Stat. 6 (1978); R. Kass & L. Wasserman, JASA 90 (1995).
    • D. MacKay, Neural Computation 4 (1992); J. Hoeting, D. Madigan, A. Raftery & C. Volinsky, Stat. Sci. 14 (1999).
  • Decisions. H. Raiffa & R. Schlaifer, Applied Statistical Decision Theory (1961).
  • Checking and workflow.
    • D. Rubin, Ann. Stat. 12 (1984); A. Gelman, X.-L. Meng & H. Stern, Statistica Sinica 6 (1996).
    • G. Box, JRSS A 143 (1980); R. Little, The American Statistician 60 (2006).
    • S. Talts, M. Betancourt, D. Simpson, A. Vehtari & A. Gelman, arXiv:1804.06788 (2018); A. Gelman et al., Bayesian Workflow, arXiv:2011.01808 (2020).
    • A. Gelman & D. Rubin, Stat. Sci. 7 (1992); A. Vehtari et al., Bayesian Analysis 16 (2021).
  • Nonparametrics.
    • T. Ferguson, Ann. Stat. 1 (1973); J. Sethuraman, Statistica Sinica 4 (1994); C. Antoniak, Ann. Stat. 2 (1974).
    • M. Escobar & M. West, JASA 90 (1995); J. Pitman (2006).
  • Books.
    • A. Gelman, J. Carlin, H. Stern, D. Dunson, A. Vehtari & D. Rubin, Bayesian Data Analysis (3rd ed., 2013).
    • R. McElreath, Statistical Rethinking (2nd ed., 2020).
    • C. Robert, The Bayesian Choice (2nd ed., 2007).
About this partfrom its README

Part 26 of a sixty-five-part course in statistics, from a first course to a PhD (see the series plan and the syllabus), and the sixth part of Stage III, Master's. Part 15 laid down Bayes's machinery for one parameter with a prior chosen by hand. This part builds, fits, checks and defends Bayesian models with many parameters: hierarchies justified by exchangeability, priors chosen for reasons, tests and decisions, and the workflow that makes the result trustworthy.

It opens with Rubin's (1981) eight schools: SAT coaching experiments in eight high schools, with estimated effects 28, 8, −3, 7, −1, 1, 18, 12 and standard errors 9 to 18 points.

  • No pooling believes each estimate; complete pooling gives one effect, 7.7 ± 4.1. Cochran's Q = 4.7 on 7 df (p = 0.70) cannot reject equal effects.
  • Part 25's empirical Bayes estimates τ̂ = 0 and collapses to complete pooling.
  • The hierarchical model averages over τ instead.

From there the part covers:

  • The upgrade.
    • Part 15's assumptions; exchangeability (Part 5) and de Finetti's theorem as the justification for the hierarchy.
    • Conditional exchangeability with covariates; hierarchies in practice (MRP, genes, sport, meta-analysis).
  • Hierarchical models.
    • The three-level model and its factorization: p(τ | y) on a wide nonuniform grid checked against infinite-range integration, then μ | τ and θ | μ, τ, giving independent draws with a checked numerical approximation for τ and exact conditional normal draws.
    • The τ explorer. τ's posterior median is 5.2, 95% interval [0.2, 20.8], mode 0.
    • Posterior medians: A 10.2 [−2.2, 31.6], C 6.7, E 5.6; μ has mean 7.9.
    • P(θ_A > θ_C) = 0.68; P(A is the best school) = 0.25, against 1/8 a priori.
  • Priors.
    • Jeffreys's rule and its invariance; Beta(½, ½) on the p and logit scales.

    • Reference priors (Bernardo 1979; σ⁻¹ gives Student's t); weakly informative priors (Gelman 2006).

    • τ's posterior under four priors (medians):

      Prior All eight schools Schools A–C
      uniform on τ 5.2 23.0
      half-Cauchy(25) 4.8 10.9
      inv-gamma(1, 1) on τ² 1.2 1.2
      inv-gamma(.001, .001) 0.6 1.0
    • An improper posterior from a flat prior on log τ.

  • Conjugate families.
    • Exponential families; Diaconis–Ylvisaker linear posterior mean characterizations under regularity; priors as pseudo-data.
    • The World's doctor visits with a Gamma(4, 1) prior: posterior means 3.50, 1.83, 1.38, 2.83 and 2.15 for 1 to 1,000 adults (truth 2.24). The n = 100 interval [2.51, 3.17] misses, because the Poisson model is wrong.
    • The predictive is a negative binomial.
  • Bernstein–von Mises.
    • The statement and Laplace's argument.
    • A Poisson rate's posterior against N(λ̂, λ̂/n): full-support TV 0.084, 0.028 and 0.008 at n = 3, 30 and 300.
    • Exact coverage of the Jeffreys interval: 98.3% at n = 1, 95.2% at n = 100.
    • Failures: few groups and the eight schools' τ (mode on the boundary), Neyman–Scott, nonparametric priors.
  • Bayes factors.
    • Definition; the Kass–Raftery scale; the normal point null in closed form.
    • z = 2.5, n = 50 (p = 0.012): BF₀₁ = 0.33 with τ = σ, at best 0.18, and 311 at τ = 1,000 (Bartlett).
    • BIC 0.31 against the unit-information prior's 0.33.
    • Model averaging; cautions.
  • Lindley's paradox.
    • The PEAR random event generator: 52,263,470 of 104,490,000, z = 3.61, p = 0.0003. Jefferys's uniform-prior BF₀₁ is 11.9, so P(H₀ | y) = 0.92.
    • Why: the alternative spreads its predictions over [0, 1].
    • At fixed p = 0.05, BF₀₁ grows like √n: 0.58 at n = 10, 4.7 at 1,000, 464 at 10⁷.
    • Sellke–Bayarri–Berger: p = 0.05 leaves P(H₀ | y) ≥ 0.29.
  • Occam's razor.
    • MacKay's picture. The evidence for polynomial degree on 20 points from a cubic peaks at degree 3 (log evidence −6.47), while the maximized log likelihood keeps rising.
    • A gentle razor under N(0, 1) coefficient priors; the Occam factor and BIC; type II maximum likelihood.
  • Decisions.
    • Expected utility (Savage 1954); losses giving the mean, median, mode and quantiles.
    • Bayes risk and Wald's complete class theorem.
    • Should a ninth school adopt coaching? P(θ_new > 5) = 0.66 and the expected gain is 2.93 points.
    • EVPI 2.20; EVSI of a pilot with SE 10 is 1.23, by direct normal-mixture integration.
  • Checking.
    • Posterior predictive p-values. The eight schools pass on the maximum (0.48), minimum (0.17) and SD (0.78).
    • Of 500 adults, 43% had no visits. No Poisson replicate matches that zero fraction (0 of 2,000); a proper negative-binomial posterior check gives 0.47 for this feature.
    • Double use of the data.
    • Prior predictive checks for a logistic regression: N(0, 10²) priors put 83% of predictions below 1% or above 99%, against 6% for N(0, 1).
  • Workflow.
    • Gelman et al. (2020); computational checks (R̂, ESS, divergences).
    • Simulation-based calibration catches a halved variance (χ² p ≈ 10⁻¹³⁷) and a wrong prior mean (p ≈ 10⁻²⁷⁰). The correct code passes (p = 0.09).
    • Three Board rows; sensitivity analysis.
  • The argument.
    • History from Bayes to Gelfand & Smith; coherence (Dutch books, Cox, Savage).
    • The likelihood principle: 9 heads and 3 tails give p = 0.073 or 0.033 depending on the stopping rule, with the same posterior.
    • Objections; calibrated Bayes (Box, Rubin, Little); the schools side by side.
  • The Dirichlet process.
    • Ferguson (1973) and conjugacy; stick-breaking for α = 1 and 5.
    • The Chinese restaurant (30 customers, 5 tables). E K_n ≈ α log(1 + n/α): 9.8 and 38.5 tables at n = 10,000. A simulated restaurant of 200 with α = 2 has 12 tables (expected 9.8).
    • DP mixtures; Gaussian processes; Part 53.

Every number on screen is computed in compute.py:

  • the eight schools and the PEAR data are the Museum's;
  • doctor visits and schools are the World's;
  • the rest are seeded simulations.

Built in this part:

  • statkit.bayes II (explainer/stats/kit/bayes.py), checked in tests/test_stats_kit_bayes2.py:
    • the hierarchical normal model (hier_normal: τ's marginal posterior on a grid, conditional means and independent numerical draws);
    • bf01_normal; the Sellke–Bayarri–Berger bound;
    • Bayesian linear regression's evidence and posterior;
    • simulation-based calibration;
    • the Chinese restaurant process, its expected table count, and stick-breaking.
  • The τ explorer (TauExplorer in explainer/stats/viz.py): the schools' conditional means against τ above τ's posterior, with a moving cursor.
  • The Museum: EIGHT_SCHOOLS / eight_schools(), and the PEAR counts PEAR_N, PEAR_S.

The Coverage Board gains three rows:

Method Setting Independent sets / intervals Achieved Verdict
no pooling, ȳ_j ± 1.96σ_j 8 of the World's schools, 10 pupils each 1,000 / 8,000 94.7% kept
complete pooling 8 schools, 10 pupils each 1,000 / 8,000 31.9% broken
hierarchical, 95% credible 8 schools, 10 pupils each 1,000 / 8,000 93.8% broken

The hierarchical numerical intervals are 11% narrower than no pooling's. Monte Carlo error is estimated across 1,000 independent dataset-level coverage averages, retaining the dependence among eight intervals within a fit. Prior-average calibration requires a proper prior and its joint generative model; it is not guaranteed by the improper-flat-hyperprior fit used here or by the finite World's school population.

Chapter notes
# Chapter Numbers
0 The eight schools, 1981 pooled 7.7 ± 4.1; Q 4.7, p 0.70; τ̂_EB = 0
1 Upgrade: what Part 15 assumed exchangeability; de Finetti
2 Hierarchical models τ median 5.2 [0.2, 20.8]; A 10.2 [−2.2, 31.6]; P(A > C) 0.68; P(A best) 0.25
3 Priors medians 5.2 / 4.8 / 1.2 / 0.6 (eight), 23.0 / 10.9 / 1.2 / 1.0 (three)
4 Conjugate and exponential families 3.50 → 2.15; the n = 100 interval misses 2.24
5 Bernstein–von Mises TV 0.084 / 0.028 / 0.008; coverage 98.3% → 95.2%
6 Bayes factors BF₀₁ 0.33, min 0.18, 311 at τ = 1,000; BIC 0.31
7 Lindley's paradox PEAR p 0.0003, BF₀₁ 11.9, P(H₀) 0.92; 0.58 → 464; SBB 0.29
8 Occam's razor, built in the evidence peaks at degree 3
9 Decisions P 0.66; gain 2.93; EVPI 2.20; EVSI 1.23
10 Checking p_B 0.48 / 0.17 / 0.78; zeros 43%: Poisson 0/2,000 exceedances, NB 0.47; 83% vs 6% extreme
11 Workflow SBC p 0.09 / 10⁻¹³⁷ / 10⁻²⁷⁰; Board 94.7 / 31.9 / 93.8%
12 The argument, honestly 0.073 vs 0.033 under two stopping rules
13 Bayesian nonparametrics, first look 5 tables of 30; 12 of 200 (9.8 expected)
14 Outro —

Companion material in this repository

The syllabus's plan for this partfrom SYLLABUS.md, the plan of record
  1. Hook: the eight schools (Rubin 1981).
  2. Upgrade card (Part 15).
  3. Hierarchical models. Exchangeability and de Finetti (Part 5) as the justification; the eight schools' posterior over τ on a grid.
  4. Priors. Jeffreys (1946) from invariance; reference priors (Bernardo 1979); weakly informative (Gelman 2006); improper posteriors.
  5. Conjugate families and exponential families (Diaconis & Ylvisaker 1979).
  6. Bernstein–von Mises, stated and seen. Posterior and sampling distributions overlap (Part 53 proves it).
  7. Bayes factors (Jeffreys 1939; Kass & Raftery 1995).
  8. Lindley's paradox (1957). Computed; the Sellke–Bayarri–Berger bound.
  9. Occam's razor, built in. The evidence (MacKay 1992).
  10. Decisions. Expected utility; value of information.
  11. Checking. Posterior predictive checks (Rubin 1984; Gelman, Meng & Stern 1996); prior predictive checks.
  12. Workflow (Gelman et al. 2020).
  13. The argument, honestly. History from Laplace to MCMC (McGrayne 2011); Cox and coherence; where the schools differ.
  14. Bayesian nonparametrics, first look. The Dirichlet process and the Chinese restaurant (Part 53).
  15. Outro.

Built: statkit.bayes (II). Data: the eight schools.

Build the film

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

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

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