MVA · Course notes

Bayesian Machine Learning

M2 MVA · Semester 2 · Learning · 5 ECTS

Contents

Introduction and overview

Module Bayesian Machine Learning
Official title Bayesian machine learning
Instructors R. BARDENET, J. ARBEL, G. VICTORINO CARDOSO (master-mva.com, 2026–2027)
Period Semester 2 · period 2 (04/01/2027 – 02/04/2027)
Credits and volume 5 ECTS · 28 h (lectures 16 h, labs 12 h) per the Université Paris-Saclay programme table
Label Learning · domains on master-mva.com: Machine Learning
Language English: all classes and material are in English; the final report may be written in French or English (master-mva.com)
Assessment In groups, the study of a research paper chosen from a list, with a small report and a short oral presentation to the class, in a “student seminar” during the last lecture; students are encouraged to find a weak point or limitation of the paper and push in that direction (master-mva.com); Université Paris-Saclay: “Evaluation Continue non Intégrale” (partial continuous assessment)
Prerequisites An undergraduate course in probability; recommended: the semester-1 course of P. Latouche and N. Chopin on “Probabilistic graphical models” or that of S. Allassonière on “Computational statistics”; a basic knowledge of Python and R for the practicals (master-mva.com)
Note on sources master-mva.com announces 8 × 3 h of lectures and practicals plus 4 h of student seminars for the evaluation, 28 h in all, the total of the Université Paris-Saclay table; the course is open to external auditors, without grade, assessment or certificate

Audience: a student with a good M1 in mathematics or computer science who knows maximum likelihood and has trained a classifier, and who wants models that say how much they do not know, and decisions that use it.

Empirical first: fit polynomials of degree 0 to 9 to 20 noisy points of a sine curve. The training error falls from 0.73 to 0.17 as the degree grows, so it cannot choose the degree. The Bayesian marginal likelihood of the same models, computed in closed form from the training data alone, peaks at degree 3 (ch. 3).

Five neural networks trained on 60 points agree to within 0.02 inside the data and spread to 0.24 far outside it, where all five miss the truth by 3 to 3.5 (ch. 8). Averaging models helps, but it is not yet a calibrated posterior.

This course treats Bayesian inference as a way of deciding under uncertainty. Choose the loss that matters, put a probability distribution on everything unknown, condition on the data, and act to minimize the posterior expected loss. The course then asks where priors come from, how to compute posteriors at the scale of machine learning, how to put priors on infinite-dimensional objects, and what survives of all this in deep learning.

It continues Introduction to Probabilistic Graphical Models and Deep Generative Models and Computational Statistics, and shares tools with Kernel Methods for Machine Learning and Learning Physical Phenomena: Metamodelling and Uncertainty Quantification.

What you will be able to do

Official objectives and syllabus (2026–2027)

The course description on master-mva.com states that by the end of the course students should have a high-level view of the main approaches to making decisions under uncertainty, and be able to detect when being Bayesian helps and why. They should be able to design and run a Bayesian machine learning pipeline for standard supervised or unsupervised learning.

They should also have a global view of the current limitations of Bayesian approaches and of the research landscape, and be able to understand the abstract of most Bayesian machine learning papers.

The description lists six themes. It announces 8 × 3 hours of lectures and practical sessions, in Python and R, and 4 hours of student seminars for the evaluation. The Université Paris-Saclay course detail gives the volume (16 h of lectures, 12 h of labs) and the type of assessment, with no programme of its own.

Official topic Course section
Decision theory ch. 1: Definitions 1.1–1.2, Theorem 1.3 (Bayes rules), Proposition 1.4 (Bayes estimators), Propositions 1.7–1.8 and Theorem 1.10 (admissibility, minimaxity, complete classes), Theorem 1.11 (James–Stein), Proposition 1.12 (cost-sensitive classification)
50 shades of Bayes: Subjective and objective interpretations ch. 2: coherence and exchangeability (Theorems 2.2 and 2.4), conjugate elicitation (Example 2.5), Jeffreys and reference priors (Definition 2.6, Proposition 2.7), empirical Bayes (Definition 2.9, Example 2.10), Bernstein–von Mises (Theorem 2.11), the likelihood principle (Example 2.12)
Bayesian supervised and unsupervised learning Supervised: ch. 3 (Bayesian linear and logistic regression, evidence, Laplace approximation, Gaussian processes). Unsupervised: ch. 4 (mixtures and the Gibbs sampler, label switching, probabilistic and Bayesian PCA, latent Dirichlet allocation)
Bayesian computation for ML: Advanced Monte Carlo and variational methods Monte Carlo: ch. 5 (importance sampling, Metropolis–Hastings, MALA, Hamiltonian Monte Carlo, diagnostics, sequential Monte Carlo and the evidence), after the Gibbs sampler of ch. 4. Variational: ch. 6 (ELBO, coordinate ascent, stochastic and black-box VI); expectation propagation and the accuracy of variational Bayes in ch. 9
Bayesian nonparametrics ch. 7: the Dirichlet process (Definition 7.2 to Theorem 7.7), DP mixtures (Definition 7.8, Algorithm 7.9), Pitman–Yor and hierarchical processes; consistency and contraction rates in ch. 9 (Theorems 9.2–9.4) with the Pitman–Yor urn (Proposition 9.5); Gaussian processes in ch. 3
Bayesian methods for deep learning ch. 8: priors on weights and the Gaussian-process limit (Theorem 8.2), Laplace (Proposition 8.3), variational and dropout methods, SGLD (Algorithm 8.4), deep ensembles, scoring rules and calibration (Definitions 8.5–8.7), cold posteriors (Definition 8.8)
Objective: a high-level view of the main approaches to decisions under uncertainty ch. 1 (Bayes rules, minimax rules, admissibility, expected utility) and ch. 8 (proper scoring rules)
Objective: detect when being Bayesian helps and why Theorem 1.10, Example 2.10, Theorem 2.11, Proposition 3.6 and the code of ch. 3 and ch. 8
Objective: design and run a Bayesian ML pipeline for standard supervised or unsupervised learning The code of ch. 3 to ch. 7, Exercises 14 and 17, the projects
Objective: current limitations of Bayesian approaches and the research landscape ch. 10 (self-study), with the limits met on the way: Theorem 2.11, Proposition 6.4, the number of clusters in ch. 7 and ch. 9, cold posteriors in ch. 8
Objective: understand the abstract of most Bayesian ML papers ch. 10, “Reading a Bayesian machine learning paper”, and the paper studies of the projects
Organisation: 8 × 3 hours of lectures and practical sessions Session plan, sessions 1–8, each with a practical in Python
Organisation: practicals in Python and R Partly covered: the code of these notes is Python only (NumPy, SciPy, PyTorch); R is not covered, to keep a single environment
Organisation: 4 hours of student seminars for the evaluation Session plan, session 9, and Projects and assessment
Assessment: group paper study with a report and a student seminar (master-mva.com); “Evaluation Continue non Intégrale” (Université Paris-Saclay) Projects and assessment

Every official theme has a section in these notes. The extensions beyond the syllabus are the review of ch. 0 and two self-study chapters: the complements of ch. 9 (consistency and contraction rates, mixtures of finite mixtures, expectation propagation, accuracy of variational Bayes) and the research directions of ch. 10.

Where this course fits in the programme

Official prerequisites: an undergraduate course in probability, and a basic knowledge of Python and R. The description recommends the semester-1 course of P. Latouche and N. Chopin on probabilistic graphical models or that of S. Allassonière on computational statistics. Ch. 0 reviews the probability used throughout.

Course outline

Session plan

28 h in class = 9 sessions (8 × 3 h + 1 × 4 h). The volume of 28 h comes from the Université Paris-Saclay programme table (16 h of lectures and 12 h of labs). master-mva.com describes the same total as 8 × 3 h of lectures and practicals plus 4 h of student seminars for the evaluation. The content of each session and its split between lecture and practical are a proposal.

Level 1 = foundations, 2 = core results and algorithms, 3 = advanced and research-level material. The level never goes down from one session to the next.

Session Hours Level Content Practice
1 3 h 1 ch. 0 Review: Bayes’ formula, Gaussian conditioning, conjugacy, KL, Markov chains; ch. 1 Decision theory: risk, Bayes rules, admissibility, minimaxity, James–Stein, cost-sensitive decisions Ex. 1, 2, 8, 9; lab: risk curves
2 3 h 1 ch. 2 Fifty shades of Bayes: coherence, exchangeability, conjugate and objective priors, empirical Bayes, Bernstein–von Mises, likelihood principle Ex. 3, 4, 7; lab: coverage of credible intervals
3 3 h 2 ch. 3 Bayesian linear regression, evidence, Laplace approximation, logistic regression, Gaussian processes Ex. 5, 13; lab: evidence and GP hyperparameters
4 3 h 2 ch. 4 Mixtures and the Gibbs sampler, label switching, probabilistic PCA, latent Dirichlet allocation Ex. 14; lab: Gibbs sampler for a mixture
5 3 h 2 ch. 5 Importance sampling, Metropolis–Hastings, MALA, HMC, diagnostics, sequential Monte Carlo Ex. 11; lab: three samplers compared
6 3 h 2 ch. 6 ELBO, coordinate ascent VI, stochastic and black-box VI, beyond the reverse KL Ex. 10; lab: reparameterized VI
7 3 h 3 ch. 7 Dirichlet process, Chinese restaurant and stick-breaking, DP mixtures and their collapsed Gibbs sampler, Pitman–Yor and hierarchical processes Ex. 6, 12, 17; lab: DP mixture
8 3 h 3 ch. 8 Priors on weights and the GP limit, Laplace, VI, dropout, SG-MCMC, ensembles, calibration, cold posteriors Ex. 15, 16; lab: deep ensembles
9 4 h 3 Student seminars: each group presents its paper study (the official evaluation) Projects

Self-study, outside the 28 h (about 6 h in total): ch. 9 Complements for self-study (≈ 3 h) · ch. 10 Research directions and open problems (≈ 3 h).

How to study this module

0. Review: probability tools for Bayesian inference

Bayesian machine learning manipulates joint, marginal and conditional distributions, Gaussian vectors, exponential families, the Kullback–Leibler divergence and Markov chains. This chapter states the M1-level facts used later. The Probability and Statistics refresher covers the same ground at a slower pace.

Bayes’ formula for densities

Definition 0.1 — Bayesian model, posterior, predictive A Bayesian model consists of a family of densities p(x \mid \theta) of the data, the likelihood, and a density p(\theta) on the parameter, the prior. Densities are taken with respect to Lebesgue or counting measures. The posterior is the conditional density of \theta given the data: p(\theta \mid x) = \frac{p(x \mid \theta)\, p(\theta)}{p(x)}, \qquad p(x) = \int p(x \mid \theta)\, p(\theta)\, d\theta .

The normalizing constant p(x) is the marginal likelihood, or evidence. If a new observation x^\star is independent of x given \theta, its posterior predictive density is p(x^\star \mid x) = \int p(x^\star \mid \theta)\, p(\theta \mid x)\, d\theta .

Two remarks are used constantly. First, the posterior is known up to a constant as soon as the product of likelihood and prior is, and the constant p(x) is usually the hard part. Second, for independent observations the posterior can be updated one observation at a time: yesterday’s posterior is today’s prior.

Gaussian vectors

Proposition 0.2 — Conditioning a Gaussian vector Let (u, v) be a Gaussian vector with means \mu_u, \mu_v and covariance blocks \Sigma_{uu}, \Sigma_{uv}, \Sigma_{vv}, with \Sigma_{vv} invertible. Then u given v is Gaussian: u \mid v \;\sim\; \mathcal{N}\big(\mu_u + \Sigma_{uv} \Sigma_{vv}^{-1} (v - \mu_v),\;\; \Sigma_{uu} - \Sigma_{uv} \Sigma_{vv}^{-1} \Sigma_{vu}\big).

Proof. Set A = \Sigma_{uv}\Sigma_{vv}^{-1} and r = u - \mu_u - A(v - \mu_v).

  • The vector (r, v) is Gaussian and \mathrm{Cov}(r, v) = \Sigma_{uv} - A \Sigma_{vv} = 0, so r is independent of v.
  • Hence, given v, the vector u = \mu_u + A(v - \mu_v) + r is Gaussian with the announced mean and covariance \mathrm{Cov}(r) = \Sigma_{uu} - A\Sigma_{vu} - \Sigma_{uv}A^\top + A\Sigma_{vv}A^\top = \Sigma_{uu} - \Sigma_{uv}\Sigma_{vv}^{-1}\Sigma_{vu} .

∎

Proposition 0.3 — The linear Gaussian model Let \theta \sim \mathcal{N}(m_0, S_0) and y \mid \theta \sim \mathcal{N}(\Phi\theta, \Sigma). Then the marginal of y and the posterior of \theta are Gaussian: y \sim \mathcal{N}\big(\Phi m_0,\; \Sigma + \Phi S_0 \Phi^\top\big), \qquad \theta \mid y \sim \mathcal{N}(m_N, S_N), S_N^{-1} = S_0^{-1} + \Phi^\top \Sigma^{-1} \Phi, \qquad m_N = S_N\big(S_0^{-1} m_0 + \Phi^\top \Sigma^{-1} y\big).

Proof. Write y = \Phi\theta + \varepsilon with \varepsilon \sim \mathcal{N}(0, \Sigma) independent of \theta: the pair (\theta, y) is Gaussian, which gives the marginal.

For the posterior, the logarithm of p(y \mid \theta)\, p(\theta) is, as a function of \theta, -\tfrac12\, \theta^\top \big(S_0^{-1} + \Phi^\top\Sigma^{-1}\Phi\big)\theta + \theta^\top\big(S_0^{-1}m_0 + \Phi^\top\Sigma^{-1}y\big) + \text{const}, which is the logarithm of the announced Gaussian density up to a constant: complete the square. ∎

Exponential families and conjugacy

Definition 0.4 — Exponential family A family of densities is an exponential family with natural parameter \eta and sufficient statistic T if p(x \mid \eta) = h(x) \exp\big(\eta^\top T(x) - A(\eta)\big), where the log-partition function A(\eta) normalizes the density. Differentiating under the integral gives \nabla A(\eta) = \mathbb{E}_\eta[T(x)] and \nabla^2 A(\eta) = \mathrm{Cov}_\eta[T(x)].

Proposition 0.5 — Conjugate priors For n independent observations from the family of Definition 0.4, the priors p(\eta \mid \nu, \tau) \propto \exp\big(\eta^\top \tau - \nu A(\eta)\big) form a conjugate family: the posterior belongs to it, with updated parameters \tau_n = \tau + \sum_{i=1}^n T(x_i), \qquad \nu_n = \nu + n .

Proof. The product of the prior and the n likelihood factors is proportional to \exp\Big(\eta^\top\big(\tau + \textstyle\sum_i T(x_i)\big) - (\nu + n) A(\eta)\Big). ∎

The prior behaves like \nu pseudo-observations with total sufficient statistic \tau. Ch. 2 uses this reading to elicit priors.

Example 0.6 — Three conjugate pairs

  • Bernoulli likelihood and Beta(a, b) prior: after k successes in n trials the posterior is Beta(a + k, b + n - k). With a uniform prior and 7 successes in 10 trials, the posterior is Beta(8, 4), with mean 8/12 = 0.667 .
  • Poisson likelihood and Gamma(a, b) prior (shape a, rate b): the posterior is Gamma(a + \sum_i x_i,\; b + n).
  • Gaussian likelihood with known variance \sigma^2 and a \mathcal{N}(m_0, s_0^2) prior on the mean: the posterior precision is 1/s_0^2 + n/\sigma^2, and the posterior mean is the precision-weighted average of m_0 and the sample mean.

The Kullback–Leibler divergence

Definition 0.7 — Kullback–Leibler divergence For densities p and q with q > 0 wherever p > 0, \mathrm{KL}(p \,\|\, q) = \int p(x) \log \frac{p(x)}{q(x)}\, dx .

Proposition 0.8 — Gibbs’ inequality For all densities p and q, \mathrm{KL}(p \,\|\, q) \geq 0, \quad \text{with equality if and only if } p = q \text{ almost everywhere.}

Proof. By Jensen’s inequality for the concave logarithm, -\mathrm{KL}(p \,\|\, q) = \mathbb{E}_p\Big[\log \frac{q(x)}{p(x)}\Big] \leq \log \mathbb{E}_p\Big[\frac{q(x)}{p(x)}\Big] = \log \int_{p > 0} q \leq 0 . Equality in Jensen forces q/p to be constant on \{p > 0\}, and the second inequality forces the constant to be 1. ∎

The divergence is not symmetric. Variational inference (ch. 6) minimizes \mathrm{KL}(q \,\|\, p) over an approximation q, and expectation propagation works with the other direction; the two give different answers.

Markov chains

Definition 0.9 — Markov kernel, invariance, reversibility A Markov kernel P(x, dy) on a state space E moves a point x to a random point y.

A probability \pi is invariant for P if X_0 \sim \pi implies X_1 \sim \pi, that is \int_E \pi(dx)\, P(x, dy) = \pi(dy).

The kernel is reversible with respect to \pi, or satisfies detailed balance, if \pi(dx) P(x, dy) = \pi(dy) P(y, dx) as measures on E \times E. Reversibility implies invariance: integrate both sides over x.

Theorem 0.10 — Ergodic theorem for Markov chains Let P be a kernel with invariant distribution \pi that is \pi-irreducible and Harris recurrent. Then for every f integrable under \pi and every starting point, \frac{1}{T} \sum_{t=1}^T f(X_t) \xrightarrow[T \to \infty]{\text{a.s.}} \int f\, d\pi .

The proof is in Robert and Casella (2004, ch. 6) and Meyn and Tweedie (2009).

This theorem is the reason Markov chain Monte Carlo works (ch. 4 and 5): build a chain whose invariant distribution is the posterior, run it, and average along the path.

Key takeaways — chapter 0

  • Posterior ∝ likelihood × prior; the evidence p(x) is the normalizing constant and the hard part.
  • Gaussian conditioning (Proposition 0.2) and the linear Gaussian model (Proposition 0.3) give closed-form posteriors.
  • Exponential families have conjugate priors that act as pseudo-observations.
  • KL is non-negative and asymmetric; MCMC rests on invariance and the ergodic theorem.

