Bayesian Statistics
A Bayesian model is a joint distribution over parameters and data, ; everything else is conditioning. The course is a march of inference algorithms, deployed in order as exactness fails: conjugate exact → MAP + Laplace → MCMC (M–H, Gibbs, HMC) → variational. Each step trades exactness for reach, and the whole modern field lives at the last two stops — MCMC and VI are the load-bearing sections of this guide. The workflow wrapper is Box’s loop: build → infer → criticize → revise. Prerequisites cashed in: conjugacy and exp families (track 1 §2), posterior basics and MLE/MAP (track 3 §7), and the entire MCMC substrate — stationarity, detailed balance, ergodic theorem (track 5 §6).
1. The frame: posteriors and the proportionality workflow
- Bayes’ rule is the product and sum rules applied to the joint:
Numerator: likelihood × prior — the model you wrote down. Denominator: the marginal likelihood / evidence — an integral over all of parameter space, and the villain of the entire course. Every algorithm below is a strategy for never computing it.
- The #1 working skill — recognize-the-shape: the denominator is constant in , so
Multiply, simplify the -dependence, match the shape to a known family; the normalizer comes free because that family is already normalized. You almost never integrate.
- The Gaussian instance of recognize-the-shape — complete the square. Any log-density that is quadratic in is a Gaussian, and you can read its parameters off the coefficients:
(precision) and are the Gaussian’s natural parameters. Worked instance (factor analysis posterior — prior , likelihood ): multiply, collect the quadratic and linear terms in :
This one template computes every Gaussian conditional in the field — Gibbs conditionals, Kalman updates, GP posteriors.
- Improper priors (e.g. , the zero-pseudo-data limit of Normal-Inverse-Gamma): don’t integrate to 1, often still give a proper posterior — legal if you check. The cost arrives in §4: the evidence becomes undefined.
- Sequential = batch: today’s posterior is tomorrow’s prior; same answer as processing everything at once.
- Box’s loop: build the joint → infer → criticize (predictive checks, §9) → revise. Modeling is iteration, not specification.
Implications
- The log-joint is the universal interface: MAP optimizers, M–H ratios, HMC dynamics, and the ELBO all consume only it (and its gradient). This is why probabilistic programming languages work — you write the joint, the inference engine does the rest.
- Recognize-the-shape is why conjugacy matters at all: it converts integration (hard, global) into pattern matching (easy, local).
- Complete-the-square is the reason “everything Gaussian is tractable” — linear-Gaussian models (regression, Kalman, factor analysis) stay closed under conditioning.
Core competency set
- Write Bayes’ rule from the joint; name what makes the denominator hard.
- Execute recognize-the-shape on a conjugate pair, and complete-the-square on a Gaussian product, reading off and .
- Define improper priors, when they’re legal, and what they cost.
2. Conjugate exact inference and the hierarchical move
The exp-family machine from track 1 §2, driven in production:
- Likelihood of iid points: ; conjugate prior . Multiplying preserves the shape — updating is pseudo-data arithmetic:
= pseudo-observations, = pseudo-count. Every conjugate-table row is this template.
- The Gaussian with both parameters unknown takes the Normal-Inverse-Gamma (≡ Normal-Inv-χ²) prior, ; the limit recovers .
- Numbers (track 3’s formula, run once): known, prior , , . Precisions , :
The prior, worth observations, is outvoted 16-to-1.
The hierarchical move — eight schools, in full. Eight schools each report a treatment-effect estimate with standard error . Three models:
- No pooling: each school its own , flat priors — estimates stay at , noisy schools stay noisy.
- Complete pooling: one shared — as if one giant school; school identity erased.
- Partial pooling (hierarchy): school effects drawn from a shared population:
The population level is itself learned from the data. Conditional on , each school’s posterior mean is a precision-weighted compromise (complete-the-square again):
- Read the limits: ⟹ no pooling (the population prior is vague); ⟹ complete pooling (all schools forced to ). The data chooses — the data decides how much to pool.
- Numbers — the famous school A: , ; suppose the population posterior centers at , . Precisions: , :
The headline effect of 28 shrinks to ~11 — most of it was noise, and the hierarchy knew because the other seven schools said effects that large don’t happen. Noisy groups borrow strength from the ensemble.
Implications
- Partial pooling is the Bayesian answer to regression-to-the-mean (track 4 §1) as a modeling device: shrinkage isn’t a correction you apply, it falls out of the joint.
- Hierarchies are conjugacy stacked: each level conditions on the one above; Gibbs sampling (§6) walks the levels.
- The same structure powers multilevel regression, random effects (track 4’s mixed models), and empirical Bayes; “how much do groups share?” becomes a parameter () instead of a modeling fiat.
Core competency set
- Run the pseudo-data template generically and for Normal-Inverse-Gamma; compute the Normal–Normal numeric.
- Write the eight-schools hierarchy, derive the precision-weighted shrinkage, read both limits, and run the school-A numbers.
- Explain “borrowing strength” in one sentence.
3. Bayesian linear regression — and ridge unmasked
- Model: ; conjugate prior .
- Posterior by recognize-the-shape — same family, sufficient statistics absorbed:
Pseudo-data again: the prior contributes fake ‘s and fake ‘s.
- Uninformative limit (): MAP = MLE = OLS — track 4 rung 2, met from the other side.
- Ridge unmasked. Set , :
Ridge is the posterior mode under a spherical Gaussian prior — the penalty is the prior, is a prior precision. Track 4 §8’s “targeted variance repair” and “shrink toward the prior mean” are one operation in two vocabularies. Lasso = MAP under a Laplace (double-exponential) prior — its sharp peak at zero is what produces exact zeros.
- Posterior predictive — integrate the parameters out, never plug in:
Here analytic: Gaussian × Inv-χ² ⟹ Student-t — track 1 §8’s “normal with a noisy scale,” rediscovered as parameter uncertainty. Credible bands flare outside the data; in general estimate by Monte Carlo (sample parameters, average conditional densities).
Implications
- Every regularizer is a prior. The penalty-as-prior dictionary (ridge↔Gaussian, lasso↔Laplace) means regularization tuning is prior elicitation — and exposes what assumptions a penalty silently makes.
- Prediction with integrated-out parameters is systematically better-calibrated than plug-in: the t’s heavy tails are honesty about not knowing .
- Frequentist answers reappear as limits (flat priors, modes) — the frameworks disagree at small and informative priors, exactly where the prior has something to say.
Core competency set
- Derive the posterior updates and narrate them as pseudo-data.
- Reproduce ridge-as-MAP in two lines; state the lasso analogue.
- Explain why the predictive is a t and what integrating out buys over plugging in.
4. The marginal likelihood: evidence and Occam
The villain rehabilitated as a model-comparison tool:
- — the probability the prior-averaged model assigns the data. Not best-case fit; expected fit, before seeing the data.
- The Z-ratio trick, displayed once (works in any conjugate family). Write the unnormalized posterior and multiply-divide by its known normalizer :
( collects likelihood constants like .) Evidence = ratio of posterior to prior normalizing constants — the same multiply-by-one move that proves conjugate predictives.
- Automatic Occam’s razor. In polynomial-degree selection the evidence factors into a fight:
- fit: (residual error) falls with degree ⟹ pushes evidence up;
- complexity: falls as dimension grows — more parameters spread the prior’s mass thinner over data space, so any particular dataset receives less of it. The maximum sits at “complex enough.” No penalty was added by hand — it lives in the integral.
- Caveats: undefined for improper priors (infinitely spread prior gives every dataset measure zero), and genuinely sensitive to prior choices.
Implications
- Ratios of evidences are Bayes factors — the Bayesian replacement for hypothesis tests; Occam is built in rather than bolted on (contrast /AIC’s additive corrections, track 4 §7).
- Laplace-approximating this integral (§5) and keeping the terms yields BIC — the cheap shadow of the evidence.
- The prior-sensitivity caveat is what pushes practice toward the predictive currency (§9) when priors are diffuse.
Core competency set
- Define the evidence as a prior expectation; run the Z-ratio manipulation.
- Tell the Occam story with both factors named.
- State the caveats and what each pushes you toward.
5. GLMs, MAP, and the Laplace approximation
First failure of conjugacy — non-Gaussian observations:
- GLM recipe: observations exp-family, , with . The mean is (track 1’s identity), so the canonical mean function is — logistic for Bernoulli, for Poisson. The link isn’t a modeling choice; it’s the family’s own gradient.
- Logistic regression + Gaussian prior : the posterior has no closed form (the denominators never collapse). Retreat to the mode:
— an error signal against the covariates, minus the prior’s pull to zero. The Hessian is negative definite (, plus the prior), so the log-posterior is concave: Newton/IRLS finds the unique MAP.
- Laplace approximation — promote the mode to a distribution. Second-order Taylor at (linear term dead there):
Picture to hold: a skewed posterior bump with a symmetric Gaussian snugged to its summit — exact at the top, wrong in the tails.
- Bernstein–von Mises: as the posterior is asymptotically normal, centered at the MLE with variance — track 3 §7’s large-sample posterior with its proper name; the log-likelihood Hessian converges to Fisher information, one observation’s curvature at a time.
Implications
- Laplace gives cheap uncertainty for anything you can MAP-train — including neural networks (Laplace on the last layer is a modern serving trick). Cost: one Hessian.
- BvM is the peace treaty: with enough data, Bayesian and frequentist uncertainty coincide. All the disagreement lives at small — which is where you actually need the prior.
- Concavity of exp-family GLM posteriors is why logistic/Poisson regression are reliable workhorses: one optimum, no restarts.
Core competency set
- Build a GLM and explain why the canonical link is .
- Write the logistic MAP gradient; argue concavity.
- Derive Laplace from the Taylor expansion; state BvM and its track-3 identity.
6. MCMC — sampling the posterior
When no approximation is trusted, sample. Track 5 §6 built the theory; here it earns its living. This and §8 are the two sections to over-learn.
Why Monte Carlo at all. Everything you want is an expectation — posterior means, event probabilities, predictives are all . Quadrature’s cost grows exponentially in dimension; the MC estimator is unbiased with standard error independent of dimension. High dimensions are exactly where Bayes lives, so MC wins there.
The obstruction and the escape. Sampling directly is as hard as computing . But ratios of posteriors need only the joint:
So build a Markov chain that only ever consults ratios — then the evidence never appears.
Metropolis–Hastings, derived from detailed balance. We want a transition kernel with the posterior as its stationary distribution; detailed balance (track 5 §5) suffices. Write the kernel as propose-then-accept, , and impose DBC:
Only the ratio of acceptance probabilities is pinned down — so make them as large as possible by setting the bigger one to 1:
- Symmetric ⟹ accept uphill always, downhill with probability = the density ratio: stochastic hill climbing that provably samples the right thing. Any that can reach everywhere gives an ergodic chain; the ergodic theorem (track 5) then makes time averages converge to posterior expectations.
- Designing is the whole game: too-small steps ⟹ high acceptance but snail mixing; too-big ⟹ constant rejection. (Optimal random-walk acceptance ≈ 0.23 in high dimension — you want rejections.)
Gibbs sampling = M–H whose proposal is the full conditional, , changing one block at a time. The acceptance ratio cancels identically — display it once, with fixed:
- Acceptance probability 1, always. Cycle through coordinates/blocks for ergodicity. Gibbs shines in conditionally conjugate models — each conditional is a known family (recognize-the-shape / complete-the-square supply them).
- Where Gibbs dies: correlated coordinates. The picture to hold: axis-parallel zigzag steps trapped inside a long tilted ellipse — each conditional slice is tiny, so the chain inches along the ridge. Note it’s the correlation, not the elongation: an axis-aligned ellipse samples perfectly.
- Fixes: reparametrize to decorrelate; block correlated coordinates and sample them jointly; collapse — integrate a parameter out analytically (exp-family conjugacy makes this possible) and run the chain on the lower-dimensional marginal. Collapsing trades parallelism for mixing.
Diagnostics — the estimator is consistent but correlated and transiently biased.
- Trace plots: flat stretches = rejections; parameters mix at different rates. Burn-in: discard early samples still under the initialization’s influence (bias decays faster than variance).
- Autocorrelation discounts your sample size. Effective sample size:
- Benchmark it on AR(1), , where the whole computation is a geometric series: , so
Numbers: ⟹ — a 100k chain is worth ~5k independent draws. This number is why the gradient methods below exist.
Use the gradient. Autodiff makes essentially free, and it changes the game:
- MALA: drift the proposal uphill, . Asymmetric, so both directions’ ‘s enter the acceptance ratio. Cuts the steps-per-independent-sample from toward .
- HMC — the big idea: stop diffusing, start coasting. Augment with a momentum variable and define a physical system:
The joint factorizes — sample momenta fresh, simulate the dynamics, keep only , and the -marginal is exactly the posterior. The dynamics follow Hamilton’s equations (, ): a frictionless puck coasting over the negative log posterior landscape — it converts potential to kinetic energy and back, traveling far along level sets instead of dithering. Energy is conserved ⟹ proposals from exact dynamics would be accepted with probability 1.
- Discretization must respect the geometry. The leapfrog integrator alternates half-steps:
Each update is a **shear** (one variable moves, by an amount depending only on the *other*) — determinant 1, volume preserved — which is exactly what forward Euler lacks (its trajectories spiral out). The small leftover energy error is repaired by one M–H accept/reject.
- NUTS auto-tunes the trajectory length: simulate until the path starts doubling back on itself (the U-turn), avoiding both wasted laps and premature stops. NUTS-on-HMC is the default engine of Stan and PyMC — when someone “fits a Bayesian model” today, this is usually what runs.
- The practical art: mix and match — Gibbs the conditionally conjugate coordinates, HMC the rest; collapse what you can.
Implications
- MCMC’s contract: asymptotically exact — the gold standard against which approximations (§8) are judged; its price is correlation (ESS) and per-step cost.
- The gradient era reorganized the field: HMC/NUTS made “write the joint, autodiff it, sample” a button — modeling effort shifted from designing samplers to designing models (Box’s loop sped up).
- Diagnostics are not optional bureaucracy: an unconverged chain looks like a converged one locally. Trace + ESS (+ multi-chain in practice) are the seatbelt.
Core competency set
- Explain dimension-free MC error and the ratio escape from the evidence.
- Derive M–H acceptance from detailed balance; display the Gibbs cancellation; draw the correlated-ellipse failure and name the three fixes.
- Run the AR(1) ESS derivation and the number.
- Tell the HMC story: augmentation, factorized joint, coasting, energy conservation, leapfrog-as-shears, NUTS.
7. Latent variable models: mixtures and mixed membership
- Bayesian mixture model — the generic clustering joint: ; components conjugate prior; assignments ; data . The joint factors — exactly what Gibbs wants.
- The Gibbs sweep, every conditional in closed form:
- Degenerate limits locate the classics: MAP coordinate ascent on with shared spherical Gaussians ⟹ k-means; collapses conditionals to point estimates ⟹ EM-like behavior. Soft assignment is the general case; hard assignment is its zero-temperature limit.
- Mixed membership / LDA: grouped data — each document mixes the same topics with its own proportions. Sharing at the corpus level, variability at the document level. The posterior’s tension — explain each document with few topics vs each topic with few words — is what makes topics sharp. Exchangeability (de Finetti: any exchangeable joint is a mixture of iid models) is the license for bag-of-words.
Implications
- The mixture Gibbs sweep is the template for all conditionally conjugate latent-variable models — HMMs (transitions linked ‘s), topic models, factor models all reuse it with one conditional swapped.
- Responsibilities are the bridge to EM (§8): E-step = expected responsibilities, M-step = their weighted conjugate updates.
Core competency set
- Write the mixture joint and all three Gibbs conditionals from memory.
- Place k-means as a degenerate limit; narrate the LDA tension and the de Finetti license.
8. Variational inference — optimization replaces sampling
MCMC is asymptotically exact but slow to decorrelate; VI trades bias for variance: pick a tractable family , then optimize to make close to the posterior. You give up exactness-in-the-limit and get back speed, determinism, and SGD-scale data handling. Modern ML’s generative stack lives here.
- Closeness = KL divergence, and the direction is a real decision:
Nonnegative, zero iff equal, an expectation under — which we chose to be easy. The direction makes mode-seeking / zero-forcing: where , any -mass costs infinitely, so retreats inside one mode and underestimates spread. (The reverse KL, , is mass-covering — but you can’t take expectations under the posterior you don’t have.) Picture to hold: a bimodal posterior with locked snugly onto one mode, ignoring the other entirely.
- The ELBO derivation — removing the unknown posterior from the objective. Expand inside the KL:
The evidence is constant in : maximizing the ELBO ⟺ minimizing the KL, and the ELBO needs only the joint (the universal interface again). Picture to hold: a fixed bar of height split into ELBO below, KL above — pushing the ELBO up squeezes the KL out. And since , the ELBO really is a lower bound on the evidence — usable for model comparison too.
- Two readings of the same objective, each guarding against a failure:
- Mean field: — all posterior dependence discarded by fiat. What’s lost: correlations, and (via zero-forcing) variances come out too small. What’s gained: every expectation factorizes.
- CAVI — coordinate ascent on the ELBO. Hold fixed; as a function of the ELBO is , maximized by
CAVI is Gibbs with expectations in place of samples: same conditional structure, same conjugate algebra, but a deterministic sweep that monotonically increases the ELBO. (For LDA: same updates as the Gibbs sampler, expectations swapped in.)
- EM placed exactly. With point-estimated parameters and latent variables : the ELBO satisfies
so the bound is tight exactly when = the true posterior over latents — that’s the E-step; the M-step maximizes over . EM = alternating exact-fit of and parameter maximization. Variational EM = EM where the E-step posterior is itself out of reach and must be approximated within a family — opening the approximation gap (best-in-family KL > 0).
- Stochastic / black-box VI — what makes VI scale. Optimize the ELBO by SGD; the obstacle is (the parameter sits inside the sampling distribution). The reparameterization trick moves it:
Sample ‘s, differentiate through — a Monte Carlo gradient with low variance, requiring , the density, and differentiable. (Discrete latents need the score-function/REINFORCE estimator instead — unbiased but high-variance.)
- VAEs — amortize. Instead of optimizing a separate per data point, learn an inference network (the encoder) jointly with the generative model (the decoder), training both by reparameterized SGD on the ELBO. Two gaps now stack: the approximation gap (family can’t reach the posterior) + the amortization gap (the network doesn’t even find the family’s best member). Sanity anchor: for linear factor analysis the optimal encoder is exactly the analytic posterior map from §1 — a pseudoinverse-like linear function; the network’s job is to learn the decoder’s inverse.
Implications
- The modern division of labor: MCMC when you need fidelity (science, small-to-medium models, calibrated uncertainty), VI when you need scale or speed (embedded in larger systems, millions of data points, deep generative models). The bias–variance trade is the organizing axis of contemporary inference.
- Standing warning: mean-field VI underestimates posterior variance — never read calibrated uncertainty off a vanilla mean-field fit.
- The ELBO is the loss function of deep generative modeling: VAEs and their descendants are this section with neural networks for — diffusion models train on a (hierarchical) ELBO too.
- CAVI ⟷ Gibbs is a two-way street: a model you can Gibbs you can CAVI, and vice versa — derive one, get the other’s structure free.
Core competency set
- Derive the ELBO from the KL; state evidence = ELBO + KL with the bar picture; explain why ELBO-maximization needs only the joint.
- Explain mode-seeking from the KL direction and its underdispersion consequence, with the bimodal picture.
- Write the CAVI update and its Gibbs correspondence; place EM, variational EM, and VAEs with their two gaps.
- Derive the reparameterization trick and say what breaks without it.
9. Model criticism — closing Box’s loop
- Posterior predictive checks: simulate replicate datasets from the posterior predictive; compare a test statistic between replicates and observed data; the tail fraction is a posterior predictive p-value. Internal coherence: “does my fitted model generate data that looks like mine?”
- Predictive scoring (the external currency): log predictive density on held-out data, — integrate over the posterior, never plug in. CV is the standard; WAIC/DIC approximate it from the posterior itself (AIC matches only when MAP ≈ MLE).
- Sensitivity analysis: perturb priors and structure, watch the conclusions; extrapolations are fragile, interpolations robust.
- The two currencies divide cleanly: evidence compares models as priors (§4); prediction compares them as forecasters. Diffuse or improper priors ⟹ only the second is available.
Core competency set
- Run a PPC in words: statistic, replicates, tail probability.
- Contrast evidence vs predictive scoring and when each is the right currency.
10. Memorize cold
The instant-recall layer — these should cost nothing to produce; the fluency flashcards drill exactly this list.
- Bayes from the joint; posterior ∝ likelihood × prior; recognize-the-shape workflow.
- Complete-the-square: ; factor-analysis instance , .
- Conjugate template: , ; Normal-Inverse-Gamma for ; improper limit .
- Eight schools: ; shrinkage ; complete pooling, none.
- Regression updates , ; ridge = MAP under Gaussian prior, lasso = MAP under Laplace prior.
- Predictive: integrate parameters out; Gaussian × Inv-χ² ⟹ Student-t.
- Evidence ; Occam = fit ↑ vs prior-mass-spreading ↓; Bayes factors; undefined for improper priors; BIC = Laplace’s skeleton.
- Canonical link = ; logistic MAP gradient ; concave.
- Laplace: ; Bernstein–von Mises → .
- M–H from DBC: ; ratios kill the evidence; ~0.23 optimal RW acceptance.
- Gibbs = full-conditional proposal ⟹ acceptance 1 (the cancellation); fails on correlated coordinates; fixes: reparametrize / block / collapse.
- ESS ; AR(1): ; .
- HMC: , ; joint factorizes so the -marginal is the posterior; leapfrog = volume-preserving shears; energy conservation ⟹ near-1 acceptance; NUTS stops at the U-turn.
- Mixture Gibbs: responsibilities / conjugate / ; k-means = degenerate limit.
- ; ELBO .
- KL is mode-seeking/zero-forcing ⟹ mean-field VI underestimates variance.
- CAVI: — Gibbs with expectations.
- EM: bound tight ⟺ = latent posterior; variational EM adds the approximation gap; VAEs add the amortization gap.
- Reparameterization: .
- Named moves: recognize-the-shape; complete-the-square; pseudo-data update; integrate-out; multiply-by-; ratios-kill-the-evidence; trade-bias-for-variance; augment-then-marginalize (HMC’s momentum).