1. Decision theory

Learning is acting: predicting a label, choosing a dose, flagging a transaction. Decision theory compares ways of acting when the state of the world is unknown, and shows that the Bayes rule answers a precise question.

Losses, risks and Bayes rules

Definition 1.1 — Statistical decision problem A decision problem consists of

  • a parameter space \Theta, the unknown state of the world, and a statistical model P_\theta for the data X;
  • an action space \mathcal{A} and a loss function L : \Theta \times \mathcal{A} \to [0, \infty);
  • decision rules \delta, measurable maps from the data space to \mathcal{A}.

The (frequentist) risk of \delta is its average loss over the data, for a fixed \theta: R(\theta, \delta) = \mathbb{E}_\theta\big[L(\theta, \delta(X))\big].

Estimation takes \mathcal{A} = \Theta and, for instance, the squared loss. Testing takes \mathcal{A} = \{0, 1\} and the 0–1 loss. Probabilistic prediction takes for \mathcal{A} a set of distributions and the log loss, the setting of ch. 8.

The risk is a function of \theta, and two rules are rarely ordered for every \theta. There are two classical ways to summarize a risk function by a number: average it over \theta (Bayes), or take its worst case (minimax).

Definition 1.2 — Bayes risk, posterior expected loss, Bayes rule Let \pi be a prior on \Theta.

  • The integrated risk of \delta is r(\pi, \delta) = \int R(\theta, \delta)\, \pi(d\theta).
  • The posterior expected loss of an action a after observing x is \rho(\pi, a \mid x) = \mathbb{E}\big[L(\theta, a) \mid X = x\big] = \int L(\theta, a)\, \pi(d\theta \mid x).
  • A Bayes rule \delta^\pi minimizes r(\pi, \cdot) over all decision rules, and r(\pi) = r(\pi, \delta^\pi) is the Bayes risk of \pi.

Theorem 1.3 — Bayes rules minimize the posterior expected loss Suppose that for almost every x the action \delta^\pi(x) minimizes a \mapsto \rho(\pi, a \mid x), and that r(\pi, \delta^\pi) < \infty. Then \delta^\pi is a Bayes rule: r(\pi, \delta^\pi) = \min_\delta\, r(\pi, \delta).

Proof. The loss is non-negative, so Fubini’s theorem lets us integrate over the joint law of (\theta, X) in either order: r(\pi, \delta) = \int\!\!\int L(\theta, \delta(x))\, p(x \mid \theta)\, \pi(\theta)\, dx\, d\theta = \int \rho\big(\pi, \delta(x) \mid x\big)\, p(x)\, dx .

For every rule \delta, the integrand is at least \rho(\pi, \delta^\pi(x) \mid x) for almost every x. Integrating against p(x) gives r(\pi, \delta) \geq r(\pi, \delta^\pi). ∎

Key formula — the Bayes action \delta^\pi(x) \in \arg\min_{a \in \mathcal{A}}\; \mathbb{E}\big[L(\theta, a) \mid X = x\big]

The theorem is the operational content of Bayesian decision theory. There is no need to optimize over functions: after seeing x, minimize a function of the action. The average-over-data question and the given-the-data question have the same answer.

Proposition 1.4 — Bayes estimators for three standard losses Let \theta be real with posterior \pi(\cdot \mid x).

  • Squared loss (\theta - a)^2: the Bayes estimator is the posterior mean, and its posterior expected loss is the posterior variance.
  • Absolute loss |\theta - a|: any posterior median is a Bayes estimator.
  • For a discrete \Theta and the 0–1 loss \mathbb{1}\{a \neq \theta\}: the posterior mode (MAP).

Proof. All expectations are under the posterior.

  • Squared loss: the bias–variance decomposition \mathbb{E}[(\theta - a)^2] = \mathrm{Var}(\theta \mid x) + (\mathbb{E}[\theta \mid x] - a)^2 is minimal at the posterior mean.
  • Absolute loss: let m be a median and a' > m. The difference |\theta - a'| - |\theta - m| equals a' - m when \theta \leq m and is at least -(a' - m) otherwise. Hence \mathbb{E}|\theta - a'| - \mathbb{E}|\theta - m| \geq (a' - m)\big[P(\theta \leq m) - P(\theta > m)\big] \geq 0, because P(\theta \leq m) \geq 1/2. The case a' < m is symmetric.
  • 0–1 loss: the posterior expected loss of a is 1 - \pi(a \mid x), minimal at the mode. ∎

For a continuous parameter, the MAP is in general not the Bayes estimator of a fixed loss. Under regularity conditions, it is only a limit of Bayes estimators for the losses \mathbb{1}\{|\theta - a| > \varepsilon\} as \varepsilon \to 0. It also depends on the parameterization, through the Jacobian of the change of variables (Exercise 13). It is best seen as a cheap summary of the posterior.

Example 1.5 — Three estimators from one posterior After 7 successes in 10 trials with a uniform prior, the posterior is Beta(8, 4) (Example 0.6).

  • Squared loss: the posterior mean 8/12 = 0.667.
  • Absolute loss: the posterior median 0.676.
  • MAP: the mode 7/10 = 0.700, which is also the maximum-likelihood estimate because the prior is flat.

Three losses encode three questions, and the same posterior gives three answers.

Admissibility and minimaxity

Definition 1.6 — Admissible and minimax rules A rule \delta' dominates \delta if R(\theta, \delta') \leq R(\theta, \delta) for every \theta, with strict inequality for at least one \theta. A rule is admissible if no rule dominates it. A rule \delta^\star is minimax if \sup_\theta R(\theta, \delta^\star) = \inf_\delta\, \sup_\theta R(\theta, \delta).

Proposition 1.7 — Bayes rules are admissible A Bayes rule \delta^\pi with r(\pi) < \infty is admissible in each of the two following cases.

  • (a) It is the unique Bayes rule for \pi.
  • (b) \Theta is an open subset of \mathbb{R}^d, \pi gives positive mass to every non-empty open set, and every rule has a risk continuous in \theta.

Proof. Suppose that \delta' dominates \delta^\pi.

  • (a) Integrating the domination against \pi gives r(\pi, \delta') \leq r(\pi, \delta^\pi), so \delta' is also a Bayes rule. By uniqueness \delta' = \delta^\pi, which cannot strictly dominate itself.
  • (b) Let \theta_0 be a point of strict domination. By continuity, there are \varepsilon > 0 and an open neighbourhood U of \theta_0 on which R(\theta, \delta') < R(\theta, \delta^\pi) - \varepsilon . Integrating against \pi, the integrated risk of \delta' is at most r(\pi) - \varepsilon\, \pi(U), which is smaller than the Bayes risk: a contradiction. ∎

Proposition 1.8 — A Bayes rule with constant risk is minimax If R(\theta, \delta^\pi) = c for every \theta, then \delta^\pi is minimax.

Proof. For any rule \delta, a supremum is larger than an average, and \delta^\pi minimizes the average: \sup_\theta R(\theta, \delta) \geq r(\pi, \delta) \geq r(\pi, \delta^\pi) = c = \sup_\theta R(\theta, \delta^\pi). \qquad ∎

Example 1.9 — A minimax estimator of a proportion Let K \sim \mathrm{Bin}(n, \theta) and take the squared loss. With a Beta(a, a) prior, the Bayes estimator is (K + a)/(n + 2a), and its risk is its variance plus its squared bias: R(\theta) = \frac{n\theta(1-\theta) + a^2(1 - 2\theta)^2}{(n + 2a)^2} = \frac{a^2 + (n - 4a^2)(\theta - \theta^2)}{(n + 2a)^2}.

  • The risk does not depend on \theta when a = \sqrt{n}/2. It is then R = \frac{1}{4(1 + \sqrt{n})^2}, so the estimator (K + \sqrt n/2)/(n + \sqrt n) is minimax by Proposition 1.8.
  • For n = 16 the minimax estimator is (K + 2)/20, with risk 0.0100 everywhere. The maximum-likelihood estimator K/n has maximal risk 1/(4n) = 0.0156, at \theta = 1/2.

The code computes the exact risk curves of three estimators. It reports their worst-case risk and their average risk under the uniform prior:

import numpy as np
from scipy import stats

n = 16
theta = np.linspace(0.001, 0.999, 999)
k = np.arange(n + 1)
pmf = stats.binom.pmf(k[None, :], n, theta[:, None])     # P(K = k | theta)

def risk(est):                                             # squared-error risk R(theta, delta)
    return (pmf * (est[None, :] - theta[:, None]) ** 2).sum(axis=1)

rules = {
    "MLE k/n": k / n,
    "Bayes, uniform prior": (k + 1) / (n + 2),
    "minimax, Beta(2,2) prior": (k + 2) / (n + 4),          # a = sqrt(16)/2 = 2
}
for name, est in rules.items():
    r = risk(est)
    print(f"{name:26s} max risk {r.max():.5f}   Bayes risk (uniform) {r.mean():.5f}")

The maximum-likelihood estimator has worst-case risk 0.0156 and average risk 0.0104. The uniform-prior Bayes rule has the smallest average, 0.0093, as it must, and a worst case of 0.0123. The minimax rule has the smallest worst case, 0.0100, flat in \theta. No estimator wins for every \theta.

Complete classes and Stein’s paradox

Theorem 1.10 — Complete class theorem (Wald) Under regularity conditions, every admissible rule is a Bayes rule or a limit of Bayes rules. For a finite parameter space and randomized rules, every admissible rule is Bayes for some prior.

Proof sketch for \Theta = \{\theta_1, \dots, \theta_k\}. Randomized rules make the set S of risk vectors (R(\theta_1, \delta), \dots, R(\theta_k, \delta)) convex.

An admissible rule has a risk vector r^\star on the lower-left boundary of S. The separating hyperplane theorem gives weights \pi_i \geq 0 summing to 1 with \sum_i \pi_i r^\star_i \leq \sum_i \pi_i r_i for every r \in S: the rule is Bayes for \pi. The general case is treated in Berger (1985) and Robert (2007).

This is one precise sense in which being Bayesian helps: any sensible rule, in the sense of admissibility, is Bayes for some prior, so restricting attention to Bayes rules loses nothing. The next result shows that the most natural non-Bayesian estimator is not admissible.

Theorem 1.11 — James–Stein (1961) Let X \sim \mathcal{N}(\theta, I_d) with d \geq 3, and take the loss \|\theta - a\|^2. The estimator \delta^{\mathrm{JS}}(X) = \Big(1 - \frac{d - 2}{\|X\|^2}\Big) X has risk R(\theta, \delta^{\mathrm{JS}}) = d - (d-2)^2\, \mathbb{E}_\theta\big[\|X\|^{-2}\big] \;<\; d = R(\theta, X), so the maximum-likelihood estimator X is inadmissible when d \geq 3.

Proof. Stein’s lemma: for Z \sim \mathcal{N}(\mu, 1) and a weakly differentiable g with \mathbb{E}|g'(Z)| < \infty, an integration by parts against the Gaussian density gives \mathbb{E}[(Z - \mu)\, g(Z)] = \mathbb{E}[g'(Z)].

Write \delta^{\mathrm{JS}} = X - g(X) with g(x) = (d-2)\, x / \|x\|^2. Expanding the square, \mathbb{E}\|\delta^{\mathrm{JS}} - \theta\|^2 = d - 2\,\mathbb{E}\big[(X-\theta)^\top g(X)\big] + \mathbb{E}\|g(X)\|^2 .

  • Stein’s lemma, coordinate by coordinate, turns the middle expectation into \mathbb{E}[\operatorname{div} g(X)], and \operatorname{div}(x/\|x\|^2) = (d-2)/\|x\|^2.
  • So the middle term is -2(d-2)^2\, \mathbb{E}\|X\|^{-2}, while the last term is (d-2)^2\, \mathbb{E}\|X\|^{-2}. ∎

At \theta = 0, \|X\|^2 follows a \chi^2_d law with \mathbb{E}[1/\chi^2_d] = 1/(d-2), so the risk drops from d to 2. For d = 10, that is from 10 to 2. Shrinking all coordinates towards a common point helps, although they are independent: ch. 2 explains why, as empirical Bayes (Example 2.10).

Decisions in classification and the foundations

Proposition 1.12 — Cost-sensitive classification Labels are y \in \{0, 1\} and actions \hat y \in \{0, 1\}. Predicting 1 when y = 0 costs c_{\mathrm{FP}}, predicting 0 when y = 1 costs c_{\mathrm{FN}}, and correct predictions cost nothing. The Bayes rule predicts 1 if and only if p(y = 1 \mid x, \mathcal{D}) > \frac{c_{\mathrm{FP}}}{c_{\mathrm{FP}} + c_{\mathrm{FN}}} .

Proof. Write p = p(y = 1 \mid x, \mathcal{D}). The posterior expected loss of predicting 1 is c_{\mathrm{FP}}(1 - p), that of predicting 0 is c_{\mathrm{FN}}\, p; Theorem 1.3 picks the smaller one. ∎

The threshold is applied to the predictive probability. If that probability is miscalibrated, the decision is wrong even with the right costs; this is why ch. 3 and ch. 8 care about predictive distributions rather than point predictions. An option to abstain at cost c_r adds a third action, chosen when both expected losses exceed c_r.

Foundations: expected utility Why maximize expected utility at all? Von Neumann and Morgenstern (1944) show that preferences between lotteries satisfying completeness, transitivity, continuity and independence are represented by an expected utility. Savage (1954) goes further: preferences between acts satisfying his axioms are represented by an expected utility under a subjective probability, which plays the role of the prior. Parmigiani and Inoue (2009) develop these axioms and their criticisms.

Key takeaways — chapter 1

  • The risk R(\theta, \delta) averages the loss over data; the Bayes rule minimizes its average over the prior, which amounts to minimizing the posterior expected loss for the observed data (Theorem 1.3).
  • Squared, absolute and 0–1 losses give the posterior mean, median and mode.
  • Bayes rules are admissible, constant-risk Bayes rules are minimax, and admissible rules are (limits of) Bayes rules.
  • In dimension 3 or more, shrinkage beats the maximum-likelihood estimator of a Gaussian mean.
  • Cost-sensitive decisions threshold the predictive probability, so it must be calibrated.

2. Fifty shades of Bayes: subjective and objective interpretations

Theorem 1.3 needs a prior. Where does it come from, and what does a posterior probability mean? Two families of answers coexist. For the subjective view, probability is a coherent degree of belief. For the objective view, the prior is a convention derived from the model. Two pragmatic positions complete the picture: estimate the prior from the data (empirical Bayes), or judge Bayesian procedures by their frequentist properties.

Subjective Bayes: coherence and exchangeability

Definition 2.1 — Coherent previsions (de Finetti) An agent announces a price P(A) for every event A of a finite algebra. At that price she accepts to buy or sell, for any stake s \in \mathbb{R}, the bet that costs s P(A) and pays s\, \mathbb{1}_A.

A Dutch book is a finite set of such bets whose total gain for the agent is negative in every state of the world. The prices are coherent if no Dutch book exists.

Theorem 2.2 — Coherence means probability (de Finetti, 1937) Prices on a finite algebra of events are coherent if and only if they form a probability: P(A) \in [0, 1], P(\Omega) = 1, and P(A \cup B) = P(A) + P(B) for disjoint A and B.

Proof. Additivity is necessary. Let A, B be disjoint with P(A \cup B) > P(A) + P(B). The opponent sells the agent a unit bet on A \cup B and buys from her unit bets on A and on B.

Since \mathbb{1}_{A \cup B} = \mathbb{1}_A + \mathbb{1}_B, the payoffs cancel in every state, and the agent’s net gain is P(A) + P(B) - P(A \cup B) < 0. Reverse the bets for the opposite inequality. The same kind of argument gives 0 \leq P(A) \leq 1 and P(\Omega) = 1.

Probability is sufficient. If P is a probability, every bet has expected gain zero under P, and so does every finite combination. A combination with a negative gain in every state would have a negative expectation. ∎

Coherence gives probabilities, not a specific prior. De Finetti’s second theorem explains where parameters and priors come from in the first place.

Definition 2.3 — Exchangeability A sequence (X_1, X_2, \dots) is exchangeable if, for every n and every permutation \sigma of \{1, \dots, n\}, the vectors (X_{\sigma(1)}, \dots, X_{\sigma(n)}) and (X_1, \dots, X_n) have the same law.

Theorem 2.4 — De Finetti’s representation theorem An infinite exchangeable sequence of \{0, 1\}-valued variables is a mixture of independent Bernoulli sequences. There is a unique probability \mu on [0, 1] such that, with k = x_1 + \dots + x_n, P(X_1 = x_1, \dots, X_n = x_n) = \int_0^1 \theta^{k} (1 - \theta)^{n - k}\, \mu(d\theta), and \mu is the law of the limiting frequency of ones, which exists almost surely.

Proof. Sketch. Fix N \geq n and let K_N be the number of ones among X_1, \dots, X_N.

  • By exchangeability, given K_N, the first n variables are distributed as n draws without replacement from an urn holding K_N ones and N - K_N zeros.
  • As N \to \infty, draws without replacement approach draws with replacement, so the probability above is close to \mathbb{E}\big[(K_N/N)^k (1 - K_N/N)^{n-k}\big].
  • Along a subsequence, the law of K_N/N converges weakly to some \mu, which gives the formula. Hewitt and Savage (1955) extend the theorem to general state spaces. ∎

The interpretation matters. If your beliefs about a sequence do not depend on the order of the observations, you behave as if there were a parameter \theta, with a prior \mu, and independent data given \theta. The parameter and the prior are consequences of a judgement on observable quantities.

Conjugate priors as an elicitation tool

Proposition 0.5 reads a conjugate prior as pseudo-data. An expert can express a prior mean and an equivalent sample size, “as sure as if I had seen m observations”, and the two numbers fix the prior.

Example 2.5 — Eliciting a click rate An expert believes a click rate is about 2 %, and is as sure as if she had seen 200 impressions. The prior is Beta(4, 196).

  • After 1000 impressions with 35 clicks, the posterior is Beta(39, 1161).
  • Its mean is 39 / 1200 = 0.0325, between the prior mean 0.02 and the empirical rate 0.035, with weights 200/1200 and 1000/1200.

A responsible analysis reports how the conclusions move when the prior moves within a plausible family. This sensitivity analysis is the subjective answer to the charge of arbitrariness.

Objective Bayes: Jeffreys and reference priors

Definition 2.6 — Jeffreys prior For a regular model with Fisher information I(\theta) = \mathbb{E}_\theta\big[-\nabla^2 \log p(X \mid \theta)\big], the Jeffreys prior is \pi_J(\theta) \propto \sqrt{\det I(\theta)} .

Proposition 2.7 — Invariance under reparameterization Let \varphi = h(\theta) with h a smooth bijection. The Jeffreys prior computed in the parameter \varphi is the image of \pi_J under h.

Proof. Let J = \partial\theta / \partial\varphi. By the chain rule the score transforms as \nabla_\varphi \log p = J^\top \nabla_\theta \log p, so the information transforms as I_\varphi(\varphi) = J^\top I_\theta(\theta)\, J, \qquad \sqrt{\det I_\varphi(\varphi)} = |\det J|\, \sqrt{\det I_\theta(\theta)} . The factor |\det J| is exactly the change-of-variables factor of a density. ∎

The point of the proposition: “ignorance” cannot be expressed by a flat prior, since a flat prior on \theta is not flat on \theta^2. Jeffreys’ rule gives the same answer whatever parameterization one starts from.

Example 2.8 — Jeffreys priors of common models

  • Bernoulli: I(\theta) = 1/(\theta(1 - \theta)), so \pi_J is Beta(1/2, 1/2).
  • Normal location with known variance: I is constant, so \pi_J is flat on \mathbb{R}.
  • Normal scale \sigma with known mean: I(\sigma) = 2/\sigma^2, so \pi_J(\sigma) \propto 1/\sigma.
  • Poisson: I(\lambda) = 1/\lambda, so \pi_J(\lambda) \propto \lambda^{-1/2}.

The last three priors are improper: they do not integrate to 1. Such a prior is acceptable only if the posterior is proper, that is if \int p(x \mid \theta)\, \pi(\theta)\, d\theta is finite. Improper priors leave the evidence defined only up to an arbitrary constant, so they cannot be used to compare models (ch. 3).

In several dimensions the Jeffreys prior can behave badly. Reference priors (Bernardo, 1979; Berger, Bernardo and Sun, 2009) fix this: they maximize the expected Kullback–Leibler divergence from prior to posterior, in the limit of many replications of the experiment. In regular one-dimensional models they coincide with the Jeffreys prior.

Empirical Bayes

Definition 2.9 — Hierarchical model and empirical Bayes In a hierarchical model, \theta_1, \dots, \theta_d are drawn independently from a prior \pi_\lambda with a hyperparameter \lambda, and X_i \mid \theta_i \sim p(\cdot \mid \theta_i). Empirical Bayes estimates \lambda by maximizing the marginal likelihood p(x \mid \lambda) = \prod_{i=1}^d \int p(x_i \mid \theta)\, \pi_\lambda(\theta)\, d\theta , also called type-II maximum likelihood, then uses the posterior with the estimated \hat\lambda. A fully Bayesian analysis puts a prior on \lambda instead.

Example 2.10 — Normal means: empirical Bayes rediscovers James–Stein Let \theta_i \sim \mathcal{N}(0, \tau^2) and X_i \mid \theta_i \sim \mathcal{N}(\theta_i, 1), for i = 1, \dots, d.

  • Posterior mean (Example 0.6): \mathbb{E}[\theta_i \mid X_i] = (1 - B) X_i, with B = 1/(1 + \tau^2).
  • Marginally the X_i are independent \mathcal{N}(0, 1/B), so B\, \|X\|^2 follows a \chi^2_d law and \mathbb{E}\Big[\frac{d - 2}{\|X\|^2}\Big] = B .
  • Replacing B by this unbiased estimate gives exactly the James–Stein estimator of Theorem 1.11.

The coordinates are independent, but they share a hyperparameter, and each coordinate carries information on it. Efron and Morris (1973) develop this reading.

Frequentist properties of Bayesian procedures

Theorem 2.11 — Bernstein–von Mises Let X_1, \dots, X_n be i.i.d. from p_{\theta_0}, with \theta_0 interior to \Theta \subset \mathbb{R}^d.

Assume the model is regular (differentiable in quadratic mean, with invertible Fisher information I(\theta_0)), that uniformly consistent tests of \theta_0 exist, and that the prior has a continuous positive density at \theta_0. Then, in P_{\theta_0}-probability, \Big\| \Pi(\cdot \mid X_{1:n}) - \mathcal{N}\big(\hat\theta_n,\; \tfrac{1}{n} I(\theta_0)^{-1}\big) \Big\|_{\mathrm{TV}} \longrightarrow 0, where \hat\theta_n is an efficient estimator, for instance the maximum-likelihood estimator.

Proof. Sketch (van der Vaart, 1998, Theorem 10.1). Work in the local parameter h = \sqrt{n}(\theta - \theta_0).

  • Local asymptotic normality: the log-likelihood ratio is h^\top \Delta_n - \frac12 h^\top I(\theta_0) h + o_P(1), where \Delta_n is the normalized score, asymptotically \mathcal{N}(0, I(\theta_0)).
  • On the scale 1/\sqrt{n} the prior density is nearly constant, equal to \pi(\theta_0).
  • So the posterior density of h is nearly proportional to \exp(h^\top \Delta_n - \frac12 h^\top I h), a Gaussian with covariance I^{-1}. The tests control the posterior mass outside shrinking neighbourhoods of \theta_0. ∎

Three consequences follow. In fixed dimension, the prior is forgotten at rate 1/\sqrt{n}. A 95 % credible set is asymptotically a 95 % confidence set. And the theorem fails exactly where Bayesian methods are most interesting: in high dimension, in nonparametric models (ch. 7), and under misspecification, where the posterior concentrates at the best approximation within the model but with the wrong spread (Kleijn and van der Vaart, 2012).

The code computes the exact frequentist coverage of three 95 % intervals for a proportion with n = 30: the Wald interval, and the equal-tailed credible intervals under the Jeffreys and the uniform priors.

import numpy as np
from scipy import stats

n = 30
k = np.arange(n + 1)
z = stats.norm.ppf(0.975)

def coverage(lo, hi, theta):
    inside = (lo <= theta) & (theta <= hi)
    return stats.binom.pmf(k, n, theta)[inside].sum()

phat = k / n
wald = (phat - z * np.sqrt(phat * (1 - phat) / n), phat + z * np.sqrt(phat * (1 - phat) / n))
jeff = (stats.beta.ppf(0.025, k + 0.5, n - k + 0.5), stats.beta.ppf(0.975, k + 0.5, n - k + 0.5))
unif = (stats.beta.ppf(0.025, k + 1, n - k + 1), stats.beta.ppf(0.975, k + 1, n - k + 1))

thetas = np.linspace(0.01, 0.99, 197)
for name, (lo, hi) in {"Wald": wald, "Jeffreys": jeff, "uniform": unif}.items():
    c = np.array([coverage(lo, hi, t) for t in thetas])
    print(f"{name:9s} mean coverage {c.mean():.3f}   min coverage {c.min():.3f}"
          f"   at theta=0.1: {coverage(lo, hi, 0.1):.3f}")

The Wald interval has mean coverage 0.887 and drops to 0.26 near the boundary. The Jeffreys interval has mean coverage 0.950 and minimum 0.889; the uniform-prior interval has 0.952 and 0.879. At \theta = 0.1 the three coverages are 0.809, 0.932 and 0.974. Brown, Cai and DasGupta (2001) recommend the Jeffreys interval on these grounds: an objective prior gives a good frequentist procedure.

The likelihood principle

Bayesian inference depends on the data only through the likelihood function, up to a constant factor. Frequentist inference also depends on the experiments that could have happened but did not. Birnbaum (1962) showed that the sufficiency and conditionality principles together imply this likelihood principle.

Example 2.12 — Same data, two stopping rules A coin gives 9 heads and 3 tails. Under design A, 12 tosses were planned; under design B, the experimenter tossed until the third tail.

  • Both likelihoods are proportional to \theta^9 (1 - \theta)^3, so any prior gives the same posterior under both designs.
  • The one-sided p-values for \theta = 1/2 against \theta > 1/2 differ: p_A = 0.073 \;\;\text{(binomial)}, \qquad p_B = 0.033 \;\;\text{(negative binomial)} .

At the 5 % level, the test rejects under design B only. Lindley and Phillips (1976) discuss this example.

from scipy import stats
# 9 heads and 3 tails: P(at least 9 heads) under each design, for a fair coin
print("design A, binomial n = 12:        ", stats.binom.sf(8, 12, 0.5))
print("design B, stop at the third tail: ", stats.nbinom.sf(8, 3, 0.5))

Key takeaways — chapter 2

  • Coherent betting prices are probabilities, and exchangeable beliefs behave as an i.i.d. model with a prior (de Finetti).
  • Conjugate priors encode pseudo-observations; report how conclusions move with the prior.
  • Jeffreys priors are invariant under reparameterization; improper priors need a proper posterior and cannot compare models.
  • Empirical Bayes estimates the prior from many related problems, and explains James–Stein shrinkage.
  • Bernstein–von Mises: in regular finite-dimensional models, credible sets are asymptotically confidence sets.
  • Bayesian inference obeys the likelihood principle; p-values do not.

3. Bayesian supervised learning

Supervised learning the Bayesian way: put a prior on the function, through its parameters or directly, condition on the training pairs, and predict by averaging over the posterior. Linear-Gaussian models give closed forms; other models need approximations, the first of which is Laplace’s.

Bayesian linear regression

Take features \phi(x) \in \mathbb{R}^p, the design matrix \Phi with rows \phi(x_i)^\top, Gaussian noise of precision \beta and the prior w \sim \mathcal{N}(0, \alpha^{-1} I): y_i = w^\top \phi(x_i) + \varepsilon_i, \qquad \varepsilon_i \sim \mathcal{N}(0, \beta^{-1}) .

Proposition 3.1 — Posterior and predictive of Bayesian linear regression The posterior is w \mid y \sim \mathcal{N}(m_N, S_N) with S_N^{-1} = \alpha I + \beta\, \Phi^\top\Phi, \qquad m_N = \beta\, S_N \Phi^\top y , and the predictive distribution at a new input x^\star, with \phi^\star = \phi(x^\star), is y^\star \mid x^\star, y \;\sim\; \mathcal{N}\big(m_N^\top \phi^\star,\;\; \beta^{-1} + \phi^{\star\top} S_N\, \phi^\star\big). The posterior mean m_N is the ridge regression estimator with penalty \alpha / \beta.

Proof. Apply Proposition 0.3 with m_0 = 0, S_0 = \alpha^{-1} I and \Sigma = \beta^{-1} I.

Given y, the new response is y^\star = w^\top\phi^\star + \varepsilon^\star with w and \varepsilon^\star independent Gaussians, so the means and the variances add. Finally m_N = (\Phi^\top\Phi + (\alpha/\beta) I)^{-1}\Phi^\top y. ∎

Key formula — the Bayesian linear predictive y^\star \mid x^\star, y \sim \mathcal{N}\big(m_N^\top \phi^\star,\; \beta^{-1} + \phi^{\star\top} S_N \phi^\star\big)

The predictive variance has two parts: the noise \beta^{-1}, which no amount of data removes (aleatoric uncertainty), and the parameter uncertainty \phi^{\star\top} S_N \phi^\star, which shrinks as data accumulate near x^\star (epistemic uncertainty).

Example 3.2 — One feature, two points Take \phi(x) = x, \alpha = 1, \beta = 4 (noise standard deviation 0.5), and the data x = (1, 2), y = (1.2, 1.9).

  • \sum_i x_i^2 = 5 and \sum_i x_i y_i = 5, so the posterior precision is 1 + 4 \times 5 = 21.
  • The posterior is w \mid y \sim \mathcal{N}(20/21,\; 1/21) = \mathcal{N}(0.952,\; 0.218^2).
  • At x^\star = 3 the predictive mean is 2.857 and the predictive variance 0.25 + 9/21 = 0.679, a standard deviation of 0.824.

The marginal likelihood and model selection

Proposition 3.3 — Evidence of the linear model Marginally y \sim \mathcal{N}(0, C) with C = \beta^{-1} I + \alpha^{-1}\Phi\Phi^\top, so \log p(y \mid \alpha, \beta) = -\tfrac12\, y^\top C^{-1} y - \tfrac12 \log\det C - \tfrac{n}{2}\log 2\pi .

Proof. This is the marginal of Proposition 0.3. ∎

The evidence implements Occam’s razor. The first term rewards fit. The log-determinant penalizes models that spread their prior predictive mass over many possible data sets: since p(y \mid \mathcal{M}) integrates to 1 over y, a flexible model cannot give high density to everything.

To compare two models, Bayes’ formula multiplies the prior odds by the Bayes factor p(y \mid \mathcal{M}_1) / p(y \mid \mathcal{M}_2) (Kass and Raftery, 1995). The hyperparameters \alpha, \beta can be fitted by maximizing the evidence (Definition 2.9), as MacKay (1992) proposed.

The code fits polynomials of degree 0 to 9 to 20 noisy points of \sin(\pi x) and prints the training error of least squares and the log evidence:

import numpy as np

rng = np.random.default_rng(1)
n, alpha, beta = 20, 1.0, 1 / 0.2**2          # prior precision, noise precision (sigma = 0.2)
x = np.sort(rng.uniform(-1, 1, n))
y = np.sin(np.pi * x) + 0.2 * rng.normal(size=n)

def log_evidence(Phi):
    """log p(y) for y = Phi w + noise, w ~ N(0, I/alpha), noise ~ N(0, I/beta)."""
    C = np.eye(n) / beta + Phi @ Phi.T / alpha   # marginal covariance of y
    _, logdet = np.linalg.slogdet(C)
    return -0.5 * (y @ np.linalg.solve(C, y) + logdet + n * np.log(2 * np.pi))

for deg in range(10):
    Phi = np.vander(x, deg + 1, increasing=True)
    w_ml = np.linalg.lstsq(Phi, y, rcond=None)[0]
    rmse = np.sqrt(np.mean((Phi @ w_ml - y) ** 2))
    print(f"degree {deg}: training RMSE {rmse:.3f}   log evidence {log_evidence(Phi):7.2f}")

The training error decreases from 0.726 to 0.165. The log evidence jumps from −55.3 at degree 2 to −19.2 at degree 3, a Bayes factor of e^{36}, then slowly decreases to −20.3 at degree 9. The evidence picks degree 3 without any validation set, although its preference over degree 9 is weak (a factor of about 3).

A warning, known as Lindley’s paradox (Lindley, 1957): as the prior on the extra coefficients becomes vaguer, \alpha \to 0, the log-determinant grows without bound and the evidence of the larger model goes to 0. Evidence-based comparisons need proper, carefully chosen priors.

The Laplace approximation

Definition 3.4 — Laplace approximation Let \ell(\theta) = \log p(y \mid \theta) + \log p(\theta) have a mode \hat\theta with H = -\nabla^2 \ell(\hat\theta) positive definite. The Laplace approximation replaces the posterior and the evidence by p(\theta \mid y) \approx \mathcal{N}(\hat\theta, H^{-1}), \qquad \log p(y) \approx \ell(\hat\theta) + \frac{d}{2}\log 2\pi - \frac12 \log\det H .

Both come from the second-order Taylor expansion of \ell at \hat\theta and a Gaussian integral. For regular models with n observations, the relative error on the evidence is O(1/n) (Tierney and Kadane, 1986).

Corollary 3.5 — The Bayesian information criterion For n i.i.d. observations, H \approx n\, I(\hat\theta), so \log\det H = d \log n + O(1) and \log p(y) = \log p(y \mid \hat\theta) - \frac{d}{2}\log n + O_P(1). This is the BIC of Schwarz (1978): the prior disappears into the O_P(1) term.

Bayesian logistic regression

With labels y_i \in \{0, 1\}, P(y_i = 1 \mid w) = \sigma(w^\top x_i) and the prior \mathcal{N}(0, \alpha^{-1} I), the posterior has no closed form. The log posterior is concave, so the MAP is found by Newton’s method, and the Hessian at the mode is H = \alpha I + \sum_{i=1}^n \sigma_i (1 - \sigma_i)\, x_i x_i^\top, \qquad \sigma_i = \sigma(\hat w^\top x_i).

Proposition 3.6 — Moderated predictions Under a Gaussian approximation \mathcal{N}(m, S) of the posterior, the activation a = w^\top x^\star is \mathcal{N}(\mu_a, \sigma_a^2), with \mu_a = m^\top x^\star and \sigma_a^2 = x^{\star\top} S x^\star.

Approximating \sigma(a) by \Phi(\lambda a), where \Phi here denotes the standard normal distribution function (not a design matrix) and \lambda^2 = \pi/8, gives p(y^\star = 1 \mid x^\star, \mathcal{D}) \approx \sigma\big(\kappa(\sigma_a^2)\, \mu_a\big), \qquad \kappa(s) = \big(1 + \pi s / 8\big)^{-1/2} .

Proof. Let Z \sim \mathcal{N}(0, 1) be independent of a. Then \mathbb{E}[\Phi(\lambda a)] = P(Z - \lambda a \leq 0), and Z - \lambda a is \mathcal{N}(-\lambda\mu_a, 1 + \lambda^2\sigma_a^2), so \mathbb{E}[\Phi(\lambda a)] = \Phi\Big(\frac{\lambda\mu_a}{\sqrt{1 + \lambda^2\sigma_a^2}}\Big) \approx \sigma\Big(\frac{\mu_a}{\sqrt{1 + \lambda^2\sigma_a^2}}\Big). \qquad ∎

Example 3.7 — A moderated decision With \mu_a = 2 and \sigma_a^2 = 4, \kappa = (1 + \pi/2)^{-1/2} = 0.624.

  • The predictive probability is \sigma(1.247) = 0.777; the plug-in probability \sigma(2) is 0.881.
  • With costs giving the threshold 0.8 of Proposition 1.12, the plug-in rule predicts 1 and the Bayesian rule predicts 0.

Far from the data \sigma_a^2 grows and the predictive probability returns towards 1/2 (MacKay, 1992).

Gaussian processes

Definition 3.8 — Gaussian process A random function f is a Gaussian process with mean m and covariance kernel k, written f \sim \mathcal{GP}(m, k), if for all inputs x_1, \dots, x_n the vector (f(x_1), \dots, f(x_n)) is Gaussian with \text{mean } \big(m(x_i)\big)_{i} \quad \text{and covariance} \quad K = \big[k(x_i, x_j)\big]_{i,j} .

Bayesian linear regression is a Gaussian process with k(x, x') = \alpha^{-1} \phi(x)^\top \phi(x'). Kernels with infinitely many features, such as the squared-exponential kernel, give priors on infinite-dimensional spaces of functions: a first Bayesian nonparametric model (ch. 7).

Proposition 3.9 — Gaussian process regression Let y_i = f(x_i) + \varepsilon_i with f \sim \mathcal{GP}(0, k) and independent \varepsilon_i \sim \mathcal{N}(0, \sigma^2). With k_\star = (k(x_i, x^\star))_i and K_\sigma = K + \sigma^2 I, the posterior of f(x^\star) is Gaussian with \mathbb{E}[f(x^\star) \mid y] = k_\star^\top K_\sigma^{-1} y, \qquad \mathrm{Var}[f(x^\star) \mid y] = k(x^\star, x^\star) - k_\star^\top K_\sigma^{-1} k_\star , and the log marginal likelihood is \log p(y) = -\tfrac12\, y^\top K_\sigma^{-1} y - \tfrac12 \log\det K_\sigma - \tfrac{n}{2}\log 2\pi .

Proof. The vector (f(x^\star), y) is Gaussian, with \mathrm{Cov}(f(x^\star), y) = k_\star^\top and \mathrm{Var}(y) = K_\sigma. Apply Proposition 0.2. ∎

The posterior mean is the kernel ridge regression predictor with n\lambda = \sigma^2, studied in Kernel Methods for Machine Learning. The posterior variance does not depend on y. Exact inference costs O(n^3), through a Cholesky factorization. The code fits a GP to 30 points with a gap in (-1, 1) and compares length-scales by marginal likelihood:

import numpy as np

rng = np.random.default_rng(0)
x = np.concatenate([rng.uniform(-3, -1, 15), rng.uniform(1, 3, 15)])
y = np.sin(2 * x) + 0.1 * rng.normal(size=x.size)
noise = 0.1**2

def k(a, b, ell):
    return np.exp(-(a[:, None] - b[None, :]) ** 2 / (2 * ell**2))

def gp(ell, xs):
    K = k(x, x, ell) + noise * np.eye(x.size)
    L = np.linalg.cholesky(K)
    a = np.linalg.solve(L.T, np.linalg.solve(L, y))
    lml = -0.5 * y @ a - np.log(np.diag(L)).sum() - 0.5 * x.size * np.log(2 * np.pi)
    Ks = k(xs, x, ell)
    v = np.linalg.solve(L, Ks.T)
    sd = np.sqrt(1 - (v**2).sum(0) + noise)          # predictive sd of a new observation
    return lml, Ks @ a, sd

xs = np.array([-2.0, 0.0, 6.0])
for ell in [0.1, 0.3, 0.6, 1.0, 3.0]:
    lml, mean, sd = gp(ell, xs)
    print(f"ell={ell}: log marginal lik. {lml:7.2f}  sd at x=-2, 0, 6: {np.round(sd, 2)}")

The marginal likelihood is largest at \ell = 0.6 (8.41, against 7.24 at \ell = 1 and −271.6 at \ell = 3). With \ell = 0.6, the predictive standard deviation is 0.13 among the data, close to the noise level 0.1, then 0.88 in the gap and 1.00 far away, where the prior takes over. The over-smooth \ell = 3 gives 0.11 in the gap: confidently wrong.

Before trusting a model, check it: simulate replicated data sets from the posterior predictive and compare a statistic of interest with its observed value (Box, 1980; Gelman, Meng and Stern, 1996).

Key takeaways — chapter 3

  • Bayesian linear regression: Gaussian posterior, ridge as its mean, predictive variance = noise + parameter uncertainty.
  • The evidence trades fit against complexity and selects models from training data, but needs proper priors.
  • Laplace: a Gaussian at the mode; BIC is its crude version. Moderation shrinks predictions towards 1/2 where the posterior is uncertain.
  • Gaussian processes: closed-form posteriors on functions, hyperparameters by marginal likelihood.

4. Bayesian unsupervised learning

Unsupervised learning looks for structure that is not observed: clusters, low-dimensional factors, topics. The Bayesian version writes a generative model with latent variables and computes their posterior. Conjugacy makes the conditional distributions simple, and the Gibbs sampler exploits it.

Mixtures and the Gibbs sampler

Definition 4.1 — Bayesian finite Gaussian mixture For K components, n observations and a known variance \sigma^2: w \sim \mathrm{Dir}(a_0, \dots, a_0), \qquad \mu_k \sim \mathcal{N}(0, s_0^2), \qquad z_i \mid w \sim \mathrm{Cat}(w), \qquad x_i \mid z_i, \mu \sim \mathcal{N}(\mu_{z_i}, \sigma^2). The allocations z_i are latent; the posterior is a distribution over (w, \mu, z).

The Probabilistic Graphical Models course fits this model by EM, which returns one maximizer of the likelihood. The Bayesian treatment keeps the whole posterior, and the simplest way to explore it is to update one block of variables at a time.

Definition 4.2 — Gibbs sampler For a target \pi(\theta_1, \dots, \theta_m) split into blocks, a systematic-scan Gibbs sweep replaces each block \theta_j in turn by a draw from its full conditional distribution \pi(\theta_j \mid \theta_{-j}).

Proposition 4.3 — Gibbs updates preserve the target Each block update leaves \pi invariant, and so does a full sweep.

Proof. If \theta \sim \pi, the block \theta_{-j} has its marginal law \pi(\theta_{-j}). Drawing \theta_j' \sim \pi(\cdot \mid \theta_{-j}) produces the pair (\theta_j', \theta_{-j}) with law \pi(\theta_{-j})\, \pi(\theta_j' \mid \theta_{-j}) = \pi(\theta_j', \theta_{-j}) . A composition of \pi-invariant kernels is \pi-invariant. ∎

Invariance is not enough: the chain must also be irreducible, which holds here because all conditionals have full support. The ergodic theorem (Theorem 0.10) then justifies the averages.

Proposition 4.4 — Full conditionals of the mixture With n_k the number of i such that z_i = k:

  • allocations, independently over i: p(z_i = k \mid w, \mu, x) \propto w_k\, \mathcal{N}(x_i;\, \mu_k, \sigma^2) ;
  • weights: w \mid z \sim \mathrm{Dir}(a_0 + n_1, \dots, a_0 + n_K);
  • means: \mu_k \mid z, x \sim \mathcal{N}(m_k, v_k), independently over k, with v_k = \Big(\frac{1}{s_0^2} + \frac{n_k}{\sigma^2}\Big)^{-1}, \qquad m_k = \frac{v_k}{\sigma^2} \sum_{i : z_i = k} x_i .

Proof. Each full conditional is proportional to the joint density seen as a function of the block. The Dirichlet prior is conjugate to the categorical allocations, and the Gaussian prior on \mu_k to the observations allocated to k (Example 0.6). ∎

The code runs this sampler on 300 points from three components with means -4, 0, 3 and weights 0.3, 0.5, 0.2:

import numpy as np

rng = np.random.default_rng(0)
true_mu, true_w = np.array([-4.0, 0.0, 3.0]), np.array([0.3, 0.5, 0.2])
z_true = rng.choice(3, size=300, p=true_w)
x = rng.normal(true_mu[z_true], 1.0)                 # known unit variance

K, s0, a0 = 3, 10.0, 1.0                              # mu_k ~ N(0, s0^2), w ~ Dir(a0, ..., a0)
mu, w = rng.normal(0, 1, K), np.full(K, 1 / K)
draws = []
for it in range(2000):
    # 1. allocations: p(z_i = k | ...) proportional to w_k N(x_i; mu_k, 1)
    logp = np.log(w) - 0.5 * (x[:, None] - mu[None, :]) ** 2
    p = np.exp(logp - logp.max(1, keepdims=True))
    p /= p.sum(1, keepdims=True)
    z = (p.cumsum(1) > rng.uniform(size=(x.size, 1))).argmax(1)
    n_k = np.bincount(z, minlength=K)
    # 2. weights: Dirichlet(a0 + n_k)
    w = rng.dirichlet(a0 + n_k)
    # 3. means: Gaussian, precision 1/s0^2 + n_k, mean (sum of x in k) / precision
    prec = 1 / s0**2 + n_k
    mu = rng.normal(np.bincount(z, weights=x, minlength=K) / prec, 1 / np.sqrt(prec))
    if it >= 500:
        order = np.argsort(mu)                         # relabel by sorted means
        draws.append(np.concatenate([mu[order], w[order]]))
d = np.array(draws)
print("posterior mean of (mu_1, mu_2, mu_3):", d[:, :3].mean(0).round(2))
print("posterior sd   of (mu_1, mu_2, mu_3):", d[:, :3].std(0).round(2))
print("posterior mean of (w_1, w_2, w_3):  ", d[:, 3:].mean(0).round(2))

The posterior means of the component means are (-4.08, 0.02, 2.88), with standard deviations 0.12 to 0.16. The weights come out as (0.25, 0.48, 0.27): they match the proportions actually drawn in this sample, (0.253, 0.483, 0.263), rather than the generating weights.

Label switching

Proposition 4.5 — Symmetry of the mixture posterior If the prior is the same for every component, the posterior is invariant under every permutation of the labels. In particular, the posterior means \mathbb{E}[\mu_k \mid x] are all equal.

Proof. Permuting the labels simultaneously in z, w and \mu leaves the joint density p(x, z, w, \mu) unchanged, so the posterior inherits the symmetry. Coordinates that are exchangeable under the posterior have the same marginal law, hence the same mean. ∎

So a sampler that explores the whole posterior gives useless component-wise averages: each average is the mean of all components. The code sorts the means at each iteration, an identifiability constraint that is harmless here because the components are well separated. In general one relabels the draws (Stephens, 2000) or reports label-free quantities: the predictive density, or the co-clustering probabilities P(z_i = z_j \mid x).

The Gibbs sampler above never switches labels, because crossing between the symmetric modes requires moving many allocations at once. This is a failure to mix that happens to be convenient (Celeux, Hurn and Robert, 2000).

The number of components K can be chosen by the evidence, estimated with the methods of ch. 5. Alternatively, take K large with a small a_0, below half the dimension of a component’s parameter (here a_0 < 1/2): Rousseau and Mengersen (2011) show that the posterior then empties the superfluous components. Ch. 7 removes the choice altogether, with infinitely many components.

Probabilistic and Bayesian PCA

Definition 4.6 — Probabilistic PCA (Tipping and Bishop, 1999) With W \in \mathbb{R}^{p \times q}, z_i \sim \mathcal{N}(0, I_q) and x_i \mid z_i \sim \mathcal{N}(W z_i + \mu, \sigma^2 I_p), the marginal law of x_i is x_i \sim \mathcal{N}\big(\mu,\; W W^\top + \sigma^2 I_p\big).

Proposition 4.7 — Maximum likelihood and latent posterior Let U_q hold the q leading eigenvectors of the sample covariance and \Lambda_q the matching eigenvalues. The maximum-likelihood estimates (Tipping and Bishop, 1999) are \hat W = U_q (\Lambda_q - \hat\sigma^2 I)^{1/2} R, \qquad \hat\sigma^2 = \text{mean of the } p - q \text{ smallest eigenvalues}, for any rotation R. Given x_i, the latent vector is Gaussian (Proposition 0.3), with M = W^\top W + \sigma^2 I_q: z_i \mid x_i \sim \mathcal{N}\big(M^{-1} W^\top (x_i - \mu),\; \sigma^2 M^{-1}\big).

Bayesian PCA (Bishop, 1999) puts a prior \mathcal{N}(0, \alpha_j^{-1} I_p) on each column of W and fits the precisions \alpha_j by evidence maximization. Columns not supported by the data get \alpha_j \to \infty and are switched off. This automatic relevance determination selects the latent dimension.

Topic models

Definition 4.8 — Latent Dirichlet allocation (Blei, Ng and Jordan, 2003) There are K topics, each a distribution \beta_k \sim \mathrm{Dir}(\eta) over a vocabulary of V words.

Each document d draws topic proportions \theta_d \sim \mathrm{Dir}(\alpha). Each word position n of document d draws a topic z_{dn} \sim \mathrm{Cat}(\theta_d), then a word w_{dn} \sim \mathrm{Cat}(\beta_{z_{dn}}).

Proposition 4.9 — Collapsed Gibbs sampler for LDA (Griffiths and Steyvers, 2004) Integrate out \theta and \beta.

Define three counts:

  • n_{dk}, the number of words of document d assigned to topic k;
  • n_{kv}, the number of occurrences of word v assigned to topic k;
  • n_k, the total number of words assigned to topic k.

A superscript - means that position dn is excluded from the counts. With v = w_{dn}, p(z_{dn} = k \mid z_{-dn}, w) \propto \big(n_{dk}^{-} + \alpha\big)\, \frac{n_{kv}^{-} + \eta}{n_{k}^{-} + V\eta} .

Proof. For a Dirichlet–multinomial pair, the marginal probability of counts c is a ratio of multivariate Beta functions, B(\alpha + c)/B(\alpha). Adding one count to coordinate k multiplies it by (c_k + \alpha_k)/(\sum_j c_j + \sum_j \alpha_j).

Apply this to the document–topic counts and to the topic–word counts. The document-side denominator does not depend on k and drops out. ∎

Key takeaways — chapter 4

  • Latent-variable models become conditionally conjugate once the latent variables are included; the Gibbs sampler alternates their full conditionals and preserves the posterior.
  • Mixture posteriors are symmetric under relabelling: report label-free summaries or relabel.
  • Probabilistic PCA has a closed-form maximum-likelihood solution; Bayesian PCA selects the dimension by automatic relevance determination.
  • Collapsing conjugate parameters (LDA) gives samplers on discrete allocations only.

5. Bayesian computation I: advanced Monte Carlo

Posterior expectations are integrals in high dimension against a density known up to a constant. Monte Carlo methods replace them by averages over samples. This chapter goes beyond the Gibbs sampler: importance sampling and its curse of dimensionality, Metropolis–Hastings, gradient-based samplers, diagnostics, and sequential Monte Carlo, which also estimates the evidence.

Throughout, the target is \pi = \gamma / Z, where \gamma(\theta) = p(x \mid \theta)\, p(\theta) can be evaluated and Z = p(x) is unknown.

Importance sampling

Proposition 5.1 — Importance sampling Let \theta_1, \dots, \theta_N be i.i.d. from a proposal q that is positive wherever \gamma is, and let w_i = \gamma(\theta_i)/q(\theta_i). Then \hat Z = \frac1N \sum_{i=1}^N w_i \;\text{ is unbiased for } Z, \qquad \hat I = \frac{\sum_i w_i\, f(\theta_i)}{\sum_i w_i} \xrightarrow[N \to \infty]{\text{a.s.}} \mathbb{E}_\pi[f] .

Proof. First, \mathbb{E}_q[\gamma/q] = \int \gamma = Z. For \hat I, the strong law of large numbers sends the numerator divided by N to \int f \gamma = Z\, \mathbb{E}_\pi[f], and the denominator divided by N to Z. ∎

The effective sample size (\sum_i w_i)^2 / \sum_i w_i^2, between 1 and N, measures how many draws effectively carry the estimate.

Example 5.2 — The curse of dimensionality Take the target \mathcal{N}(0, I_d) and the proposal \mathcal{N}(0, 2 I_d), wider than the target and centred on it.

  • In one dimension, the normalized weights satisfy \mathbb{E}_q[w^2] = 2/\sqrt{3}; in dimension d the factors multiply.
  • The effective sample size is therefore about N \big(\sqrt{3}/2\big)^d , that is 7.5 \times 10^{-4} N for d = 50 and 5.7 \times 10^{-7} N for d = 100.

Independent proposals fail in high dimension. Markov chains move locally instead.

Metropolis–Hastings

Algorithm 5.3 — Metropolis–Hastings From the current state \theta, propose \theta' \sim q(\theta, \cdot) and accept it with probability \alpha(\theta, \theta') = \min\Big(1,\; \frac{\gamma(\theta')\, q(\theta', \theta)}{\gamma(\theta)\, q(\theta, \theta')}\Big); otherwise stay at \theta. Only ratios of \gamma appear, so Z is never needed.

Theorem 5.4 — Metropolis–Hastings is reversible The Metropolis–Hastings kernel satisfies detailed balance with respect to \pi, so \pi is invariant.

Proof. For \theta' \neq \theta, the kernel has density q(\theta, \theta')\, \alpha(\theta, \theta'), and \pi(\theta)\, q(\theta, \theta')\, \alpha(\theta, \theta') = \frac{1}{Z}\min\big(\gamma(\theta)\, q(\theta, \theta'),\; \gamma(\theta')\, q(\theta', \theta)\big), which is symmetric in (\theta, \theta'). The rejection part is a point mass at \theta, symmetric on the diagonal. Definition 0.9 concludes. ∎

Key formula — the Metropolis–Hastings ratio \alpha(\theta, \theta') = \min\Big(1,\; \frac{\gamma(\theta')\, q(\theta', \theta)}{\gamma(\theta)\, q(\theta, \theta')}\Big)

For the random-walk proposal \theta' = \theta + h\xi, with \xi standard Gaussian, on product targets in dimension d, the optimal step is of order d^{-1/2} and the optimal acceptance rate is 0.234 (Roberts, Gelman and Gilks, 1997). The chain then needs of order d iterations to move across the target.

Langevin and Hamiltonian samplers

The Langevin diffusion d\theta_t = \frac12 \nabla \log \pi(\theta_t)\, dt + dB_t has \pi as invariant distribution: for smooth compactly supported f, an integration by parts gives \int \Big(\tfrac12 \nabla\log\pi \cdot \nabla f + \tfrac12 \Delta f\Big)\, \pi \;=\; \tfrac12 \int \nabla\pi \cdot \nabla f - \tfrac12 \int \nabla \pi \cdot \nabla f = 0 . Its Euler discretization with step h^2 is the unadjusted Langevin algorithm (ULA): \theta_{k+1} = \theta_k + \frac{h^2}{2} \nabla \log\gamma(\theta_k) + h\, \xi_k .

ULA is biased: for a fixed step, its invariant law is not \pi. Using the same move as a Metropolis–Hastings proposal removes the bias: this is MALA. Its optimal step is of order d^{-1/6}, with acceptance rate 0.574 (Roberts and Rosenthal, 1998). For strongly log-concave targets, ULA has explicit non-asymptotic error bounds (Dalalyan, 2017; Durmus and Moulines, 2017). The diffusions themselves are studied in Stochastic Calculus in Machine Learning.

Hamiltonian Monte Carlo (HMC) adds a momentum p \sim \mathcal{N}(0, I) and the energy H(\theta, p) = -\log\gamma(\theta) + \frac12 \|p\|^2. The Hamiltonian flow preserves H and volume, so it can travel far along a level set of the joint density. It is integrated by the leapfrog scheme with step \varepsilon: p_{1/2} = p + \tfrac{\varepsilon}{2}\nabla\log\gamma(\theta), \qquad \theta' = \theta + \varepsilon\, p_{1/2}, \qquad p' = p_{1/2} + \tfrac{\varepsilon}{2}\nabla\log\gamma(\theta').

Proposition 5.5 — Properties of the leapfrog map Let \Psi be L leapfrog steps and F(\theta, p) = (\theta, -p) the momentum flip. Then \Psi preserves volume, and F \circ \Psi is an involution: applying it twice gives the identity.

Proof. Each of the three updates adds to one variable a function of the other, a shear with Jacobian determinant 1, so the composition preserves volume. Running the updates with the momentum reversed undoes them in reverse order, because the scheme is symmetric; hence F \circ \Psi \circ F \circ \Psi is the identity. ∎

Theorem 5.6 — Hamiltonian Monte Carlo is exact Draw p \sim \mathcal{N}(0, I), compute (\theta', p') = F\circ\Psi(\theta, p), and accept \theta' with probability \min\big(1, e^{H(\theta, p) - H(\theta', p')}\big). This kernel leaves \pi invariant.

Proof sketch. Metropolis–Hastings with a deterministic proposal that is a volume-preserving involution satisfies detailed balance, with the acceptance ratio above: the Jacobian is 1. Resampling the momentum is a Gibbs step for the joint law \pi(\theta)\,\mathcal{N}(p; 0, I). Both steps preserve that law, whose \theta-marginal is \pi.

The leapfrog energy error is O(\varepsilon^2) over a trajectory of fixed length, so long moves are accepted with high probability; the optimal step scales as d^{-1/4} (Beskos et al., 2013). The No-U-Turn sampler (Hoffman and Gelman, 2014), used by Stan, chooses the trajectory length adaptively.

The code compares the three samplers on a 50-dimensional Gaussian whose standard deviations range from 0.1 to 1, with steps tuned to the usual acceptance rates. It reports the effective sample size of the widest coordinate.

import numpy as np

rng = np.random.default_rng(0)
d = 50
sd = np.linspace(0.1, 1.0, d)                  # target N(0, diag(sd^2)), condition number 100
logpi = lambda x: -0.5 * np.sum((x / sd) ** 2)
grad = lambda x: -x / sd**2

def ess(chain):                                # sum autocorrelations until the first negative one
    c = chain - chain.mean()
    f = np.fft.rfft(c, 2 * c.size)
    acf = np.fft.irfft(f * np.conj(f))[:c.size] / (c.var() * c.size)
    tau = 1 + 2 * np.sum(acf[1:np.argmax(acf < 0)])
    return c.size / tau

def rwmh(h, n):
    x, out, acc = np.zeros(d), [], 0
    for _ in range(n):
        y = x + h * rng.normal(size=d)
        if np.log(rng.uniform()) < logpi(y) - logpi(x):
            x, acc = y, acc + 1
        out.append(x[-1])
    return np.array(out), acc / n

def mala(h, n):
    x, out, acc = np.zeros(d), [], 0
    logq = lambda b, a: -np.sum((b - a - 0.5 * h**2 * grad(a)) ** 2) / (2 * h**2)
    for _ in range(n):
        y = x + 0.5 * h**2 * grad(x) + h * rng.normal(size=d)
        if np.log(rng.uniform()) < logpi(y) + logq(x, y) - logpi(x) - logq(y, x):
            x, acc = y, acc + 1
        out.append(x[-1])
    return np.array(out), acc / n

def hmc(eps, L, n):
    x, out, acc = np.zeros(d), [], 0
    for _ in range(n):
        p0 = rng.normal(size=d)
        q, p = x.copy(), p0 + 0.5 * eps * grad(x)          # leapfrog integrator
        for i in range(L):
            q = q + eps * p
            p = p + (eps if i < L - 1 else 0.5 * eps) * grad(q)
        if np.log(rng.uniform()) < logpi(q) - 0.5 * p @ p - logpi(x) + 0.5 * p0 @ p0:
            x, acc = q, acc + 1
        out.append(x[-1])
    return np.array(out), acc / n

n = 10000
for name, (ch, acc), grads in [("RWMH h=0.1", rwmh(0.1, n), 0),
                               ("MALA h=0.16", mala(0.16, n), 1),
                               ("HMC eps=0.08, L=20", hmc(0.08, 20, n), 20)]:
    e = ess(ch[n // 10:])
    print(f"{name:20s} acceptance {acc:.2f}   ESS of x_50 per 1000 iterations {1000 * e / (0.9 * n):6.1f}"
          f"   gradients per iteration {grads}")

The acceptance rates are 0.27, 0.56 and 0.93. Per 1000 iterations, the effective sample sizes are about 1 for the random walk, 3 for MALA and 900 for HMC. Even counted per gradient evaluation, HMC gives about 45 effective draws per 1000 gradients, against 2.6 for MALA. The small scales force small steps, and only HMC turns them into long moves.

This comparison flatters HMC a little. Its trajectory length \varepsilon L = 1.6 is close to \pi/2, a quarter of the oscillation period of the unit-scale coordinate, where the exact Hamiltonian flow returns an independent draw. With L between 10 and 40, HMC gives about 17 to 45 effective draws per 1000 gradients. The tuning matters, but HMC stays far ahead of MALA; the No-U-Turn sampler chooses L automatically.

Diagnostics

Definition 5.7 — Autocorrelation time and effective sample size For a stationary chain and a function f with lag-k autocorrelations \rho_k, the integrated autocorrelation time and the effective sample size of T iterations are \tau_f = 1 + 2 \sum_{k \geq 1} \rho_k, \qquad \mathrm{ESS} = T / \tau_f . Under a Markov chain central limit theorem, the variance of the ergodic average is about \mathrm{Var}_\pi(f)\, \tau_f / T.

The \hat R statistic (Gelman and Rubin, 1992; Vehtari et al., 2021) runs several chains from dispersed starting points and compares between-chain and within-chain variances; values above 1.01 signal trouble. No diagnostic proves convergence: they can only reveal its failure, as the label-switching example of ch. 4 shows.

Sequential Monte Carlo and the evidence

Algorithm 5.8 — Tempered sequential Monte Carlo Choose temperatures 0 = \lambda_0 < \lambda_1 < \dots < \lambda_T = 1 and the intermediate targets \gamma_t(\theta) = p(\theta)\, p(x \mid \theta)^{\lambda_t} . Start from N prior draws with equal weights. For t = 1, \dots, T:

  1. reweight: multiply each weight by p(x \mid \theta_i)^{\lambda_t - \lambda_{t-1}}, and record the weighted mean of these factors, \hat r_t;
  2. resample the particles with probabilities proportional to their weights when the effective sample size falls below N/2, and reset the weights;
  3. move each particle with a few MCMC steps that leave \gamma_t invariant, such as MALA or HMC.

The product \hat r_1 \cdots \hat r_T is an unbiased estimator of the evidence Z = p(x), and it is consistent as N \to \infty (Del Moral, Doucet and Jasra, 2006). Temperatures are usually chosen adaptively, so that each step keeps a fixed fraction of effective particles. This gives the evidence that ch. 3 and ch. 4 needed for model choice. Annealed importance sampling (Neal, 2001) is the same scheme without resampling; Chopin and Papaspiliopoulos (2020) give a full treatment.

When n is large, each evaluation of \gamma costs O(n). Bardenet, Doucet and Holmes (2017) review subsampling MCMC: naive subsampling destroys the invariant distribution, and exact methods need good control variates. Stochastic-gradient Langevin dynamics, in ch. 8, trades exactness for speed.

Key takeaways — chapter 5

  • Importance sampling estimates the evidence without bias but collapses in high dimension.
  • Metropolis–Hastings is reversible for any proposal; random walks need O(d) steps.
  • Gradients help: MALA corrects the bias of Langevin steps, and HMC makes long, accepted moves with the leapfrog integrator.
  • Measure efficiency by effective sample size per gradient, and run several chains.
  • Tempered SMC samples the posterior and estimates the evidence.

6. Bayesian computation II: variational methods

Monte Carlo is exact in the limit but can be slow. Variational inference (VI) turns inference into optimization: choose a family \mathcal{Q} of tractable distributions and find its member closest to the posterior. VI scales to large data and models, at the price of a bias that this chapter makes precise.

The evidence lower bound

Proposition 6.1 — The ELBO identity For every density q that is positive only where the posterior is, \log p(x) = \underbrace{\mathbb{E}_q[\log p(x, \theta)] - \mathbb{E}_q[\log q(\theta)]}_{\mathrm{ELBO}(q)} \;+\; \mathrm{KL}\big(q \,\|\, p(\cdot \mid x)\big).

Proof. For every \theta, \log p(x) = \log p(x, \theta) - \log p(\theta \mid x). Take the expectation under q, then add and subtract \mathbb{E}_q[\log q(\theta)]. ∎

Key formula — the evidence lower bound \log p(x) = \mathrm{ELBO}(q) + \mathrm{KL}\big(q \,\|\, p(\cdot \mid x)\big) \;\geq\; \mathrm{ELBO}(q)

Three consequences follow. The ELBO is a lower bound on the log evidence (Proposition 0.8). Maximizing it over q is the same as minimizing the divergence to the posterior. And neither requires p(x).

Mean field and coordinate ascent

The mean-field family contains the product densities q(\theta) = \prod_j q_j(\theta_j) over blocks of variables.

Theorem 6.2 — Coordinate ascent update (CAVI) With all factors but q_j held fixed, the ELBO is maximized by q_j^\star(\theta_j) \propto \exp\Big(\mathbb{E}_{-j}\big[\log p(x, \theta)\big]\Big), where \mathbb{E}_{-j} is the expectation over the other blocks under \prod_{i \neq j} q_i.

Proof. As a function of q_j, the ELBO equals \int q_j(\theta_j)\, \mathbb{E}_{-j}[\log p(x, \theta)]\, d\theta_j - \int q_j \log q_j + \text{const} = -\mathrm{KL}(q_j \,\|\, q_j^\star) + \text{const}, since \log q_j^\star = \mathbb{E}_{-j}[\log p(x, \theta)] minus a constant. By Proposition 0.8 the maximum is reached at q_j = q_j^\star. ∎

Cycling through the blocks never decreases the ELBO, and converges to a local optimum. The update has the same shape as a Gibbs conditional, with random neighbours replaced by expectations.

Example 6.3 — Mean field on a Gaussian Take the target \mathcal{N}(\mu, \Lambda^{-1}) in two dimensions, a stand-in for a posterior. As a function of \theta_1, the expected log density is quadratic with coefficient -\frac12\Lambda_{11}, so CAVI gives q_1 = \mathcal{N}\big(\mu_1 - \Lambda_{11}^{-1}\Lambda_{12}(m_2 - \mu_2),\; \Lambda_{11}^{-1}\big), where m_2 is the current mean of q_2, and symmetrically for q_2. At the fixed point the means are exact, m = \mu, and the variances are 1/\Lambda_{jj}.

Proposition 6.4 — Mean field underestimates variances In Example 6.3, in any dimension, \frac{1}{\Lambda_{jj}} = \mathrm{Var}(\theta_j \mid \theta_{-j}) \leq \Sigma_{jj} , with equality if and only if \theta_j is uncorrelated with the other coordinates.

Proof. By the Schur complement formula, 1/\Lambda_{jj} = \Sigma_{jj} - \Sigma_{j,-j}\Sigma_{-j,-j}^{-1}\Sigma_{-j,j}, which is the conditional variance of Proposition 0.2. The subtracted term is a non-negative quadratic form, zero exactly when \Sigma_{j,-j} = 0. ∎

With unit variances and correlation \rho = 0.9, the mean-field variance is 1 - \rho^2 = 0.19: a standard deviation of 0.44 instead of 1. The reverse KL penalizes mass of q where the posterior has little, so it prefers to sit inside the posterior. Minimizing \mathrm{KL}(p \,\|\, q) over the same family gives the exact marginals instead (Exercise 10).

Example 6.5 — CAVI for the mixture of ch. 4 Take Definition 4.1 with equal fixed weights 1/K and \sigma = 1, and the family q(\mu_k) = \mathcal{N}(m_k, s_k^2), q(z_i) = \mathrm{Cat}(\varphi_i) (Blei, Kucukelbir and McAuliffe, 2017). Theorem 6.2 gives the updates \varphi_{ik} \propto \exp\Big(m_k x_i - \tfrac12\big(m_k^2 + s_k^2\big)\Big), \qquad s_k^2 = \Big(\frac{1}{s_0^2} + \sum_i \varphi_{ik}\Big)^{-1}, \qquad m_k = s_k^2 \sum_i \varphi_{ik}\, x_i . Compare with Proposition 4.4: allocation counts become expected counts, and means become expected means.

In conditionally conjugate exponential-family models, the CAVI update of a global parameter adds the expected sufficient statistics of all data points to the prior’s natural parameter. Stochastic VI (Hoffman, Blei, Wang and Paisley, 2013) estimates this sum from a minibatch, scaled by n over the batch size, and moves part of the way with a decreasing step. The resulting step is a stochastic natural-gradient step on the ELBO, which scales VI to millions of documents.

Black-box and reparameterized VI

For non-conjugate models, choose a parametric family q_\phi and maximize \mathrm{ELBO}(\phi) by stochastic gradient ascent. Two unbiased gradient estimators exist.

Proposition 6.6 — Two gradient estimators

  • Score function (Ranganath, Gerrish and Blei, 2014): \nabla_\phi \mathrm{ELBO} = \mathbb{E}_{q_\phi}\big[\nabla_\phi \log q_\phi(\theta)\, \big(\log p(x, \theta) - \log q_\phi(\theta)\big)\big] .
  • Reparameterization (Kingma and Welling, 2014; Rezende, Mohamed and Wierstra, 2014): if \theta = T_\phi(\varepsilon) with \varepsilon \sim r independent of \phi, then \nabla_\phi \mathrm{ELBO} = \mathbb{E}_{\varepsilon \sim r}\Big[\nabla_\phi \big(\log p(x, T_\phi(\varepsilon)) - \log q_\phi(T_\phi(\varepsilon))\big)\Big] .

Proof. Score function: differentiate \int q_\phi\, g_\phi with g_\phi = \log p - \log q_\phi, using \nabla q_\phi = q_\phi \nabla \log q_\phi. The extra term \mathbb{E}_q[\nabla g_\phi] equals -\mathbb{E}_q[\nabla \log q_\phi], which is -\nabla \int q_\phi = 0.

Reparameterization: write the ELBO as an expectation over \varepsilon, whose law does not depend on \phi, and differentiate under the integral. ∎

The reparameterization estimator usually has a much smaller variance, but it needs continuous parameters and a differentiable model. For q = \mathcal{N}(m, \mathrm{diag}(e^{2s})), take T(\varepsilon) = m + e^{s} \odot \varepsilon; the entropy of q is \sum_j s_j plus a constant.

The code fits this mean-field Gaussian to the posterior of a two-parameter Bayesian logistic regression with strongly correlated features, and compares it with the exact posterior computed on a grid:

import numpy as np
import torch

torch.set_num_threads(1)
torch.manual_seed(0)
rng = np.random.default_rng(0)
n = 40
X = rng.normal(size=(n, 2))
X[:, 1] = 0.9 * X[:, 0] + 0.45 * X[:, 1]              # correlated features
y = (rng.uniform(size=n) < 1 / (1 + np.exp(-X @ np.array([1.5, -1.0])))).astype(float)
Xt, yt = torch.tensor(X), torch.tensor(y)

def log_joint(w):                                       # w: (S, 2); prior N(0, 4 I)
    logits = w @ Xt.T
    loglik = (yt * logits - torch.nn.functional.softplus(logits)).sum(1)
    return loglik - (w**2).sum(1) / 8

# exact posterior moments on a grid (feasible in two dimensions)
g = torch.linspace(-8, 8, 401, dtype=torch.float64)
W = torch.cartesian_prod(g, g)
p = torch.softmax(log_joint(W), 0)
m_exact = (p[:, None] * W).sum(0)
sd_exact = ((p[:, None] * (W - m_exact) ** 2).sum(0)).sqrt()

# mean-field Gaussian q(w) = N(m, diag(exp(2 s))), reparameterization gradient of the ELBO
m = torch.zeros(2, dtype=torch.float64, requires_grad=True)
s = torch.zeros(2, dtype=torch.float64, requires_grad=True)
opt = torch.optim.Adam([m, s], lr=0.05)
for step in range(3000):
    eps = torch.randn(64, 2, dtype=torch.float64)
    w = m + eps * s.exp()
    elbo = log_joint(w).mean() + s.sum()               # entropy of q up to a constant
    opt.zero_grad(); (-elbo).backward(); opt.step()
print("posterior mean  exact", m_exact.numpy().round(2), "  VI", m.detach().numpy().round(2))
print("posterior sd    exact", sd_exact.numpy().round(2), "  VI", s.exp().detach().numpy().round(2))
corr = (p * (W[:, 0] - m_exact[0]) * (W[:, 1] - m_exact[1])).sum() / sd_exact.prod()
print("exact posterior correlation", round(corr.item(), 2))

The means agree: (0.30, 0.01) exactly, (0.31, 0.05) by VI. The exact posterior correlation is −0.89, and the VI standard deviations (0.37, 0.33) are half the exact ones, (0.74, 0.68). For a Gaussian with this correlation, Proposition 6.4 predicts the ratio \sqrt{1 - 0.89^2} = 0.46; the posterior is not exactly Gaussian, and the observed ratios are 0.50 and 0.49.

Amortized inference learns a map from each data point to its variational parameters, as in variational auto-encoders, treated in the Probabilistic Graphical Models course. Whatever the algorithm, check a variational fit before trusting it. The Pareto diagnostic of Yao, Vehtari, Simpson and Gelman (2018) fits a generalized Pareto tail to the importance weights p(x, \theta)/q(\theta), \theta \sim q; a shape estimate above 0.7 flags an unreliable approximation. Ch. 9 discusses expectation propagation and the theory of variational Bayes.

Key takeaways — chapter 6

  • The log evidence is the ELBO plus the divergence from q to the posterior: maximizing the ELBO fits q without knowing p(x).
  • CAVI sets each factor to the exponentiated expected log joint; in conjugate models this is closed-form and stochastic VI scales it.
  • Mean field gets means right and variances too small, by the factor of Proposition 6.4 for Gaussians.
  • Reparameterization gradients make VI black-box for differentiable models.

7. Bayesian nonparametrics

Parametric models fix their complexity before seeing the data. Bayesian nonparametric models put priors on infinite-dimensional objects, such as distributions or functions, and let the posterior decide how much complexity the data support. The Gaussian process of ch. 3 is one cornerstone; the Dirichlet process is the other.

The Dirichlet process

Proposition 7.1 — Aggregation property of the Dirichlet law If (W_1, \dots, W_k) \sim \mathrm{Dir}(a_1, \dots, a_k), merging two coordinates gives a Dirichlet vector with summed parameters: (W_1 + W_2, W_3, \dots, W_k) \sim \mathrm{Dir}(a_1 + a_2, a_3, \dots, a_k).

Proof. Represent W_j = G_j / \sum_i G_i with independent G_j \sim \mathrm{Gamma}(a_j, 1), and use that G_1 + G_2 \sim \mathrm{Gamma}(a_1 + a_2, 1). ∎

Definition 7.2 — Dirichlet process (Ferguson, 1973) Let \alpha > 0 and G_0 be a probability measure on a space \mathcal{X}.

A random probability measure G is a Dirichlet process \mathrm{DP}(\alpha, G_0) if, for every finite measurable partition (A_1, \dots, A_k) of \mathcal{X}, \big(G(A_1), \dots, G(A_k)\big) \sim \mathrm{Dir}\big(\alpha G_0(A_1), \dots, \alpha G_0(A_k)\big).

Proposition 7.1 makes these finite-dimensional laws consistent with each other under merging of cells; a Kolmogorov-type argument, or the explicit construction of Theorem 7.7, gives existence. The base measure G_0 is the mean, and the concentration \alpha is a precision.

Proposition 7.3 — Moments For every measurable set A, \mathbb{E}[G(A)] = G_0(A), \qquad \mathrm{Var}[G(A)] = \frac{G_0(A)\,(1 - G_0(A))}{1 + \alpha} .

Proof. The partition (A, A^c) gives G(A) \sim \mathrm{Beta}\big(\alpha G_0(A),\; \alpha(1 - G_0(A))\big). Use the mean a/(a+b) and the variance ab/((a+b)^2(a+b+1)) of a Beta(a, b) law. ∎

Theorem 7.4 — Conjugacy If G \sim \mathrm{DP}(\alpha, G_0) and X_1, \dots, X_n are i.i.d. from G given G, then G \mid X_{1:n} \sim \mathrm{DP}\Big(\alpha + n,\; \frac{\alpha G_0 + \sum_{i=1}^n \delta_{X_i}}{\alpha + n}\Big).

Proof. Sketch for n = 1; induction gives the general case. Fix a partition (A_1, \dots, A_k). Given G, the probability that X_1 falls in A_j is G(A_j), a categorical draw with Dirichlet-distributed probabilities.

By Dirichlet–categorical conjugacy, given X_1 \in A_j the vector (G(A_1), \dots, G(A_k)) is Dirichlet with \alpha G_0(A_j) increased by 1. This is the claimed process evaluated on the partition. A full proof refines the partition around X_1 (Ghosal and van der Vaart, 2017, ch. 4). ∎

Proposition 7.5 — Pólya urn (Blackwell and MacQueen, 1973) With G integrated out, the predictive law of a new draw is X_{n+1} \mid X_{1:n} \;\sim\; \frac{\alpha}{\alpha + n}\, G_0 + \frac{1}{\alpha + n} \sum_{i=1}^n \delta_{X_i} .

Proof. Condition on G first: P(X_{n+1} \in A \mid X_{1:n}) = \mathbb{E}[G(A) \mid X_{1:n}], which is the posterior base measure of A by Theorem 7.4 and Proposition 7.3. ∎

Key formula — the Pólya urn X_{n+1} \mid X_{1:n} \sim \frac{\alpha\, G_0 + \sum_{i=1}^n \delta_{X_i}}{\alpha + n}

New draws repeat earlier values with positive probability, so G is almost surely discrete. Grouping equal values gives the Chinese restaurant process: customer n + 1 joins an existing table c of size n_c with probability n_c / (\alpha + n), and opens a new table with probability \alpha / (\alpha + n).

Example 7.6 — An urn step and the number of clusters Take \alpha = 2 and 8 observations with three distinct values, seen 4, 3 and 1 times.

  • The next draw repeats them with probabilities 0.4, 0.3 and 0.1, and is a new value from G_0 with probability 0.2.
  • More generally, with G_0 without atoms, the number K_n of distinct values increases by one at step i with probability \alpha/(\alpha + i - 1), whatever happened before. Hence \mathbb{E}[K_n] = \sum_{i=1}^n \frac{\alpha}{\alpha + i - 1} \;\sim\; \alpha \log n .
  • For \alpha = 1 and n = 150, this is 5.59.

Theorem 7.7 — Stick-breaking (Sethuraman, 1994) Let V_k \sim \mathrm{Beta}(1, \alpha) and \theta_k \sim G_0, all independent, and set \pi_k = V_k \prod_{j < k} (1 - V_j). Then G = \sum_{k=1}^\infty \pi_k\, \delta_{\theta_k} \;\sim\; \mathrm{DP}(\alpha, G_0).

Proof idea. Splitting off the first stick gives the distributional equation G = V_1\, \delta_{\theta_1} + (1 - V_1)\, G', where G' is built from the remaining sticks and has the same law as G. A Dirichlet process satisfies the same equation, by a computation on the Dirichlet laws of Definition 7.2. The equation has a unique solution in law, which proves the theorem (Sethuraman, 1994).

The mass left after K sticks is \prod_{k \leq K}(1 - V_k), with expectation (\alpha/(1+\alpha))^K by independence. For \alpha = 2, 18 sticks leave an expected mass below 10^{-3}. Truncated stick-breaking is the basis of variational algorithms for DP mixtures (Blei and Jordan, 2006).

Dirichlet process mixtures

Definition 7.8 — Dirichlet process mixture (Antoniak, 1974; Lo, 1984) Draw G \sim \mathrm{DP}(\alpha, G_0), then \theta_i \mid G \sim G and x_i \mid \theta_i \sim F(\cdot \mid \theta_i) for i = 1, \dots, n. Equivalently, x_i comes from a mixture with infinitely many components and stick-breaking weights. Ties among the \theta_i define the clusters.

Algorithm 7.9 — Collapsed Gibbs sampler (Neal, 2000) When G_0 is conjugate to F, integrate out the cluster parameters. For each i in turn, remove x_i from its cluster, then reassign it:

  • to an existing cluster c with probability proportional to n_c^{-i}\, p(x_i \mid \text{the other points of } c);
  • to a new cluster with probability proportional to \alpha \int F(x_i \mid \theta)\, G_0(d\theta).

The weights n_c^{-i} and \alpha come from the Chinese restaurant process: by exchangeability, x_i can be treated as the last customer.

The code runs this sampler on 150 points from three unit-variance Gaussians centred at -4, 0, 4, with \alpha = 1 and the base measure \mathcal{N}(0, 25) for the means:

import numpy as np

rng = np.random.default_rng(0)
x = np.concatenate([rng.normal(-4, 1, 50), rng.normal(0, 1, 70), rng.normal(4, 1, 30)])
n, alpha, tau2 = x.size, 1.0, 25.0          # components N(mu, 1), base measure mu ~ N(0, tau2)

def log_pred(xi, s, m):
    """log density of xi given m points with sum s already in the cluster (mu integrated out)."""
    prec = 1 / tau2 + m
    mean, var = s / prec, 1 + 1 / prec
    return -0.5 * (np.log(2 * np.pi * var) + (xi - mean) ** 2 / var)

z = np.zeros(n, dtype=int)                    # start with every point in one cluster
counts, big = {}, {}
for it in range(200):
    for i in range(n):
        z[i] = -1                             # remove point i from its cluster
        labels, sizes = np.unique(z[z >= 0], return_counts=True)
        sums = np.array([x[z == k].sum() for k in labels])
        logw = np.log(np.append(sizes, alpha))                    # CRP prior weights
        logw += np.append(log_pred(x[i], sums, sizes), log_pred(x[i], 0.0, 0))
        w = np.exp(logw - logw.max())
        j = rng.choice(w.size, p=w / w.sum())
        z[i] = labels[j] if j < labels.size else (labels.max() + 1 if labels.size else 0)
    if it >= 50:
        sizes = np.unique(z, return_counts=True)[1]
        counts[sizes.size] = counts.get(sizes.size, 0) + 1
        b = int((sizes >= 5).sum())                    # clusters with at least 5 points
        big[b] = big.get(b, 0) + 1
total = sum(counts.values())
print("posterior of the number of clusters:", {k: round(v / total, 2) for k, v in sorted(counts.items())})
print("clusters with at least 5 points:    ", {k: round(v / total, 2) for k, v in sorted(big.items())})
print("prior mean number of clusters, sum alpha/(alpha+i-1):", round(sum(alpha / (alpha + i) for i in range(n)), 2))

The posterior of the number of clusters is spread from 3 to 11, with mode 6 (probability 0.26) and only 0.08 on the true value 3. Counting only clusters of at least 5 points, the mode moves to 3 (probability 0.43). The extra clusters are small: the DP mixture fits the density well, but its number of clusters is not a consistent estimator of a number of components, as Miller and Harrison (2013) proved. Ch. 9 returns to this point.

Two extensions are used widely. The Pitman–Yor process (Pitman and Yor, 1997) adds a discount parameter and makes the number of clusters grow like a power of n, as word frequencies do. The hierarchical Dirichlet process (Teh, Jordan, Beal and Blei, 2006) shares atoms across groups of data, which gives topic models with an unbounded number of topics. Posterior consistency and contraction rates, the frequentist guarantees of these priors, are the subject of ch. 9.

Key takeaways — chapter 7

  • \mathrm{DP}(\alpha, G_0): Dirichlet marginals on every partition, mean G_0, precision \alpha, conjugate to i.i.d. sampling.
  • Integrating G out gives the Pólya urn and the Chinese restaurant process; about \alpha \log n clusters a priori.
  • Stick-breaking writes G as an explicit discrete measure, convenient for truncation and variational inference.
  • DP mixtures estimate densities with an unbounded number of components; their posterior number of clusters overestimates the number of components.

8. Bayesian methods for deep learning

Deep networks are trained to a single parameter vector and are often overconfident away from their training data. Bayesian deep learning puts a prior on the weights and approximates the posterior predictive. Exact inference is out of reach, so this chapter is about approximations, and about how to tell whether they work.

Definition 8.1 — Bayesian neural network A Bayesian neural network is a network f_\theta with a prior p(\theta) on its weights, often Gaussian, and a likelihood p(y \mid f_\theta(x)). Its prediction is the Bayesian model average p(y^\star \mid x^\star, \mathcal{D}) = \int p\big(y^\star \mid f_\theta(x^\star)\big)\, p(\theta \mid \mathcal{D})\, d\theta \;\approx\; \frac1S \sum_{s=1}^S p\big(y^\star \mid f_{\theta_s}(x^\star)\big), where \theta_1, \dots, \theta_S are draws from an approximate posterior.

Training with weight decay is MAP estimation under a Gaussian prior, as ridge regression is in Proposition 3.1. The Bayesian question is what the average adds to the mode.

What a prior on weights means

Theorem 8.2 — Infinite-width limit (Neal, 1996) Consider one hidden layer of width H, f(x) = b + \frac{1}{\sqrt{H}} \sum_{j=1}^H v_j\, \varphi(u_j^\top x + c_j), with all parameters independent, b \sim \mathcal{N}(0, \sigma_b^2), v_j \sim \mathcal{N}(0, \sigma_v^2), the pairs (u_j, c_j) i.i.d., and \varphi(u^\top x + c) square-integrable. As H \to \infty, the prior of f converges to a centred Gaussian process with kernel k(x, x') = \sigma_b^2 + \sigma_v^2\, \mathbb{E}\big[\varphi(u^\top x + c)\, \varphi(u^\top x' + c)\big].

Proof. Fix inputs x_1, \dots, x_m and consider the vectors Z_j = v_j\, \big(\varphi(u_j^\top x_l + c_j)\big)_{l \leq m}, \qquad j = 1, \dots, H . They are i.i.d. and centred, because v_j is centred and independent of (u_j, c_j). Their covariance is the second term of k. The multivariate central limit theorem applies to H^{-1/2}\sum_j Z_j; adding the independent Gaussian b gives the limit. ∎

For the ReLU with u \sim \mathcal{N}(0, I) and no bias, the expectation is half the arc-cosine kernel of degree 1 of Cho and Saul (2009), where \vartheta is the angle between x and x': \mathbb{E}\big[\varphi(u^\top x)\, \varphi(u^\top x')\big] = \frac{\|x\|\, \|x'\|}{2\pi} \big(\sin\vartheta + (\pi - \vartheta)\cos\vartheta\big).

Deep networks have the same limit, layer by layer (Lee et al., 2018; Matthews et al., 2018). In this limit the hidden units do not learn features. At finite width, Vladimirova, Verbeek, Mesejo and Arbel (2019) show that Gaussian weight priors with ReLU-like activations give units of layer \ell a sub-Weibull prior with tail parameter \ell/2: tails get heavier with depth, far from Gaussian.

Approximate posteriors for networks

Proposition 8.3 — Linearized Laplace predictive Let q(\theta) = \mathcal{N}(\hat\theta, H^{-1}) and linearize the network around the MAP, with the Jacobian J(x) = \partial f_\theta(x) / \partial\theta at \hat\theta. Then the predicted function value is Gaussian: f_\theta(x) \approx f_{\hat\theta}(x) + J(x)(\theta - \hat\theta) \;\sim\; \mathcal{N}\big(f_{\hat\theta}(x),\; J(x)\, H^{-1} J(x)^\top\big).

Proof. A linear map of a Gaussian vector is Gaussian, with the transformed mean and covariance. ∎

For classification, combine it with the moderation of Proposition 3.6. ReLU networks trained to the MAP become arbitrarily confident far from the data (Hein, Andriushchenko and Bitterwolf, 2019). Kristiadi, Hein and Hennig (2020) prove that even a Laplace approximation on the last layer keeps the confidence bounded away from 1 there (Exercise 15).

Algorithm 8.4 — Stochastic-gradient Langevin dynamics (Welling and Teh, 2011) With N training points, minibatches \mathcal{B}_t of size B, steps \varepsilon_t and standard Gaussian \xi_t, iterate \theta_{t+1} = \theta_t + \frac{\varepsilon_t}{2}\Big(\nabla\log p(\theta_t) + \frac{N}{B}\sum_{i \in \mathcal{B}_t} \nabla \log p(y_i \mid x_i, \theta_t)\Big) + \sqrt{\varepsilon_t}\, \xi_t .

SGLD is the unadjusted Langevin algorithm of ch. 5 with a minibatch gradient. With steps satisfying \sum_t \varepsilon_t = \infty and \sum_t \varepsilon_t^2 < \infty, step-weighted averages are consistent (Teh, Thiery and Vollmer, 2016); with a constant step the chain is biased.

The code trains a five-member deep ensemble on 60 points of \sin x with a gap in (-1, 1), and evaluates it in the data, in the gap and far away:

import numpy as np
import torch

torch.set_num_threads(1)
torch.manual_seed(0)
rng = np.random.default_rng(0)
x = np.concatenate([rng.uniform(-4, -1, 30), rng.uniform(1, 4, 30)])
y = np.sin(x) + 0.1 * rng.normal(size=x.size)
X, Y = torch.tensor(x[:, None], dtype=torch.float32), torch.tensor(y[:, None], dtype=torch.float32)

def train(seed):
    torch.manual_seed(seed)
    net = torch.nn.Sequential(torch.nn.Linear(1, 50), torch.nn.Tanh(),
                              torch.nn.Linear(50, 50), torch.nn.Tanh(), torch.nn.Linear(50, 1))
    opt = torch.optim.Adam(net.parameters(), lr=0.01, weight_decay=1e-4)   # MAP with a Gaussian prior
    for _ in range(1000):
        opt.zero_grad()
        loss = ((net(X) - Y) ** 2).mean()
        loss.backward()
        opt.step()
    return net

nets = [train(s) for s in range(5)]
xs = torch.tensor([[-2.5], [0.0], [8.0]])
with torch.no_grad():
    preds = torch.stack([net(xs) for net in nets]).squeeze(-1)    # (members, points)
print("member predictions at x = -2.5, 0, 8:\n", preds.numpy().round(2))
print("ensemble mean:", preds.mean(0).numpy().round(2), "  true:", np.sin([-2.5, 0, 8]).round(2))
print("ensemble sd:  ", preds.std(0).numpy().round(2))

At x = -2.5 the members agree, with spread 0.02 and an error of 0.04. In the gap, at x = 0, the spread grows to 0.05 while the error is 0.20. Far away, at x = 8, the spread is 0.24 but every member predicts between -2.54 and -1.93, while \sin 8 = 0.99. Diversity among a few MAP fits signals extrapolation, but its size is not calibrated; a Gaussian process with a stationary kernel would return to its prior there (ch. 3).

Evaluating predictive uncertainty

Definition 8.5 — Proper scoring rules A scoring rule S(p, y) is the loss of the predictive distribution p when y occurs. It is proper if, for all p and q, \mathbb{E}_{y \sim q}\, S(q, y) \leq \mathbb{E}_{y \sim q}\, S(p, y), and strictly proper if equality forces p = q. Examples are the log score -\log p(y) and the Brier score \sum_k (p_k - \mathbb{1}\{y = k\})^2.

Proposition 8.6 — The log score is strictly proper For all distributions p and q, \mathbb{E}_{y \sim q}[-\log p(y)] - \mathbb{E}_{y \sim q}[-\log q(y)] = \mathrm{KL}(q \,\|\, p) \geq 0 .

Proof. Expand the difference into \mathbb{E}_q[\log(q/p)] and apply Proposition 0.8, which also gives the equality case. ∎

This closes the loop with ch. 1. Forecasting a distribution is a decision problem whose actions are distributions; proper scoring rules are exactly the losses under which the Bayes act is to report one’s actual belief (Gneiting and Raftery, 2007).

Definition 8.7 — Calibration and expected calibration error A classifier with confidence \hat c = \max_k p_k is calibrated if P(\text{correct} \mid \hat c = c) = c for every c. Group the test points into confidence bins B_b; the expected calibration error is \mathrm{ECE} = \sum_b \frac{|B_b|}{n}\, \big|\mathrm{acc}(B_b) - \mathrm{conf}(B_b)\big| .

Guo, Pleiss, Sun and Weinberger (2017) found modern networks overconfident, and corrected them with a single temperature fitted on validation data. Under dataset shift, Ovadia et al. (2019) found deep ensembles the most robust of the methods above.

The cold posterior puzzle

Definition 8.8 — Tempered posterior For a temperature T > 0 and the potential U, p_T(\theta \mid \mathcal{D}) \propto \exp\big(-U(\theta)/T\big), \qquad U(\theta) = -\log p(\mathcal{D} \mid \theta) - \log p(\theta). T = 1 is the Bayes posterior; T < 1 is a “cold” posterior, more concentrated.

Wenzel et al. (2020) report that SG-MCMC networks for image classification predict better with T well below 1 than with the Bayes posterior. Three explanations have been put forward: priors on weights are misspecified (Fortuin et al., 2022); data augmentation changes the likelihood, and with full-batch HMC Izmailov et al. (2021) see the effect mostly disappear without augmentation; and curated benchmark labels make the effective likelihood sharper (Aitchison, 2021). The puzzle is a reminder that Bayesian deep learning is approximate Bayes with an imperfect model.

Key takeaways — chapter 8

  • A Bayesian network predicts by averaging over the posterior; weight decay is the MAP.
  • Wide random networks are Gaussian processes (Theorem 8.2); finite deep networks have heavy-tailed units.
  • Laplace, variational, dropout, SGLD and ensembles approximate the average at very different costs; none is exact.
  • Evaluate with strictly proper scores (log score, Brier) and calibration, in and out of distribution.
  • Cold posteriors point at misspecified priors and likelihoods.

9. Complements for self-study

This chapter collects results that the sessions only mention: the frequentist guarantees of nonparametric posteriors, the number of clusters of DP mixtures, expectation propagation, and what is known about the accuracy of variational Bayes. It assumes ch. 2, 6 and 7.

Posterior consistency

Definition 9.1 — Posterior consistency Let X_1, X_2, \dots be i.i.d. from a distribution P_0. The posterior is consistent at P_0, for a given topology on distributions, if for every neighbourhood U of P_0, \Pi(U \mid X_{1:n}) \longrightarrow 1 \qquad P_0^\infty\text{-almost surely}.

Theorem 9.2 — Doob (1949) If the model is identifiable, and under measurability conditions, the posterior is consistent at P_\theta for \pi-almost every \theta.

Idea. The posterior mean of a bounded function f(\theta) is a martingale in n, which converges almost surely by the martingale convergence theorem. Identifiability makes \theta a limit of functions of the data, so the limit is f(\theta) itself.

Doob’s theorem is reassuring and weak at the same time. The exceptional set has prior probability zero, but in infinite dimension it can contain natural truths: Diaconis and Freedman (1986) build a reasonable prior for a location problem whose posterior is inconsistent at a simple true distribution. One needs conditions that hold at a given P_0.

Theorem 9.3 — Schwartz (1965) Suppose P_0 lies in the Kullback–Leibler support of the prior: for every \varepsilon > 0, \Pi\big(P : \mathrm{KL}(P_0 \,\|\, P) < \varepsilon\big) > 0 . Then the posterior is consistent at P_0 for the weak topology.

Proof. Sketch. Write the posterior mass of U^c as a ratio of integrals of the likelihood ratios \prod_i p(X_i)/p_0(X_i).

  • Denominator: for each P in the KL ball of radius \varepsilon, the law of large numbers makes the likelihood ratio eventually larger than e^{-2n\varepsilon}. Fatou’s lemma turns this into a bound on the integral: almost surely, the denominator eventually exceeds e^{-2n\varepsilon}.
  • Numerator: weak neighbourhoods admit tests whose errors decrease exponentially, which makes the numerator smaller than e^{-cn} for some c > 0.

Choosing \varepsilon small compared with c concludes. ∎

Dirichlet process location mixtures of Gaussians satisfy the KL condition at many smooth densities, which is why they are consistent density estimators even when their number of clusters is not consistent.

Theorem 9.4 — Contraction rates (Ghosal, Ghosh and van der Vaart, 2000) Let \varepsilon_n \to 0 with n\varepsilon_n^2 \to \infty, and let d be the Hellinger distance. Suppose there are sets \mathcal{P}_n of distributions and a constant C > 0 such that

  • entropy: the covering numbers satisfy \log N(\varepsilon_n, \mathcal{P}_n, d) \leq C n \varepsilon_n^2 ;
  • remaining mass: \Pi(\mathcal{P}_n^c) \leq e^{-(C + 4) n\varepsilon_n^2};
  • prior mass: with B(P_0, \varepsilon_n) a Kullback–Leibler neighbourhood that also controls the second moment of the log-ratio, \Pi\big(B(P_0, \varepsilon_n)\big) \geq e^{-C n\varepsilon_n^2} .

Then for M large enough, in P_0-probability, \Pi\big(P : d(P, P_0) > M\varepsilon_n \mid X_{1:n}\big) \longrightarrow 0 .

The rate solves “prior mass near the truth ≈ size of the model”, the same balance as for minimax rates. Gaussian process priors reach the minimax rate when their smoothness matches that of the truth, and lose rate otherwise (van der Vaart and van Zanten, 2008). Dirichlet mixtures of normals reach the parametric rate up to a logarithmic factor for the supersmooth densities they are built for (Ghosal and van der Vaart, 2001). The monograph of Ghosal and van der Vaart (2017) develops all of this.

The number of clusters, revisited

The code of ch. 7 put little posterior mass on the true number of components. This is not a sampling artefact. Miller and Harrison (2013, 2014) prove that, for data from a finite mixture, the posterior probability that a DP or Pitman–Yor mixture has the true number of clusters does not tend to 1. The prior keeps creating small clusters at rate \alpha/(\alpha + n) per point.

Two remedies exist. Count only clusters above a size threshold, as the code did. Or use a mixture of finite mixtures: a prior on the number of components K, then a finite mixture given K. Miller and Harrison (2018) show that this model keeps most of the computational conveniences of the DP, including a restaurant-type sampler, while its posterior on K is consistent under the model.

Proposition 9.5 — Pitman–Yor urn The Pitman–Yor process with discount \sigma \in [0, 1) and strength \alpha > -\sigma has the predictive rule: with K tables and n customers, the next customer \text{joins table } c \text{ with probability } \frac{n_c - \sigma}{\alpha + n}, \qquad \text{opens a new table with probability } \frac{\alpha + \sigma K}{\alpha + n} . Its stick-breaking weights use V_k \sim \mathrm{Beta}(1 - \sigma, \alpha + k\sigma), and for \sigma > 0 the number of tables grows like n^\sigma (Pitman, 2006).

Heuristically, the expected increment of K_n is about \sigma\, \mathbb{E}[K_n]/n for large n, and the solution of this recursion grows like n^\sigma. Power laws of this kind are observed for word types in text, which made the Pitman–Yor process a natural prior for language models (Teh, 2006).

Expectation propagation

Write the posterior as p(\theta \mid x) \propto p(\theta) \prod_i t_i(\theta) with likelihood factors t_i. Expectation propagation (EP; Minka, 2001) replaces each factor by a “site” \tilde t_i in an exponential family, for instance an unnormalized Gaussian, and sets q \propto p \prod_i \tilde t_i.

Algorithm 9.6 — Expectation propagation Repeat until the sites stop changing, for each i:

  1. form the cavity q_{\setminus i} \propto q / \tilde t_i;
  2. form the tilted distribution \hat p_i \propto q_{\setminus i}\, t_i;
  3. replace q by the member of the family with the same expected sufficient statistics as \hat p_i;
  4. set the new site \tilde t_i \propto q / q_{\setminus i}.

Proposition 9.7 — Moment matching minimizes the forward KL Let q_\eta be an exponential family with sufficient statistic T and log-partition A. If some \eta^\star satisfies \mathbb{E}_{q_{\eta^\star}}[T] = \mathbb{E}_p[T], it minimizes \eta \mapsto \mathrm{KL}(p \,\|\, q_\eta).

Proof. Up to a term independent of \eta, the divergence is A(\eta) - \eta^\top \mathbb{E}_p[T]. This function is convex, because the Hessian of A is a covariance matrix (Definition 0.4). Its gradient \nabla A(\eta) - \mathbb{E}_p[T] vanishes exactly when the moments match. ∎

Step 3 is therefore a local forward-KL projection, the opposite direction from VI. EP has no convergence guarantee in general, but it is often more accurate than Laplace or mean-field VI for Gaussian process classification (Kuss and Rasmussen, 2005).

How accurate is variational Bayes?

Combine Proposition 6.4 with the Bernstein–von Mises theorem 2.11. In a regular parametric model, the posterior is close to \mathcal{N}(\hat\theta, (nI)^{-1}) with I = I(\theta_0). The mean-field approximation of that Gaussian has the right centre and the variances 1/(n I_{jj}), smaller than the exact marginal variances (I^{-1})_{jj}/n unless I is diagonal.

Wang and Blei (2019) make this rigorous: under regularity conditions the variational posterior concentrates at \theta_0 and its mean is asymptotically normal, but its covariance is too small. Credible sets from mean-field VI are thus too narrow even with infinite data. In nonparametric problems, Alquier and Ridgway (2020) show that variational approximations of tempered posteriors contract at the same rate as the posterior, under a prior-mass condition of the type of Theorem 9.4.

Key takeaways — chapter 9

  • Doob gives consistency for prior-almost every truth; Schwartz’s KL-support condition gives it at a given truth for the weak topology; Ghosal–Ghosh–van der Vaart give rates from prior mass and entropy.
  • DP and Pitman–Yor mixtures do not estimate the number of components consistently; mixtures of finite mixtures do.
  • EP matches moments locally (forward KL); VI minimizes the reverse KL and underestimates variances, even asymptotically.

10. Research directions and open problems

This self-study chapter surveys active questions and gives a method for reading papers, the skill the student seminar evaluates. It cites only published work; the selection is partial.

Reading a Bayesian machine learning paper

Most abstracts in the field answer four questions, and locating the answers places the paper on the map of this course.

A weak point worth a seminar usually hides in the gap between two answers: an exact sampler evaluated with a misspecified model, or an approximation judged on accuracy rather than calibration.

Monte Carlo at scale

Exact MCMC costs a pass over the data per iteration. Bardenet, Doucet and Holmes (2017) analyse subsampling approaches and show that exact methods need control variates whose quality governs the speed-up. A different line replaces independent draws by repulsive ones: Bardenet and Hardy (2020) use determinantal point processes to build Monte Carlo estimators whose error decreases faster than the usual rate in N^{-1/2}. Non-asymptotic bounds for Langevin algorithms in high dimension (Dalalyan, 2017; Durmus and Moulines, 2017) have made sampling a subject of complexity theory, in parallel with optimization.

Priors for deep networks

Weight-space priors are chosen for convenience, and the cold posterior effect suggests they are wrong (Wenzel et al., 2020). Work by Vladimirova and coauthors (2019) characterizes the induced priors on hidden units, and Fortuin and coauthors (2022) compare heavier-tailed and correlated alternatives. Fortuin (2022) reviews the field. The open question is how to specify priors in function space, where knowledge actually lives, and to transfer them to weights.

Misspecification and generalized posteriors

Bayesian guarantees assume a true model. Grünwald and van Ommen (2017) exhibit inconsistency of Bayesian inference for misspecified linear models and repair it by tempering the likelihood with a learning rate. Bissiri, Holmes and Walker (2016) justify posteriors built from a loss instead of a likelihood, and PAC-Bayes theory bounds the risk of such posteriors without any model assumption (Alquier, 2024). Choosing the temperature in a principled way remains open.

Diffusion models as priors

Score-based generative models give powerful priors for images and signals. Sampling the posterior of an inverse problem with such a prior is hard, because the likelihood enters every step of the denoising process. Chung and coauthors (2023) propose an approximate guidance of the reverse diffusion. Cardoso, Janati El Idrissi, Le Corff and Moulines (2024) instead use sequential Monte Carlo to target the exact posterior of linear inverse problems as the number of particles grows. This connects ch. 5 with Inverse Problems and Imaging and Diffusion and Multiscale Models in AI.

Amortized and simulation-based inference

When the likelihood can be simulated but not evaluated, neural networks trained on simulated pairs (\theta, x) learn the posterior map directly (Cranmer, Brehmer and Louppe, 2020). The same idea, with priors over whole data sets, gives prior-data fitted networks: transformers trained to output posterior predictive distributions (Müller et al., 2022), such as TabPFN for small tabular problems (Hollmann et al., 2023). Xie, Raghunathan, Liang and Ma (2022) read in-context learning of language models as implicit Bayesian inference. Whether such learned inference is calibrated outside its training distribution is open.

Uncertainty without a model: conformal prediction

Conformal prediction builds prediction sets with finite-sample coverage guarantees under exchangeability alone (Angelopoulos and Bates, 2023). It complements Bayesian predictive distributions: Bayesian sets are optimal when the model is right, conformal sets are valid when it is wrong. Combining the two, for instance by conformalizing posterior predictive sets, is an active topic.

Open problems

Key takeaways — chapter 10

  • Read a paper by its model, its inference, its decision and its guarantee; weak points live between them.
  • Active fronts: scalable and repulsive Monte Carlo, priors for networks, generalized posteriors, diffusion priors, amortized inference, conformal guarantees.

Exercises

Levels: ★ apply the course, ★★ combine results or prove a short statement, ★★★ open-ended or research-flavoured. Exercises 7, 9, 14, 16 and 17 are computational.

  1. ★ Three Bayes estimators. Two successes in 10 trials, uniform prior. Give the Bayes estimators under the squared, absolute and 0–1 losses, and the posterior expected squared loss of the first.

    Solution: the posterior is Beta(3, 9). Its mean is 3/12 = 0.25, its median 0.236 and its mode 2/10 = 0.2 (Proposition 1.4).

    The posterior expected squared loss of the mean is the posterior variance, ab/((a+b)^2(a+b+1)) = 27/1872 = 0.0144, a standard deviation of 0.12.

  2. ★ A cost-sensitive decision. A screening model gives a predictive probability of disease of 0.15. Missing a disease costs 20, a false alarm costs 1. Should the patient be flagged? Where does the decision flip? A review by a specialist, who then settles the case without error, costs 0.5: is it worth it?

    Solution: by Proposition 1.12 the threshold is 1/(1 + 20) = 0.048, and 0.15 > 0.048: flag.

    The expected losses are 1 \times 0.85 = 0.85 for flagging and 20 \times 0.15 = 3 for not flagging. Since the review settles the case with no further loss, its expected loss is 0.5, below both, so referring the case is the Bayes action.

  3. ★ Gamma–Poisson update. Daily counts (2, 0, 3, 1, 4) follow a Poisson law with rate \lambda, and the prior is Gamma(2, 1) (shape, rate). Give the posterior, its mean and standard deviation, and the predictive probability of a day with no event.

    Solution: the posterior is Gamma(2 + 10, 1 + 5), that is Gamma(12, 6), with mean 2 and standard deviation \sqrt{12}/6 = 0.577.

    The predictive law is negative binomial, and P(X^\star = 0 \mid x) = \mathbb{E}[e^{-\lambda} \mid x] = (6/7)^{12} = 0.157 .

  4. ★ Jeffreys priors and proper posteriors. Compute the Jeffreys prior of the Poisson rate, of the exponential rate and of a Gaussian scale \sigma with known mean 0. After a single observation, when is the posterior proper?

    Solution: Poisson: I(\lambda) = 1/\lambda, prior \lambda^{-1/2}, posterior Gamma(x + 1/2, 1), always proper.

    Exponential: \log p = \log\lambda - \lambda x, so I = 1/\lambda^2, prior 1/\lambda, posterior proportional to e^{-\lambda x}, proper when x > 0.

    Gaussian scale: I = 2/\sigma^2, prior 1/\sigma, posterior proportional to \sigma^{-2} e^{-x^2/2\sigma^2}. The substitution u = 1/\sigma shows it is proper when x \neq 0.

  5. ★ Bayesian regression by hand. Redo Example 3.2 with a third point (3, 3.2). Give the posterior and the predictive distribution at x^\star = 4.

    Solution: \sum x_i^2 = 14 and \sum x_i y_i = 14.6. The posterior precision is 1 + 4 \times 14 = 57, the posterior mean 4 \times 14.6/57 = 1.025, the standard deviation 0.132.

    At x^\star = 4: predictive mean 4.098, variance 0.25 + 16/57 = 0.531, standard deviation 0.728. The parameter part of the predictive variance is now x^{\star 2}/57 instead of x^{\star 2}/21: at x^\star = 3 it falls from 0.43 to 0.16.

  6. ★ Chinese restaurant arithmetic. For n = 10 customers, compute the expected number of tables for \alpha \in \{0.1, 1, 10\}, and the probability that all customers sit at one table when \alpha = 1.

    Solution: by Example 7.6, the expectations are 1.27, 2.93 and 7.19.

    The probability of a single table is the product over customers 2 to 10 of (i - 1)/(\alpha + i - 1), which telescopes to 1/10 for \alpha = 1.

  7. ★ Coverage at n = 100 (Python). Rerun the coverage code of ch. 2 with n = 100. What changes for each interval?

    Hints and expected result: mean coverages become 0.931 (Wald), 0.950 (Jeffreys) and 0.950 (uniform); minimum coverages 0.633, 0.881 and 0.921.

    The Wald interval still fails near the boundaries, where the normal approximation of the binomial is poor. The two credible intervals are close to nominal on average, as Theorem 2.11 predicts, and oscillate because the binomial is discrete.

  8. ★★ The Bayes risk of the posterior mean. Show that under the squared loss the Bayes risk is \mathbb{E}[\mathrm{Var}(\theta \mid X)]. For the binomial model with a uniform prior, show that it equals 1/(6(n+2)), and compare with the average risk 1/(6n) of K/n.

    Solution: by Theorem 1.3 and Proposition 1.4, the Bayes risk is the average over X of the posterior expected loss of the posterior mean, which is the posterior variance.

    With a uniform prior, K is uniform on \{0, \dots, n\}, and the posterior Beta(K + 1, n - K + 1) has variance \frac{(K+1)(n-K+1)}{(n+2)^2(n+3)} . The sum of j(n + 2 - j) over j = 1, \dots, n+1 is (n+1)(n+2)(n+3)/6, which gives 1/(6(n+2)).

    For n = 16 this is 0.00926, against 1/96 = 0.0104 for K/n: the values printed by the code of ch. 1.

  9. ★★ James–Stein risk (Python). For d = 10, estimate by simulation the risk of \delta^{\mathrm{JS}} and of its positive part, which replaces the factor by its positive part, at \|\theta\| \in \{0, 2, 5, 10\}. Check the formula of Theorem 1.11.

    Hints and expected result: with 2 \times 10^5 replications, the risk of \delta^{\mathrm{JS}} is about 2.00, 4.38, 7.97 and 9.38, always below 10, and matches d - (d-2)^2\, \mathbb{E}\|X\|^{-2} to within simulation error.

    The positive-part version gives 1.26 and 3.98 at the first two points and is practically identical further away, where the factor is almost never negative (probability 4 \times 10^{-4} at \|\theta\| = 5). It dominates \delta^{\mathrm{JS}}, a classical result (Lehmann and Casella, 1998).

  10. ★★ Mean field in both directions. Let p = \mathcal{N}(0, \Sigma) in two dimensions with unit variances and correlation \rho. Find the product of Gaussians minimizing \mathrm{KL}(q \,\|\, p), then the product of densities minimizing \mathrm{KL}(p \,\|\, q). Evaluate for \rho = 0.9.

    Solution: the first is given by Proposition 6.4: centred, variances 1 - \rho^2.

    For the second, with p_1, p_2 the marginals of p and H the entropy, write \mathrm{KL}(p \,\|\, q_1 q_2) = -H(p) + H(p_1) + H(p_2) + \mathrm{KL}(p_1 \,\|\, q_1) + \mathrm{KL}(p_2 \,\|\, q_2) . It is minimized at q_j = p_j, with unit variances; the minimum is the mutual information -\frac12 \log(1 - \rho^2).

    For \rho = 0.9: standard deviations 0.436 against 1, and a minimum of 0.830 nats.

  11. ★★ Gibbs is Metropolis–Hastings with acceptance 1. Show that the Gibbs update of block j is a Metropolis–Hastings step whose proposal is the full conditional, and that its acceptance probability is always 1.

    Solution: the proposal changes only \theta_j, with density \pi(\theta_j' \mid \theta_{-j}). The Metropolis–Hastings ratio is \frac{\pi(\theta_j', \theta_{-j})\, \pi(\theta_j \mid \theta_{-j})}{\pi(\theta_j, \theta_{-j})\, \pi(\theta_j' \mid \theta_{-j})} = \frac{\pi(\theta_{-j})\, \pi(\theta_j' \mid \theta_{-j})\, \pi(\theta_j \mid \theta_{-j})}{\pi(\theta_{-j})\, \pi(\theta_j \mid \theta_{-j})\, \pi(\theta_j' \mid \theta_{-j})} = 1 . Theorem 5.4 then gives a second proof of Proposition 4.3.

  12. ★★ Moments of the Dirichlet process. Let G \sim \mathrm{DP}(\alpha, G_0) with G_0 without atoms.

    (a) Show that two draws from G coincide with probability 1/(1+\alpha).

    (b) For disjoint A and B, compute \mathrm{Cov}(G(A), G(B)).

    (c) How many sticks leave an expected mass below 10^{-2} when \alpha = 5?

    Solution: (a) by the Pólya urn, the second draw equals the first with probability 1/(\alpha + 1).

    (b) With C the complement of A \cup B, the triple (G(A), G(B), G(C)) is Dirichlet, and \mathbb{E}[W_1 W_2] = a_1 a_2 / (a_0(a_0 + 1)) with a_0 = \alpha. Hence \mathrm{Cov}\big(G(A), G(B)\big) = -\frac{G_0(A)\, G_0(B)}{1 + \alpha} .

    (c) (5/6)^K \leq 10^{-2} requires K \geq 25.3, so 26 sticks.

  13. ★★ Laplace approximations of a Beta posterior. For the posterior Beta(8, 4) of Example 1.5, compute the Laplace approximation in \theta and in the logit \varphi = \log(\theta/(1-\theta)), and compare the resulting 95 % intervals with the exact one.

    Solution: in \theta, the log density 7\log\theta + 3\log(1-\theta) has its mode at 0.7 and curvature 7/0.49 + 3/0.09 = 47.6, so the variance is 0.021 and the interval (0.416, 0.984).

    In \varphi, the Jacobian turns the density into \theta^8(1-\theta)^4, with mode \theta = 2/3, \varphi = \log 2, and curvature 12 \times \frac23 \times \frac13 = 2.67.

    The interval \log 2 \pm 1.96/\sqrt{2.67} maps to (0.376, 0.869) on the scale of \theta.

    The exact interval is (0.390, 0.891): the logit approximation is much closer, because the posterior is more Gaussian on an unbounded scale. Laplace depends on the parameterization.

  14. ★★ A Gibbs sampler for regression with unknown noise (Python). In the evidence code of ch. 3, take degree 3, keep \alpha = 1, and put a Gamma(1, 0.01) prior (shape, rate) on the noise precision \beta. Derive the two full conditionals, implement the sampler, and report the posterior of the noise standard deviation.

    Hints and expected result: w \mid \beta, y is given by Proposition 3.1, and \beta \mid w, y \sim Gamma(1 + n/2,\; 0.01 + \|y - \Phi w\|^2/2).

    With 5000 iterations, the noise standard deviation has posterior mean about 0.32 and 90 % interval about (0.23, 0.44): larger than the 0.2 used to simulate. A cubic cannot represent \sin(\pi x) exactly (training RMSE 0.26 in ch. 3), and the prior shrinks the large coefficients. The posterior means of the coefficients are about (-0.07, 2.24, 0.04, -2.19).

  15. ★★★ Overconfidence far from the data. For a binary classifier whose logit is w^\top h(x), with h the last hidden layer of a ReLU network, show that along almost every ray t \mapsto t x the MAP confidence tends to 1. Then show that a Gaussian posterior \mathcal{N}(m, S) on w, with S positive definite, combined with Proposition 3.6, keeps the confidence below 1.

    Hints and expected result: h is piecewise affine with finitely many regions, so for large t one has h(tx) = t\, u + c on a single region. The logit is t\, w^\top u + w^\top c, which tends to \pm\infty unless w^\top u = 0 (Hein, Andriushchenko and Bitterwolf, 2019).

    Under the Gaussian posterior, \mu_a \approx t\, m^\top u and \sigma_a^2 \approx t^2\, u^\top S u, so the moderated probability tends to \sigma\Big(\frac{m^\top u}{\sqrt{\pi\, u^\top S u / 8}}\Big) < 1 . This is the mechanism of Kristiadi, Hein and Hennig (2020).

  16. ★★★ Cold posteriors on a toy problem (Python, open-ended). On the two-moons data of scikit-learn (make_moons, 200 training points, noise 0.2), sample a two-layer network with SGLD at temperatures T \in \{1, 0.3, 0.1\}. Compare test accuracy and log score. Then add “augmented” jittered copies of each training point, counted as independent observations, and compare again.

    Hints and expected result: tempering multiplies the gradient by 1/T and keeps the noise. On this small, well-specified problem, expect T = 1 to be competitive in log score.

    With augmentation counted as extra data, the likelihood is over-counted and the ranking of temperatures moves. Relate what you see to the explanations of Wenzel et al. (2020) and Izmailov et al. (2021), and report several seeds with error bars.

  17. ★★★ Is the number of clusters consistent? (Python, open-ended). Run the DP mixture code of ch. 7 on samples of size 150, 600 and 1200 from the same three-component mixture. Track the posterior probability of exactly 3 clusters, and of 3 clusters holding at least 5 % of the points. Then implement the restaurant process of a mixture of finite mixtures (Miller and Harrison, 2018) and compare.

    Hints and expected result: the probability of exactly 3 clusters does not increase with n, because small clusters keep appearing, while the count of large clusters concentrates at 3.

    The mixture of finite mixtures replaces the weights n_c and \alpha by n_c + \gamma and a ratio of coefficients that depends on the prior on K.

    Its posterior on K concentrates at 3 as n grows. Profile the code before running large n.

Projects and assessment

The official assessment, per master-mva.com, is a group study of a research paper chosen from a list. Each group writes a small report and gives a short oral presentation in front of the class, in a student seminar during the last lecture. The description strongly encourages a dash of creativity: find a weak point, shortcoming or limitation of the paper and push in that direction, by extending a proof, implementing another feature or running different experiments. The Université Paris-Saclay course detail classifies the assessment as “Evaluation Continue non Intégrale”.

All the subjects below are paper studies in that spirit, with a weak point to push. The solo subjects are sized for one student; the group subjects match the official format. The written exam is not part of the official assessment: it is offered as a self-test, and none of these proposals is official material.

Solo projects

  1. [Solo · ≈ 20 h] Stochastic-gradient Langevin dynamics: a paper study. Study Welling and Teh (2011) and reimplement SGLD (Algorithm 8.4).
    • Experiments: the two-parameter Gaussian mixture example of the paper (synthetic data), then Bayesian logistic regression on the breast-cancer data set bundled with scikit-learn.
    • Weak point to push: the bias of constant step sizes. Measure the error on posterior means and variances against a long MALA chain (ch. 5), as a function of step size and batch size.
    • Success criterion: a plot of the error against the step size showing the bias, and a comparison of effective sample size per second with MALA.
    • Deliverables: code, a 4–6 page report, a 10-minute talk. Chapters 5, 8.
  2. [Solo · ≈ 20 h] Dropout, ensembles and Laplace: a paper study. Compare Monte Carlo dropout (Gal and Ghahramani, 2016) with deep ensembles (Lakshminarayanan, Pritzel and Blundell, 2017) and a last-layer Laplace approximation (Proposition 8.3).
    • Data: the one-dimensional problem with a gap of ch. 8, and the diabetes regression data set bundled with scikit-learn.
    • Weak point to push: a posterior should contract as data accumulate. Measure how each method’s predictive variance changes when the training set grows from 50 to 400 points.
    • Success criterion: a table of test log score, RMSE and 90 % interval coverage, and a plot of predictive variance against n for each method.
    • Deliverables: code, report, talk. Chapters 3, 6, 8.
  3. [Solo · ≈ 15 h] Objective priors at work: interval estimation for a proportion. Reproduce the coverage figures of Brown, Cai and DasGupta (2001) for the Wald, Wilson, Clopper–Pearson and Jeffreys intervals.
    • Weak point to push: extend the study to a Poisson rate with the Jeffreys prior \lambda^{-1/2}, or to the difference of two proportions, where no interval is exact.
    • Success criterion: coverage curves over a fine grid of parameters, with an explanation of the oscillations and a recommendation backed by numbers.
    • Deliverables: code, report, talk. Chapters 1, 2.

Group projects

  1. [Group of 2–3 · ≈ 30 h each] Dirichlet process mixtures: sampling against variational inference. Study Blei and Jordan (2006) together with Neal (2000).
    • Work split: one member implements the collapsed Gibbs sampler (Algorithm 7.9); one the truncated stick-breaking variational algorithm; one the mixture of finite mixtures of Miller and Harrison (2018).
    • Data: synthetic Gaussian mixtures, and the digits data set of scikit-learn projected on its first principal components.
    • Weak point to push: the number of clusters (ch. 9). Show how each method’s posterior on the number of clusters behaves as n grows.
    • Success criterion: held-out log predictive density and running time for each method, and a figure reproducing the inconsistency proved by Miller and Harrison (2013).
    • Deliverables: code, a 6-page report, a 15-minute seminar talk. Chapters 4, 6, 7, 9.
  2. [Group of 2–3 · ≈ 30 h each] What do Bayesian neural network posteriors look like? A scaled-down replication. Study Izmailov, Vikram, Hoffman and Wilson (2021) and Wenzel et al. (2020).
    • Setting: a small multilayer perceptron on the scikit-learn digits data set, small enough for full-batch HMC to serve as reference.
    • Work split: one member runs the HMC reference (ch. 5); one SGLD at several temperatures (Algorithm 8.4, Definition 8.8); one mean-field VI and deep ensembles, and the shared evaluation.
    • Success criterion: a table of accuracy, log score and expected calibration error, the agreement of each method’s predictive distribution with HMC, and a cold-posterior curve with and without data augmentation.
    • Deliverables: code, report, seminar talk. Chapters 5, 6, 8.
  3. [Group of 2–3 · ≈ 30 h each] Markov chain Monte Carlo for tall data. Study Bardenet, Doucet and Holmes (2017).
    • Setting: Bayesian logistic regression on 10^5 synthetic points.
    • Work split: one member implements full Metropolis–Hastings and naive subsampling; one the confidence sampler with control variates of the paper; one SGLD and the evaluation.
    • Weak point to push: the speed-up when the posterior is far from Gaussian, for instance with heavy-tailed covariates or a misspecified model.
    • Success criterion: the number of likelihood evaluations per iteration, and the error on posterior means and variances against full Metropolis–Hastings.
    • Deliverables: code, report, seminar talk. Chapters 5, 8.

Written exam (proposal)

Format: 3 hours, one handwritten A4 sheet allowed, no electronic device; four independent exercises.

  1. Course question (4 points). Define the frequentist risk, the integrated risk and a Bayes rule. Prove that an action minimizing the posterior expected loss for each observation gives a Bayes rule. State two conditions under which a Bayes rule is admissible.

    Expected: Definitions 1.1–1.2; Theorem 1.3 with the Fubini exchange and the pointwise inequality; Proposition 1.7, uniqueness or continuity of risks with a full-support prior.

  2. Computation (6 points). Daily counts (3, 1, 4, 0, 2) are Poisson with rate \lambda, and the prior is Gamma(1, 1).

    (a) Give the posterior. (b) Give the Bayes estimators under the squared loss and under the loss (\lambda - a)^2/\lambda. (c) Compute the predictive probability of a day with no event. (d) Redo (a) with the Jeffreys prior.

    Expected: (a) Gamma(11, 6). (b) The posterior mean 11/6 = 1.83; for the weighted loss, minimizing the posterior expectation \mathbb{E}[\lambda] - 2a + a^2\, \mathbb{E}[1/\lambda] gives a = \frac{1}{\mathbb{E}[1/\lambda \mid x]} = \frac{11 - 1}{6} = 1.67 . (c) (6/7)^{11} = 0.184. (d) The prior \lambda^{-1/2} gives Gamma(10.5, 5), with mean 2.1.

  3. Short proof (5 points). Prove the ELBO identity and the coordinate-ascent update of mean-field variational inference. Deduce that for a Gaussian target the mean-field variances are the inverse diagonal entries of the precision matrix, and that they underestimate the marginal variances.

    Expected: Proposition 6.1, Theorem 6.2 with the KL to the tilted factor, Example 6.3, and Proposition 6.4 through the Schur complement.

  4. Problem (5 points). Let G \sim \mathrm{DP}(\alpha, G_0) with G_0 without atoms.

    (a) Compute the mean and variance of G(A). (b) Derive the predictive rule of X_{n+1} given X_{1:n} from the posterior. (c) Show that the expected number of distinct values among n draws grows like \alpha\log n. (d) Explain in two sentences what changes with a Pitman–Yor process.

    Expected: (a) Proposition 7.3 through the Beta marginal. (b) Theorem 7.4 and Proposition 7.5. (c) The sum of \alpha/(\alpha + i - 1), compared with an integral. (d) A discount \sigma makes new clusters more likely as K grows, so the number of clusters grows like n^\sigma (Proposition 9.5).

Grading rubric (proposal)

Criterion Weight What earns the marks
Understanding of the paper 25 % The model, the inference method and the main claim stated precisely, and placed on the map of the course (ch. 10)
Critical contribution 25 % A weak point identified and pushed: a proof extended, a feature added, or an experiment that tests an assumption
Correctness and rigour 20 % Correct derivations, assumptions stated, approximations named and their bias discussed
Experiments and code 15 % Reproducible code with fixed seeds, diagnostics for every sampler (effective sample size, several chains), error bars
Report and seminar talk 15 % A short report within the page limit, readable figures, a talk that fits its slot and answers questions

References

Official references (master-mva.com)

Textbooks

Decision theory and the interpretations of probability (ch. 1–2)

Bayesian supervised and unsupervised learning (ch. 3–4)

Monte Carlo methods (ch. 5)

Variational methods (ch. 6 and 9)

Bayesian nonparametrics (ch. 7 and 9)

Bayesian deep learning (ch. 8)

Research directions (ch. 10)