MVA · Course notes

Computational Statistics

M2 MVA · Semester 1 · Learning · 5 ECTS

Contents

Introduction and overview

Module Computational Statistics
Official title Computational Statistics
Instructors S.ALLASSONNIERE (master-mva.com, 2026–2027); the speakers section of the same page names Stéphanie Allassonnière (Université Paris Cité)
Period Semester 1 · period 1 (28/09/2026 – 08/01/2027)
Credits and volume 5 ECTS · 40 h (lectures 20 h, labs 20 h) per the Université Paris-Saclay programme table
Label LearningTrack Santé
Language Not displayed (the master-mva.com description is written in English)
Assessment master-mva.com: homework following each training session (4 assignments) = 2/3 of the grade; oral presentation of one scientific paper, team work (“Team work (2)”), no report = 1/3 · Université Paris-Saclay: “Evaluation Continue non Intégrale” (literally, non-integral continuous assessment)
Prerequisites Not displayed (neither on master-mva.com nor on the Université Paris-Saclay course detail)

Audience: an M2 student with a solid M1 in probability and optimisation who must fit models with hidden variables, compute Bayesian estimators, or sample from a distribution known only up to a constant.

Empirical first: EM fitted to a two-component Gaussian mixture raises its likelihood at every iteration, yet still gains 13 log-likelihood units between iterations 20 and 200 (ch. 3). A random-walk Metropolis chain started in one mode of a bimodal target never visits the other mode in 20 000 steps (ch. 8). The course explains both behaviours, and then repairs them.

The course is about the algorithms that turn a statistical model into numbers: stochastic gradients, EM and its stochastic versions, stochastic approximation, simulation and Markov chain Monte Carlo, and likelihood-free inference. It shares tools with Convex Optimization and Applications in Machine Learning, Introduction to Probabilistic Graphical Models and Deep Generative Models and Stochastic Calculus in Machine Learning, and it prepares Bayesian Machine Learning and Biostatistics.

What you will be able to do

Official objectives and syllabus (2026–2027)

The course description on master-mva.com states that the course details statistical computational methods and Bayesian inference. It starts with the stochastic gradient algorithm, its theoretical properties and its numerical bottlenecks. After a brief introduction to Bayesian inference, it discusses the numerical challenges of computing Bayesian estimators, which lead to the EM algorithm, its stochastic versions and, more generally, Majorize–Minimize algorithms.

Stochastic approximation is then detailed, to understand the convergence conditions of these algorithms. The second part is devoted to the simulation of random variables: from the rejection method to the classical MCMC samplers (Metropolis–Hastings and Gibbs), then recent advances in MCMC: adaptive MCMC, adaptive parallel tempering and approximate Bayesian computation. The description announces 20 h of lectures and 20 h of training and lab sessions, and lists the course for the Master 2 MVA and Data Science.

The Université Paris-Saclay course detail gives the volume (20 h of lectures, 20 h of labs, 5 ECTS) and the nature of the assessment, but no programme items. The table below has one row per topic of the master-mva.com description and per announced element of the organisation.

Official topic Course section
Statistical computational methods and Bayesian inference (overall objective) The whole page; ch. 2 maps each method to the obstacle it removes (ch. 2.4)
Stochastic gradient algorithm: theoretical properties ch. 1.1–1.3: Theorem 1.3 (rate 1/t, strongly convex case), Theorem 1.5 (rate 1/\sqrt{T} with averaging); almost-sure convergence in Corollary 4.5
Stochastic gradient algorithm: numerical bottlenecks ch. 1.4: step size, variance floor (Proposition 1.6), conditioning, mini-batches, variance reduction, Example 1.7
Brief introduction to Bayesian inference ch. 2.1–2.3: posterior, Bayes estimators (Proposition 2.3), conjugacy (Example 2.4), Bernstein–von Mises (Theorem 2.5)
Numerical challenges when computing Bayesian estimators ch. 2.3–2.5: evidence and Laplace approximation (Proposition 2.6, Example 2.7), the four computational obstacles, latent-variable models
EM algorithm ch. 3.2–3.5: EM as minorize–maximize (Proposition 3.4), monotonicity (Theorem 3.6), exponential families, Gaussian mixtures, convergence (Theorem 3.9) and rate (Proposition 3.10)
Stochastic versions of EM ch. 7: MCEM, SEM, SAEM (Proposition 7.4, Theorem 7.5), MCMC-SAEM (Theorem 7.6, Example 7.7); placed after ch. 4–6 because it uses stochastic approximation and MCMC
Majorize–Minimize algorithms ch. 3.1: Definition 3.1, descent property (Proposition 3.2), quadratic and absolute-value surrogates (Example 3.3); Exercise 8
Stochastic approximation and the convergence conditions of the previous algorithms ch. 4: Robbins–Monro, Robbins–Siegmund lemma (Lemma 4.3), almost-sure convergence (Theorem 4.4), ODE method (Theorem 4.7), rates and averaging (Theorems 4.8–4.9); applied to SGD (Corollary 4.5), SAEM (ch. 7) and adaptive MCMC (ch. 8)
Random variable simulation: the rejection method ch. 5: inversion and transformations (5.1–5.2), rejection (Theorem 5.5, Proposition 5.7), importance sampling (5.4)
Classical MCMC: Metropolis–Hastings ch. 6.1–6.2: Markov kernels, ergodic theorem, MH (Theorem 6.7), optimal scaling (Theorem 6.8)
Classical MCMC: Gibbs algorithm ch. 6.3: Proposition 6.11, Examples 6.12–6.13; diagnostics in ch. 6.4
Recent advances: adaptive MCMC ch. 8.1–8.2: adaptive Metropolis (Algorithm 8.1), counterexample (Example 8.3), Roberts–Rosenthal conditions (Theorem 8.4)
Recent advances: adaptive parallel tempering ch. 8.3–8.4: tempering, parallel tempering (Algorithm 8.6, Proposition 8.7), adaptive ladder (Algorithm 8.9)
Recent advances: Approximate Bayesian Computation ch. 9: rejection ABC (Proposition 9.2), tolerance and summaries (Proposition 9.4), ABC-MCMC (Proposition 9.6), ABC-SMC (Algorithm 9.7)
Organisation: 20 h of lectures and 20 h of training and lab work Session plan: ten sessions of 2 h lecture + 2 h lab
Assessment: homework after each training session (4) Session plan (homework 1–4) and the solo subjects of the Projects section
Assessment: oral presentation of one scientific paper, team work, no report Group subjects of the Projects section (paper studies presented orally)

Beyond the syllabus, the page adds importance sampling (ch. 5.4), MCMC diagnostics (ch. 6.4) and, in self-study, Langevin and Hamiltonian samplers, stochastic-gradient MCMC and neural simulation-based inference (ch. 10).

Where this course fits in the programme

Official prerequisites: not displayed. The material assumes M1 probability (conditional expectation, laws of large numbers, central limit theorem, finite Markov chains), M1 optimisation (gradients, convexity) and fluent NumPy.

Course outline

Session plan

40 h in class = 10 sessions of 4 h (2 h lecture + 2 h lab).

The volume is the Université Paris-Saclay programme table (20 h of lectures and 20 h of labs), which matches the master-mva.com description (20 h of lectures and 20 h of training and lab work). The split into sessions, and the placement of the four homework assignments after four of the labs, is a proposal.

The order follows the official description, with one change: the stochastic versions of EM (official part 1) are taught after simulation and MCMC, because MCMC-SAEM needs both. Level 1 = foundations, 2 = core results and algorithms, 3 = advanced and recent methods; the level never decreases.

Session Hours Level Content Practice
1 4 h 1 ch. 0 Review: Monte Carlo error, KL divergence, exponential families, smooth and strongly convex functions, martingales; ch. 1.1 the stochastic gradient algorithm Ex. 1; lab: Example 0.3 (Monte Carlo in dimension d)
2 4 h 2 ch. 1.2–1.4 Rates of SGD (Theorems 1.3, 1.5), variance floor, conditioning, mini-batches, variance reduction Ex. 2, 7; lab: Example 1.7 (step-size schedules); homework 1
3 4 h 2 ch. 2 Posterior, Bayes estimators, conjugacy, Bernstein–von Mises and Laplace, the computational obstacles, latent-variable models Ex. 3; lab: Example 2.7 (posterior summaries and evidence)
4 4 h 2 ch. 3 Majorize–Minimize, EM as minorize–maximize, monotonicity, exponential families, Gaussian mixtures, convergence and rate Ex. 8, 9; lab: Example 3.8 (EM for a mixture)
5 4 h 2 ch. 4 Robbins–Monro, Robbins–Siegmund lemma, almost-sure convergence, ODE method, central limit theorem and averaging Ex. 10; lab: Example 4.10 (quantile estimation); homework 2
6 4 h 2 ch. 5 Inversion, transformations, rejection sampling, importance sampling Ex. 4, 5; lab: Examples 5.6 and 5.10
7 4 h 2 ch. 6 Markov kernels, ergodicity, Metropolis–Hastings, optimal scaling, Gibbs sampler, diagnostics Ex. 6, 11; lab: Examples 6.9 and 6.12; homework 3
8 4 h 3 ch. 7 MCEM, SEM, SAEM and its Lyapunov function, MCMC-SAEM Ex. 14; lab: Example 7.7 (random-effects logistic model)
9 4 h 3 ch. 8 Adaptive Metropolis, ergodicity of adaptive chains, parallel tempering, adaptive ladders Ex. 12, 15, 16; lab: Examples 8.2 and 8.8
10 4 h 3 ch. 9 Rejection ABC, tolerance and summaries, regression adjustment, ABC-MCMC, ABC-SMC Ex. 13; lab: Example 9.3; homework 4

Self-study, outside the 40 h (about 5 h in total): ch. 10 Research directions and open problems — Langevin and Hamiltonian samplers, stochastic-gradient MCMC, Markovian stochastic approximation, theory of EM, tempering, simulation-based inference, stochastic algorithms in computational anatomy (≈ 5 h, with the open-ended parts of Ex. 16).

How to study this module

Independent notes These notes reconstruct the official syllabus from public sources; they are not the instructor’s material. The master-mva.com page links to a presentation of the course, which is not reproduced here.

0. Review: Monte Carlo, convexity and martingales

Every algorithm of the course is analysed with four M1 tools. The law of large numbers and the central limit theorem give Monte Carlo its error bar. The Kullback–Leibler divergence makes EM work. Smooth and strongly convex functions make gradient methods converge. Martingales make stochastic approximation converge.

This chapter states each tool in the form used later, with short proofs. Background is in the refreshers Probability and Statistics and Linear Algebra, Analysis and Optimization.

0.1 Monte Carlo integration

Definition 0.1 — Monte Carlo estimator Let \pi be a probability distribution and h a function with \pi(h^2) < \infty, where \pi(h) = \mathbb{E}_\pi[h(X)]. For X_1, \dots, X_n independent with law \pi, the Monte Carlo estimator is \hat I_n = \frac1n \sum_{i=1}^n h(X_i), \qquad \mathbb{E}[\hat I_n] = \pi(h), \qquad \mathrm{Var}(\hat I_n) = \frac{\sigma_h^2}{n}, with \sigma_h^2 = \mathrm{Var}_\pi(h(X)).

Proposition 0.2 — The Monte Carlo error bar By the strong law of large numbers, \hat I_n \to \pi(h) almost surely. By the central limit theorem, \sqrt n\,(\hat I_n - \pi(h)) converges in law to \mathcal N(0, \sigma_h^2).

With \hat\sigma_n the empirical standard deviation of the h(X_i), an asymptotic 95 % confidence interval is \hat I_n \pm 1.96\, \frac{\hat\sigma_n}{\sqrt n}.

The rate n^{-1/2} does not depend on the dimension of X; the constant \sigma_h does.

By contrast, a tensor-product quadrature rule of order r with m nodes per axis uses N = m^d evaluations. Its error is of order N^{-r/d}, which degrades with the dimension.

Example 0.3 — Monte Carlo in dimension d Take X \sim \mathcal N(0, I_d) and h(x) = \exp(-\|x\|^2/2).

  • Since \mathbb{E}[e^{-tZ^2}] = (1 + 2t)^{-1/2} for Z \sim \mathcal N(0,1), independence gives \pi(h) = 2^{-d/2} and \pi(h^2) = 3^{-d/2}.
  • The relative variance per sample is therefore \frac{\sigma_h^2}{\pi(h)^2} = \Big(\frac43\Big)^{d/2} - 1 .
  • For d = 10 this is 3.21, so n = 10^5 samples give a relative standard error of \sqrt{3.21/10^5} \approx 0.0057.
  • For d = 50 it is 1328, and the relative standard error becomes 0.115.
import numpy as np

rng = np.random.default_rng(0)
n = 100_000
for d in [1, 10, 50]:
    X = rng.standard_normal((n, d))
    h = np.exp(-0.5 * (X ** 2).sum(axis=1))      # h(x) = exp(-|x|^2 / 2)
    est = h.mean()
    se = h.std(ddof=1) / np.sqrt(n)              # CLT standard error
    exact = 2.0 ** (-d / 2)
    print(f"d={d:2d}  estimate={est:.4e}  exact={exact:.4e}  relative s.e.={se / est:.4f}")

The run prints relative standard errors of 0.0012, 0.0057 and 0.133; the last one is itself estimated from heavy-tailed values, and overshoots the exact 0.115. The rate is the same in every dimension; the constant explodes because the few samples near the origin carry all the mass of h. Importance sampling (ch. 5.4) and MCMC (ch. 6) are two ways of attacking that constant.

0.2 Jensen’s inequality and the Kullback–Leibler divergence

Definition 0.4 — Kullback–Leibler divergence For two densities q and p with q = 0 wherever p = 0, \mathrm{KL}(q \,\|\, p) = \int q(z) \log \frac{q(z)}{p(z)}\, dz . It is not symmetric in (q, p) and is not a distance, but it measures how much q differs from p.

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

Proof. The logarithm is strictly concave, so Jensen’s inequality under q gives -\mathrm{KL}(q \,\|\, p) = \mathbb{E}_q\Big[\log \frac{p(Z)}{q(Z)}\Big] \le \log \mathbb{E}_q\Big[\frac{p(Z)}{q(Z)}\Big] \le \log 1 = 0 . Equality in Jensen’s inequality forces p/q to be constant q-almost surely, and the constant is 1 because both densities integrate to 1. ∎

This inequality is the whole reason EM increases the likelihood (Theorem 3.6).

0.3 Exponential families

Definition 0.6 — Exponential family A family of densities is an exponential family with natural parameter \eta \in \mathbb{R}^q and sufficient statistic S(x) \in \mathbb{R}^q if p(x; \eta) = h(x) \exp\big(\langle \eta, S(x) \rangle - A(\eta)\big), \qquad A(\eta) = \log \int h(x)\, e^{\langle \eta, S(x)\rangle}\, dx . Examples: the Gaussian \mathcal N(m, \sigma^2) with S(x) = (x, x^2); the Bernoulli and Poisson laws with S(x) = x; a categorical law with S(x) the vector of indicators.

Proposition 0.7 — The log-partition function In the interior of the natural parameter space, A is infinitely differentiable and \nabla A(\eta) = \mathbb{E}_\eta[S(X)], \qquad \nabla^2 A(\eta) = \mathrm{Cov}_\eta(S(X)) \succeq 0 . Hence A is convex, and the maximum-likelihood equation for a sample x_1, \dots, x_n is the moment equation \nabla A(\eta) = \frac1n \sum_i S(x_i).

Proof. Differentiate e^{A(\eta)} = \int h\, e^{\langle \eta, S\rangle} under the integral sign, which dominated convergence allows in the interior. The first derivative gives \nabla A\, e^{A} = \int S\, h\, e^{\langle \eta, S\rangle}, that is \nabla A = \mathbb{E}_\eta[S].

Differentiating once more gives \nabla^2 A + \nabla A\, \nabla A^\top = \mathbb{E}_\eta[S S^\top], which is the covariance formula. The log-likelihood \langle \eta, \sum_i S(x_i)\rangle - nA(\eta) is concave, and its gradient vanishes exactly at the moment equation. ∎

Chapters 3 and 7 use this structure: when the complete data of a latent-variable model form an exponential family, the EM algorithm only manipulates the expected sufficient statistics.

0.4 Smooth and strongly convex functions

Definition 0.8 — Smoothness and strong convexity A differentiable function F : \mathbb{R}^d \to \mathbb{R} is L-smooth if its gradient is L-Lipschitz: \|\nabla F(x) - \nabla F(y)\| \le L \|x - y\| . It is \mu-strongly convex (\mu > 0) if, for all x, y, F(y) \ge F(x) + \langle \nabla F(x), y - x \rangle + \frac{\mu}{2} \|y - x\|^2 . The ratio \kappa = L / \mu \ge 1 is the condition number.

Proposition 0.9 — Three consequences Let F be L-smooth and \mu-strongly convex, with minimiser x^* and F^* = F(x^*).

  1. Descent lemma: F(y) \le F(x) + \langle \nabla F(x), y - x\rangle + \frac{L}{2}\|y - x\|^2 .
  2. Strong monotonicity: \langle \nabla F(x) - \nabla F(y), x - y \rangle \ge \mu \|x - y\|^2 .
  3. Gradient descent with step 1/L converges linearly: F(x_t) - F^* \le \Big(1 - \frac{\mu}{L}\Big)^t \big(F(x_0) - F^*\big).

Proof.

  1. Write F(y) - F(x) - \langle \nabla F(x), y - x\rangle as the integral of \langle \nabla F(x + s(y-x)) - \nabla F(x), y - x\rangle over s \in [0, 1], and bound the integrand by Ls\|y - x\|^2.

  2. Add the strong convexity inequality written at (x, y) and at (y, x). This step uses strong convexity only, not smoothness; Theorem 1.3 and Corollary 4.5 use it in that form.

  3. Apply (1) with y = x - \nabla F(x)/L: one step decreases F by at least \|\nabla F(x)\|^2 / (2L).

Minimising both sides of the strong convexity inequality over y gives F^* \ge F(x) - \|\nabla F(x)\|^2/(2\mu), that is \|\nabla F(x)\|^2 \ge 2\mu (F(x) - F^*).

Combining the two bounds gives F(x_{t+1}) - F^* \le (1 - \mu/L)(F(x_t) - F^*), and induction concludes. ∎

The stochastic version of this argument is Theorem 1.3; the deterministic theory is developed in Convex Optimization and Applications in Machine Learning.

0.5 Martingales

Definition 0.10 — Martingales Let (\mathcal F_n) be a filtration. An adapted integrable sequence (M_n) is a martingale if \mathbb{E}[M_n \mid \mathcal F_{n-1}] = M_{n-1}, and a supermartingale if \mathbb{E}[M_n \mid \mathcal F_{n-1}] \le M_{n-1}.

A sequence (\xi_n) of martingale increments satisfies \mathbb{E}[\xi_n \mid \mathcal F_{n-1}] = 0. Martingale increments are uncorrelated, so the variance of their sum is the sum of their variances.

Theorem 0.11 — Martingale convergence (Doob) A nonnegative supermartingale converges almost surely to a finite limit. A martingale bounded in L^2, that is with \sup_n \mathbb{E}[M_n^2] < \infty, converges almost surely and in L^2.

The proofs (upcrossing inequality) are in Williams (1991), chapters 11–12.

Corollary 0.12 — Summable noise Let (\xi_n) be martingale increments with \mathbb{E}[\xi_n^2 \mid \mathcal F_{n-1}] \le C, and (\gamma_n) deterministic with \sum_n \gamma_n^2 < \infty. Then the series \sum_n \gamma_n \xi_n converges almost surely.

Proof. The partial sums M_n = \sum_{k \le n} \gamma_k \xi_k form a martingale. By orthogonality of the increments, \mathbb{E}[M_n^2] = \sum_{k \le n} \gamma_k^2\, \mathbb{E}[\xi_k^2] \le C \sum_k \gamma_k^2 < \infty . Theorem 0.11 concludes. ∎

This is the probabilistic half of the step-size condition \sum_n \gamma_n^2 < \infty in stochastic approximation (ch. 4.2).

Key takeaways — chapter 0

  • Monte Carlo error is \sigma_h / \sqrt n in every dimension, but \sigma_h can grow exponentially with the dimension.
  • \mathrm{KL}(q\,\|\,p) \ge 0 by Jensen’s inequality, with equality only when q = p.
  • In an exponential family, \nabla A is the mean of the sufficient statistic, and maximum likelihood is a moment equation.
  • For L-smooth, \mu-strongly convex functions, gradient descent contracts by 1 - \mu/L per step.
  • Nonnegative supermartingales and L^2-bounded martingales converge almost surely; noise weighted by square-summable steps is summable.

1. The stochastic gradient algorithm

Fitting a model means minimising a risk that is an expectation, or an average over n data points with n in the millions. One exact gradient then costs a full pass over the data. The stochastic gradient algorithm replaces it with an unbiased estimate computed from a single sample.

This chapter proves when that works and at what rate, and lists what goes wrong in practice. The general theory of such noisy iterations is ch. 4.

1.1 The algorithm

Definition 1.1 — Stochastic optimisation problem and gradient oracle Let \Theta \subseteq \mathbb{R}^d be closed and convex, and Z a random variable. The problem is \min_{\theta \in \Theta} F(\theta), \qquad F(\theta) = \mathbb{E}\big[f(\theta, Z)\big]. Empirical risk minimisation is the special case where Z is uniform over the n data points, so that F = \frac1n \sum_i f_i.

A stochastic gradient oracle returns, at step t, the vector g_t = \nabla_\theta f(\theta_{t-1}, Z_t) with Z_t a fresh independent copy of Z. With \mathcal F_t = \sigma(Z_1, \dots, Z_t) it is unbiased: \mathbb{E}[g_t \mid \mathcal F_{t-1}] = \nabla F(\theta_{t-1}).

Algorithm 1.2 — Projected stochastic gradient descent (SGD) Start from \theta_0 \in \Theta and choose step sizes \gamma_t > 0. For t = 1, 2, \dots \theta_t = \Pi_\Theta\big(\theta_{t-1} - \gamma_t\, g_t\big), where \Pi_\Theta is the Euclidean projection onto \Theta (the identity when \Theta = \mathbb{R}^d).

For least squares, f(\theta, (x, y)) = \frac12 (y - x^\top \theta)^2 and the update reads \theta_t = \theta_{t-1} - \gamma_t\, (x_t^\top \theta_{t-1} - y_t)\, x_t . This is the least-mean-squares rule of adaptive signal processing.

The economics are simple. With n = 10^6 points in dimension d = 100, a full gradient costs about 2 \times 10^8 operations and one stochastic gradient about 200. One step of gradient descent therefore buys a million steps of SGD.

1.2 Convergence for strongly convex objectives

Theorem 1.3 — Rate 1/t in the strongly convex case Assume that F is \mu-strongly convex on \Theta with minimiser \theta^* \in \Theta, and that the oracle has bounded second moment: \mathbb{E}\big[\|g_t\|^2 \mid \mathcal F_{t-1}\big] \le B^2 . With the step sizes \gamma_t = 1/(\mu t), the iterates of Algorithm 1.2 satisfy, for every t \ge 1, \mathbb{E}\,\|\theta_t - \theta^*\|^2 \le \frac{B^2}{\mu^2\, t} .

Proof. Write \delta_t = \mathbb{E}\|\theta_t - \theta^*\|^2.

  1. The projection is 1-Lipschitz and fixes \theta^*, so \|\theta_t - \theta^*\| \le \|\theta_{t-1} - \gamma_t g_t - \theta^*\| .
  2. Expanding the square and conditioning on \mathcal F_{t-1}: \mathbb{E}\big[\|\theta_t - \theta^*\|^2 \mid \mathcal F_{t-1}\big] \le \|\theta_{t-1} - \theta^*\|^2 - 2\gamma_t \langle \nabla F(\theta_{t-1}), \theta_{t-1} - \theta^* \rangle + \gamma_t^2 B^2 .
  3. Optimality of \theta^* on \Theta means that \nabla F(\theta^*) makes a non-negative inner product with every \theta - \theta^*, \theta \in \Theta. Adding strong monotonicity (Proposition 0.9) yields \langle \nabla F(\theta), \theta - \theta^*\rangle \ge \mu \|\theta - \theta^*\|^2 .
  4. Taking expectations, \delta_t \le (1 - 2\mu\gamma_t)\, \delta_{t-1} + \gamma_t^2 B^2 .
  5. For t = 1 the factor is 1 - 2 = -1 \le 0, so \delta_1 \le B^2/\mu^2.
  6. For t \ge 2, assume \delta_{t-1} \le B^2 / (\mu^2 (t-1)). Then \delta_t \le \frac{B^2}{\mu^2} \Big[\frac{t-2}{t(t-1)} + \frac{1}{t^2}\Big] \le \frac{B^2}{\mu^2 t}, because \frac{t-2}{t-1} + \frac1t \le 1 is equivalent to \frac1t \le \frac{1}{t-1}. ∎

A gradient bound B is incompatible with strong convexity on all of \mathbb{R}^d, since the gradient grows linearly. This is why the theorem is stated on a bounded convex set \Theta with a projection. Corollary 4.5 removes this restriction for almost-sure convergence.

Remark 1.4 — The step size must know μ Take \gamma_t = c/t instead. If 2\mu c < 1, the rate degrades to t^{-2\mu c}, which can be arbitrarily slow.

Even without noise, on F(\theta) = \mu\theta^2/2 the iterates are \theta_t = \theta_0 \prod_{s \le t}(1 - \mu c/s), of order t^{-\mu c} (Exercise 7). Underestimating the curvature \mu, that is taking c too large, only inflates the constant; overestimating it can destroy the rate. Nemirovski, Juditsky, Lan and Shapiro (2009) made this point and advocated averaging (ch. 1.3 and Theorem 4.9).

1.3 Convex objectives and averaging

Theorem 1.5 — Rate 1/√T for the averaged iterate Assume that F is convex with a minimiser \theta^*, that \|\theta_0 - \theta^*\| \le D, and that \mathbb{E}[\|g_t\|^2 \mid \mathcal F_{t-1}] \le B^2. Run T steps with the constant step \gamma = D / (B\sqrt T), and set \bar\theta_T = \frac1T \sum_{t=0}^{T-1} \theta_t . Then \mathbb{E}\big[F(\bar\theta_T)\big] - F(\theta^*) \le \frac{DB}{\sqrt T} .

Proof.

  1. Steps 1–2 of the previous proof hold unchanged.
  2. Convexity bounds the gap F(\theta) - F(\theta^*) by the inner product \langle \nabla F(\theta), \theta - \theta^*\rangle. Rearranging step 2 and taking expectations: \mathbb{E}\big[F(\theta_{t-1})\big] - F(\theta^*) \le \frac{\delta_{t-1} - \delta_t}{2\gamma} + \frac{\gamma B^2}{2} .
  3. Summing over t = 1, \dots, T, the first term telescopes and is at most \delta_0 / (2\gamma) \le D^2/(2\gamma).
  4. Dividing by T and using Jensen’s inequality F(\bar\theta_T) \le \frac1T\sum_t F(\theta_t): \mathbb{E}\big[F(\bar\theta_T)\big] - F(\theta^*) \le \frac{D^2}{2\gamma T} + \frac{\gamma B^2}{2} .
  5. The chosen \gamma balances the two terms, each equal to DB/(2\sqrt T). ∎

For non-smooth convex problems with a stochastic oracle, no algorithm can do better than order DB/\sqrt T in the worst case (Nemirovski and Yudin, 1983). For smooth strongly convex problems, averaging with slowly decreasing steps reaches the optimal asymptotic variance without knowing \mu (Theorem 4.9).

1.4 Numerical bottlenecks

The theorems hide constants that dominate practice. Each bottleneck below has a precise source.

Proposition 1.6 — Constant step: fast forgetting, variance floor Under the assumptions of Theorem 1.3, with a constant step \gamma \le 1/(2\mu), \mathbb{E}\,\|\theta_t - \theta^*\|^2 \le (1 - 2\mu\gamma)^t\, \|\theta_0 - \theta^*\|^2 + \frac{\gamma B^2}{2\mu} .

Proof. Unroll the recursion of step 4 of Theorem 1.3, \delta_t \le (1 - 2\mu\gamma)\delta_{t-1} + \gamma^2 B^2. The noise terms add up to at most \gamma^2 B^2 \sum_{k \ge 0} (1 - 2\mu\gamma)^k = \frac{\gamma B^2}{2\mu} . ∎

The initial error is forgotten geometrically, but the iterates then fluctuate at a level proportional to \gamma. Decreasing steps remove the floor at the price of a slower start.

Example 1.7 — Four step-size schedules on a least-squares stream Inputs x \sim \mathcal N(0, H) in dimension d = 10, with the eigenvalues of H spread from \mu = 0.1 to L = 1, and outputs y = x^\top\theta^* + \varepsilon with unit noise.

The excess risk is F(\theta) - F(\theta^*) = \tfrac12 (\theta - \theta^*)^\top H\, (\theta - \theta^*). After T samples, no estimator can beat about \sigma^2 d / (2T).

import numpy as np

rng = np.random.default_rng(1)
d, T = 10, 50_000
eig = np.linspace(0.1, 1.0, d)            # Hessian spectrum: mu = 0.1, L = 1
theta_star = np.ones(d)
X = np.sqrt(eig) * rng.standard_normal((T, d))
Y = X @ theta_star + rng.standard_normal(T)   # noise variance sigma^2 = 1

def excess_risk(theta):                    # F(theta) - F(theta*)
    return 0.5 * np.sum(eig * (theta - theta_star) ** 2)

def sgd(step, average=False):
    theta, avg = np.zeros(d), np.zeros(d)
    for t in range(1, T + 1):
        x, y = X[t - 1], Y[t - 1]
        theta = theta - step(t) * (x @ theta - y) * x    # stochastic gradient step
        avg += (theta - avg) / t                          # running Polyak-Ruppert average
    return excess_risk(avg if average else theta)

mu, L = 0.1, 1.0
runs = {
    "constant step 0.05": (lambda t: 0.05, False),
    "1/(mu (t + 2L/mu))": (lambda t: 1 / (mu * (t + 2 * L / mu)), False),
    "c/t with 2 mu c = 0.2": (lambda t: 1.0 / (t + 2), False),
    "0.5/sqrt(t), averaged": (lambda t: 0.5 / np.sqrt(t), True),
}
for name, (step, avg) in runs.items():
    print(f"{name:24s} excess risk = {sgd(step, avg):.2e}")
print(f"{'statistical limit':24s} sigma^2 d / (2T) = {d / (2 * T):.2e}")

The run prints excess risks of about 2 \times 10^{-1} for the constant step (the variance floor of Proposition 1.6), 2.5 \times 10^{-4} for the tuned 1/(\mu t) schedule, and 1.5 \times 10^{-2} for c/t with 2\mu c = 0.2 (Remark 1.4).

The averaged iterate with steps 0.5/\sqrt t reaches 7.0 \times 10^{-5} \quad \text{against the limit } 1.0 \times 10^{-4}, without knowing \mu: it is statistically optimal up to fluctuations.

Key takeaways — chapter 1

  • SGD uses unbiased gradients from single samples; one iteration costs O(d) instead of O(nd).
  • Strongly convex case: steps 1/(\mu t) give \mathbb{E}\|\theta_t - \theta^*\|^2 \le B^2/(\mu^2 t), but c/t with 2\mu c < 1 is arbitrarily slow.
  • Convex case: the averaged iterate reaches DB/\sqrt T, which is optimal.
  • A constant step forgets the initialisation geometrically and then stalls at a floor proportional to \gamma.
  • Conditioning, step tuning and variance are the practical bottlenecks; averaging, preconditioning, mini-batches and variance reduction address them.

2. Bayesian inference and its computational challenges

Bayesian inference treats the parameter as a random variable and conditions on the data. Every Bayesian answer — an estimator, a credible interval, a prediction, a model comparison — is then an integral against the posterior distribution.

This chapter introduces the framework briefly, then pinpoints which integrals are hard. Each obstacle it identifies is removed by one of the later chapters.

2.1 Prior, likelihood and posterior

Definition 2.1 — Bayesian model and posterior A Bayesian model is a statistical model \{p(y \mid \theta) : \theta \in \Theta\} together with a prior density \pi(\theta) on \Theta \subseteq \mathbb{R}^d. Given data y, Bayes’ formula defines the posterior density \pi(\theta \mid y) = \frac{p(y \mid \theta)\, \pi(\theta)}{p(y)}, \qquad p(y) = \int_\Theta p(y \mid \theta)\, \pi(\theta)\, d\theta . The normalising constant p(y) is the evidence, or marginal likelihood. The posterior predictive density of a new observation is p(y_{\mathrm{new}} \mid y) = \int_\Theta p(y_{\mathrm{new}} \mid \theta)\, \pi(\theta \mid y)\, d\theta .

The posterior is known up to the constant p(y) as soon as the likelihood and the prior can be evaluated. Much of the course is about doing statistics with a density known only up to a constant.

2.2 Bayes estimators

Definition 2.2 — Bayes estimator Let \ell(\theta, a) \ge 0 be a loss measuring the cost of the decision a when the parameter is \theta. The Bayes estimator minimises the posterior expected loss: \hat a(y) \in \arg\min_a\ \mathbb{E}\big[\ell(\theta, a) \mid y\big] . A credible region of level 1 - \alpha is a set C(y) with posterior probability 1 - \alpha.

Proposition 2.3 — Three losses, three estimators

  1. The quadratic loss \|\theta - a\|^2 gives the posterior mean \mathbb{E}[\theta \mid y].
  2. In dimension one, the absolute loss |\theta - a| gives a posterior median.
  3. The loss \mathbf 1\{\|\theta - a\| > \varepsilon\} gives, as \varepsilon \to 0 and for a continuous unimodal posterior, the posterior mode, also called the maximum a posteriori (MAP) estimator.

Proof.

  1. With m = \mathbb{E}[\theta \mid y], the cross term has zero posterior mean, so \mathbb{E}\big[\|\theta - a\|^2 \mid y\big] = \mathbb{E}\big[\|\theta - m\|^2 \mid y\big] + \|m - a\|^2 , which is minimal at a = m.

  2. The function a \mapsto \mathbb{E}[|\theta - a| \mid y] is convex. Its right derivative is P(\theta \le a \mid y) - P(\theta > a \mid y), which changes sign at a median.

  3. The expected loss is 1 - P(\|\theta - a\| \le \varepsilon \mid y). For small \varepsilon it is close to 1 - \mathrm{vol}(B_\varepsilon)\, \pi(a \mid y), which is minimal where the posterior density is maximal. ∎

Example 2.4 — Beta–Binomial conjugacy, by hand Observe k successes in n Bernoulli trials with success probability \theta, and take the prior \mathrm{Beta}(a, b).

  • The posterior is proportional to the product of the likelihood and the prior, \theta^{k}(1-\theta)^{n-k} \cdot \theta^{a-1}(1-\theta)^{b-1} , so it is \mathrm{Beta}(a + k,\, b + n - k). Prior and posterior belong to the same family: this is called conjugacy.
  • With a = b = 2, n = 10 and k = 7, the posterior is \mathrm{Beta}(9, 5).
  • Its mean is 9/14 = 0.643, its mode (MAP) is 8/12 = 0.667, while the maximum-likelihood estimate is 0.7.
  • The posterior mean is a weighted average of the prior mean 1/2 (weight 4/14) and of the empirical frequency 0.7 (weight 10/14): the prior acts like four extra observations.

2.3 Large samples: Bernstein–von Mises and Laplace

Theorem 2.5 — Bernstein–von Mises (statement) Let Y_1, \dots, Y_n be independent with density p(\cdot \mid \theta_0) in a regular parametric model with non-singular Fisher information I(\theta_0). Assume that the prior is continuous and positive at \theta_0, and that uniformly consistent tests exist.

Then, with \hat\theta_n the maximum-likelihood estimator, in probability under \theta_0, \Big\| \Pi(\cdot \mid Y_{1:n}) - \mathcal N\big(\hat\theta_n,\ \tfrac1n I(\theta_0)^{-1}\big) \Big\|_{\mathrm{TV}} \longrightarrow 0 . A proof is in van der Vaart (1998), Theorem 10.1.

The posterior forgets the prior and becomes Gaussian around the maximum-likelihood estimator. Credible sets then become asymptotic confidence sets, and the posterior mean, median and mode agree to first order.

Proposition 2.6 — Laplace approximation of the evidence Let \hat\theta be the posterior mode and H the Hessian of -\log\big(p(y \mid \theta)\pi(\theta)\big) at \hat\theta, assumed positive definite. Then p(y) \approx p(y \mid \hat\theta)\, \pi(\hat\theta)\, (2\pi)^{d/2} \det(H)^{-1/2} . For n independent observations the relative error is O(1/n) under smoothness assumptions.

Proof. Sketch. Expand \log(p(y \mid \theta)\pi(\theta)) to second order at \hat\theta. The gradient vanishes, and the quadratic term is the negative quadratic form of H applied to \theta - \hat\theta, divided by 2.

Integrating the resulting Gaussian function gives the formula. The Hessian grows linearly with n, so the posterior mass concentrates in a region of radius n^{-1/2} where the cubic remainder is O(n^{-1/2}). Its odd part integrates to zero, which leaves a relative error of order 1/n. ∎

Example 2.7 — Posterior summaries and the evidence, numerically The evidence of Example 2.4 has a closed form, p(y) = \binom{n}{k} \frac{B(a + k,\, b + n - k)}{B(a, b)} = 120 \times \frac{6}{6435} = 0.11189 . The code compares it with adaptive quadrature and with the Laplace approximation of Proposition 2.6.

import numpy as np
from scipy import stats, special, integrate

a, b, n, k = 2, 2, 10, 7                     # Beta(2, 2) prior, 7 successes out of 10
post = stats.beta(a + k, b + n - k)          # conjugacy: Beta(9, 5)
mode = (a + k - 1) / (a + b + n - 2)
print(f"posterior mean {post.mean():.4f}  median {post.median():.4f}  "
      f"MAP {mode:.4f}  MLE {k / n:.4f}")
print("95% credible interval", np.round(post.interval(0.95), 3))

# evidence p(y): closed form, adaptive quadrature, Laplace approximation
log_ev = np.log(special.comb(n, k)) + special.betaln(a + k, b + n - k) - special.betaln(a, b)
unnorm = lambda p: stats.binom.pmf(k, n, p) * stats.beta.pdf(p, a, b)
quad, _ = integrate.quad(unnorm, 0, 1)
f = lambda p: np.log(unnorm(p))
h = 1e-4
curv = -(f(mode + h) - 2 * f(mode) + f(mode - h)) / h ** 2   # -(log density)'' at the mode
laplace = unnorm(mode) * np.sqrt(2 * np.pi / curv)
print(f"evidence: exact {np.exp(log_ev):.5f}  quadrature {quad:.5f}  Laplace {laplace:.5f}")

The run prints the median 0.650 and the equal-tailed 95 % credible interval [0.386, 0.861]. Quadrature reproduces the evidence to five digits, because the parameter is one-dimensional.

The Laplace approximation gives 0.1183, a relative error of about 6 % with ten observations; that error shrinks like 1/n.

These asymptotics fail exactly where computational statistics is needed: small samples, multimodal posteriors, parameters on a boundary, and latent-variable models whose number of hidden variables grows with n.

2.4 Where the computations get hard

Key formula — every Bayesian answer is a ratio of integrals \mathbb{E}\big[h(\theta) \mid y\big] = \frac{\int_\Theta h(\theta)\, p(y \mid \theta)\, \pi(\theta)\, d\theta}{\int_\Theta p(y \mid \theta)\, \pi(\theta)\, d\theta}

Four obstacles make this ratio hard to compute, and each is removed by a later chapter.

  1. Dimension. A grid with m points per axis needs m^d evaluations: 10^{20} for m = 10 and d = 20. Monte Carlo (ch. 0.1) avoids the grid but needs samples from the posterior, which is known only up to p(y). Rejection and importance sampling (ch. 5) work in small dimension; MCMC (ch. 6) works in general; adaptive MCMC and tempering (ch. 8) make it robust.
  2. Hidden variables. In many models the likelihood is itself an integral over unobserved variables. Even the maximum-likelihood or MAP estimator then requires EM (ch. 3), and stochastic versions of EM when the E-step is an intractable integral (ch. 7).
  3. No likelihood at all. Simulators in population genetics or epidemiology can generate data but cannot evaluate p(y \mid \theta). Approximate Bayesian computation (ch. 9) works with simulations only.
  4. Large data. When each evaluation of the likelihood costs n operations, stochastic gradients (ch. 1) and stochastic approximation (ch. 4) replace full passes over the data by single samples.

The constant p(y) cancels in the ratio \pi(\theta' \mid y)/\pi(\theta \mid y). This simple remark is what makes the Metropolis–Hastings algorithm (ch. 6.2) possible.

2.5 Latent-variable models

Definition 2.8 — Latent-variable (incomplete-data) model The complete data are a pair (y, z) with density p(y, z; \theta), of which only y is observed. The likelihood of the observed data is p(y; \theta) = \int p(y, z; \theta)\, dz , and the conditional density of the hidden variables, p(z \mid y; \theta) = p(y, z; \theta)/p(y; \theta), plays the role of a posterior.

Example 2.9 — Three latent-variable models of the course

  • Gaussian mixture. z_i \in \{1, \dots, K\} with P(z_i = k) = w_k, and y_i \mid z_i = k \sim \mathcal N(\mu_k, \sigma_k^2). The integral is a finite sum, but the log-likelihood is a sum of logarithms of sums, with no closed-form maximiser (ch. 3.4).
  • Mixed-effects model. Subject i has a random parameter \varphi_i \sim \mathcal N(\mu, \Omega), and y_{ij} = g(t_{ij}, \varphi_i) + \sigma \varepsilon_{ij}. When g is nonlinear, as in pharmacokinetics or growth curves, the integral over \varphi_i has no closed form (ch. 7).
  • Random-effects logistic regression. Given \varphi_i \sim \mathcal N(\mu, \omega^2), the answers y_{ij} are Bernoulli with success probability \mathrm{logit}^{-1}(\varphi_i), the logistic function 1/(1 + e^{-\varphi_i}). This is the running example of ch. 7.

A Bayesian model is itself a latent-variable model in which \theta is the hidden variable. This is why the same simulation tools serve both for computing posteriors and for maximising likelihoods with hidden variables.

Key takeaways — chapter 2

  • Posterior \propto likelihood \times prior; the normalising constant p(y) is an integral, usually unknown.
  • Quadratic, absolute and 0–1 losses give the posterior mean, median and mode.
  • With many observations the posterior is approximately Gaussian (Bernstein–von Mises), and the Laplace approximation estimates p(y) with relative error O(1/n).
  • The obstacles are dimension, hidden variables, intractable likelihoods and data size; they motivate MCMC, EM, ABC and stochastic gradients respectively.
  • Latent-variable models have likelihoods defined by integrals over hidden variables.

3. Majorize–Minimize and the EM algorithm

When the likelihood is an integral over hidden variables, direct maximisation is awkward, while the complete-data likelihood is often simple. The EM algorithm exploits this: at each step it maximises a surrogate that touches the log-likelihood from below.

Seen from further away, EM is one instance of a general principle, Majorize–Minimize, which we state first.

3.1 The Majorize–Minimize principle

Definition 3.1 — Majorizing surrogate and MM algorithm A function g(\cdot \mid \theta') majorizes F at \theta' if g(\theta \mid \theta') \ge F(\theta) \ \text{ for all } \theta, \qquad g(\theta' \mid \theta') = F(\theta') . The Majorize–Minimize (MM) algorithm iterates \theta_{k+1} \in \arg\min_\theta\, g(\theta \mid \theta_k) . For a maximisation problem, one minorizes and maximises instead: this is the same algorithm applied to -F.

Proposition 3.2 — Descent property Every MM iteration decreases the objective: F(\theta_{k+1}) \le F(\theta_k) .

Proof. The chain F(\theta_{k+1}) \le g(\theta_{k+1} \mid \theta_k) \le g(\theta_k \mid \theta_k) = F(\theta_k) uses the majorization, then the minimisation step, then the tangency. ∎

The proof only uses the decrease of the surrogate from \theta_k to \theta_{k+1}. Any decrease of the surrogate, not necessarily its minimum, keeps the descent property.

Example 3.3 — Two classical surrogates

  • Quadratic surrogate. If F is L-smooth, the descent lemma (Proposition 0.9) gives the majorizer g(\theta \mid \theta') = F(\theta') + \langle \nabla F(\theta'), \theta - \theta'\rangle + \frac{L}{2}\|\theta - \theta'\|^2 . Its minimiser is \theta' - \nabla F(\theta')/L: gradient descent with step 1/L is an MM algorithm.
  • Absolute value. For r' \ne 0, the inequality (|r| - |r'|)^2 \ge 0 gives |r| \le \frac{r^2}{2|r'|} + \frac{|r'|}{2} , with equality at r = \pm r'. For least absolute deviations, the surrogate is a weighted least-squares problem with weights 1/|r_i(\theta_k)|: iteratively reweighted least squares (Exercise 8).

Lange, Hunter and Yang (2000) and Hunter and Lange (2004) survey MM algorithms. Mairal (2015) extends them to large finite sums with incremental surrogates.

3.2 EM as a minorize–maximize algorithm

Consider a latent-variable model (Definition 2.8) and the log-likelihood \ell(\theta) = \log p(y; \theta).

Proposition 3.4 — Evidence lower bound For every \theta and every density q on the hidden variables, \ell(\theta) = \underbrace{\mathbb{E}_q\big[\log p(y, Z; \theta) - \log q(Z)\big]}_{\mathcal L(q,\, \theta)} + \mathrm{KL}\big(q \,\|\, p(\cdot \mid y; \theta)\big) . Consequently \mathcal L(q, \theta) \le \ell(\theta), with equality if and only if q = p(\cdot \mid y; \theta).

Proof. For every z, Bayes’ formula gives \log p(y; \theta) = \log p(y, z; \theta) - \log p(z \mid y; \theta) . Add and subtract \log q(z), then integrate against q. The inequality and its equality case follow from Gibbs’ inequality (Proposition 0.5). ∎

Algorithm 3.5 — Expectation–Maximisation (Dempster, Laird and Rubin, 1977) Start from \theta_0. For k = 0, 1, \dots

  • E-step: compute the expected complete-data log-likelihood Q(\theta \mid \theta_k) = \mathbb{E}_{\theta_k}\big[\log p(y, Z; \theta) \mid y\big] .
  • M-step: set \theta_{k+1} \in \arg\max_\theta\, Q(\theta \mid \theta_k) .

With q_k = p(\cdot \mid y; \theta_k), the lower bound \mathcal L(q_k, \theta) equals Q(\theta \mid \theta_k) plus a term that does not depend on \theta.

EM therefore maximises, at each step, a minorizer of \ell that touches it at \theta_k: it is an MM algorithm for -\ell.

Theorem 3.6 — EM increases the likelihood Every EM iteration satisfies \ell(\theta_{k+1}) \ge \ell(\theta_k) .

Proof. With q_k = p(\cdot \mid y; \theta_k), Proposition 3.4 and the M-step give \ell(\theta_{k+1}) \ge \mathcal L(q_k, \theta_{k+1}) \ge \mathcal L(q_k, \theta_k) = \ell(\theta_k) . The first inequality is the lower bound, the second is the M-step, and the equality is the case q = p(\cdot \mid y; \theta_k). ∎

Neal and Hinton (1998) read EM as coordinate ascent on \mathcal L(q, \theta): the E-step maximises over q, the M-step over \theta. This view justifies partial E-steps, incremental variants and variational EM, where q is restricted to a tractable family.

3.3 Exponential-family complete data

Assume that the complete data form a curved exponential family (Definition 0.6), p(y, z; \theta) = h(y, z) \exp\big(\langle \varphi(\theta), S(y, z) \rangle - \psi(\theta)\big), with \varphi : \mathbb{R}^p \to \mathbb{R}^q. Then, up to a constant, Q(\theta \mid \theta_k) = \langle \varphi(\theta), s_k \rangle - \psi(\theta), where s_k is the conditional expectation of S(y, Z) under \theta_k.

Algorithm 3.7 — EM in sufficient statistics Define the expected statistic and the M-step map \bar s(\theta) = \mathbb{E}_\theta\big[S(y, Z) \mid y\big], \qquad \bar\theta(s) = \arg\max_\theta\ \big\{\langle \varphi(\theta), s\rangle - \psi(\theta)\big\} . EM is the fixed-point iteration s_{k+1} = \bar s(\bar\theta(s_k)), with \theta_k = \bar\theta(s_k).

The E-step is an expectation of a fixed function; the M-step is usually explicit, as for complete-data maximum likelihood. Stochastic versions of EM (ch. 7) keep the M-step and replace the expectation \bar s by simulation.

3.4 Gaussian mixtures

Example 3.8 — EM for a Gaussian mixture For K one-dimensional components with weights w_k, means \mu_k and variances \sigma_k^2:

  • E-step: the responsibilities are the posterior probabilities of the labels, r_{ik} = \frac{w_k\, \mathcal N(y_i; \mu_k, \sigma_k^2)}{\sum_j w_j\, \mathcal N(y_i; \mu_j, \sigma_j^2)} .
  • M-step: with n_k = \sum_i r_{ik}, w_k = \frac{n_k}{n}, \qquad \mu_k = \frac{1}{n_k}\sum_i r_{ik}\, y_i, \qquad \sigma_k^2 = \frac{1}{n_k}\sum_i r_{ik} (y_i - \mu_k)^2 .
  • Derivation: up to a constant, Q = \sum_{i,k} r_{ik}\big[\log w_k + \log \mathcal N(y_i; \mu_k, \sigma_k^2)\big] . A Lagrange multiplier for \sum_k w_k = 1 gives w_k \propto n_k, and the Gaussian terms are weighted maximum-likelihood problems.

The code fits two components to n = 1000 points drawn with weights (0.3, 0.7), means (3, 0) and unit variances, and checks the monotonicity of Theorem 3.6.

import numpy as np
from scipy.stats import norm

rng = np.random.default_rng(3)
n = 1000
z = rng.random(n) < 0.3                                   # hidden labels, P(z = 1) = 0.3
y = np.where(z, rng.normal(3.0, 1.0, n), rng.normal(0.0, 1.0, n))

def loglik(w, m, s):
    return np.log(w * norm.pdf(y, m[0], s[0]) + (1 - w) * norm.pdf(y, m[1], s[1])).sum()

w, m, s = 0.5, np.array([1.0, -1.0]), np.array([2.0, 2.0])  # w = weight of component 0
trace = [loglik(w, m, s)]
for it in range(200):
    p0 = w * norm.pdf(y, m[0], s[0])
    p1 = (1 - w) * norm.pdf(y, m[1], s[1])
    r = p0 / (p0 + p1)                                     # E-step: responsibilities
    w = r.mean()                                           # M-step: weighted moments
    m = np.array([r @ y / r.sum(), (1 - r) @ y / (1 - r).sum()])
    s = np.sqrt(np.array([r @ (y - m[0]) ** 2 / r.sum(),
                          (1 - r) @ (y - m[1]) ** 2 / (1 - r).sum()]))
    trace.append(loglik(w, m, s))

trace = np.array(trace)
print("log-likelihood at iterations 0, 1, 5, 20, 200:", np.round(trace[[0, 1, 5, 20, 200]], 2))
print("monotone:", bool(np.all(np.diff(trace) > -1e-9)))
print(f"weights ({w:.3f}, {1 - w:.3f})  means {np.round(m, 3)}  std {np.round(s, 3)}")

The log-likelihood goes through -2109.1, -1956.1, -1923.5, -1913.8 and -1900.7, and never decreases. It still gains 13 units between iterations 20 and 200: the components overlap, so EM is slow (Proposition 3.10).

The final estimates are weights (0.268, 0.732), means (3.21, 0.06) and standard deviations (0.94, 1.07).

The likelihood of a Gaussian mixture is unbounded: centring one component on a data point and letting its variance tend to zero sends \ell to +\infty. EM finds local maxima, not this degenerate supremum. In practice one bounds the variances from below or adds a prior and runs MAP-EM, which adds \log \pi(\theta) to Q.

3.5 Convergence and speed

Theorem 3.9 — Limit points of EM (Wu, 1983; statement) Assume that \ell is continuous, that the level set \{\theta : \ell(\theta) \ge \ell(\theta_0)\} is compact, and that Q(\theta \mid \theta') is continuous in both arguments and differentiable in \theta.

Then \ell(\theta_k) increases to a limit \ell^*, and every limit point of (\theta_k) is a stationary point of \ell with \ell = \ell^*. These may be local maxima or saddle points, not necessarily the global maximum.

Proposition 3.10 — Rate of EM: the fraction of missing information Let \theta^* be a limit of EM, and write M for the EM map \theta_k \mapsto \theta_{k+1}. Define the complete, missing and observed informations at \theta^*: I_c = -\mathbb{E}\big[\nabla^2 \log p(y, Z; \theta) \mid y\big], \quad I_m = -\mathbb{E}\big[\nabla^2 \log p(Z \mid y; \theta) \mid y\big], \quad I_{\mathrm{obs}} = -\nabla^2 \ell(\theta^*) , so that I_{\mathrm{obs}} = I_c - I_m. If I_c is invertible, then DM(\theta^*) = I_c^{-1} I_m = \mathrm{Id} - I_c^{-1} I_{\mathrm{obs}} .

Proof.

  1. The M-step gives \nabla_\theta Q(M(\theta') \mid \theta') = 0 for all \theta'. Differentiate in \theta' at \theta^*, a fixed point: \nabla^2_{\theta\theta} Q\, DM(\theta^*) + \nabla^2_{\theta\theta'} Q = 0 .
  2. By definition, the Hessian of Q(\cdot \mid \theta^*) at \theta^* is -I_c.
  3. The complete log-likelihood is \ell(\theta) + \log p(z \mid y; \theta) and \nabla \ell(\theta^*) = 0. Hence the cross derivative is the conditional covariance of the score \nabla \log p(Z \mid y; \theta^*). By the information identity, this covariance equals I_m.
  4. Hence -I_c\, DM + I_m = 0. ∎

Near \theta^*, EM converges linearly with rate the spectral radius of I_c^{-1} I_m, the largest fraction of missing information. Well-separated mixture components give fast convergence, and overlapping ones a rate close to 1, as in Example 3.8.

Variants Generalised EM only increases Q in the M-step, and ECM (Meng and Rubin, 1993) does it by conditional maximisations. Accelerations such as SQUAREM (Varadhan and Roland, 2008) extrapolate the EM map.

Louis (1982) computes the observed information I_{\mathrm{obs}} = I_c - I_m from EM quantities, which gives standard errors. Online EM (Cappé and Moulines, 2009) processes data streams with a stochastic approximation of \bar s, the idea of ch. 7.

Key takeaways — chapter 3

  • MM minimises a surrogate that majorizes the objective and touches it at the current point; the objective decreases at every step.
  • The log-likelihood is the lower bound \mathcal L(q, \theta) plus a KL gap: EM alternates exact maximisation over q (E-step) and over \theta (M-step).
  • EM never decreases the likelihood, and its limit points are stationary points (Wu, 1983).
  • In exponential families EM iterates s \mapsto \bar s(\bar\theta(s)) on expected sufficient statistics.
  • EM converges linearly at a rate equal to the largest fraction of missing information, I_c^{-1} I_m.

4. Stochastic approximation

SGD (ch. 1), the stochastic versions of EM (ch. 7) and adaptive MCMC (ch. 8) share one structure: a parameter moves along a noisy estimate of a mean field, with decreasing steps. Stochastic approximation, started by Robbins and Monro in 1951, studies this structure once and for all.

This chapter gives the convergence conditions that the syllabus asks for, with a complete proof in the Lyapunov case, then the rates and the effect of averaging.

4.1 The Robbins–Monro algorithm

Definition 4.1 — Robbins–Monro algorithm Let H(\theta, x) be a function and X a random variable such that the mean field h(\theta) = \mathbb{E}\big[H(\theta, X)\big] is defined for all \theta \in \mathbb{R}^d. The goal is a root \theta^* of h, using only the values of H.

With independent copies X_n of X and steps \gamma_n > 0, the algorithm is \theta_n = \theta_{n-1} + \gamma_n H(\theta_{n-1}, X_n) = \theta_{n-1} + \gamma_n \big(h(\theta_{n-1}) + \xi_n\big), where \xi_n = H(\theta_{n-1}, X_n) - h(\theta_{n-1}) is a martingale increment for \mathcal F_n = \sigma(X_1, \dots, X_n).

Example 4.2 — Four instances

  • Mean. H(\theta, x) = x - \theta with \gamma_n = 1/n gives \theta_n = \frac1n\sum_{k \le n} X_k, the empirical mean.
  • SGD. H(\theta, z) = -\nabla_\theta f(\theta, z) gives the mean field h = -\nabla F, whose roots are the critical points of F.
  • Quantile. H(\theta, x) = \alpha - \mathbf 1\{x \le \theta\} gives h(\theta) = \alpha - F_X(\theta), whose root is the \alpha-quantile of X. No density is ever evaluated.
  • Later in the course. SAEM (ch. 7) and adaptive Metropolis (ch. 8) update sufficient statistics and proposal covariances with exactly this recursion.

4.2 Step-size conditions

Key result — the Robbins–Monro step-size conditions \sum_{n \ge 1} \gamma_n = \infty, \qquad \sum_{n \ge 1} \gamma_n^2 < \infty

The first condition lets the iterates travel any distance: the deterministic part moves by \sum_n \gamma_n h(\theta_{n-1}). The second makes the accumulated noise \sum_n \gamma_n \xi_n converge (Corollary 0.12). Steps \gamma_n = \gamma_0 n^{-a} satisfy both when 1/2 < a \le 1.

4.3 The Robbins–Siegmund lemma

Lemma 4.3 — Robbins and Siegmund (1971) Let (a_n) and (b_n) be deterministic nonnegative sequences with finite sums, and (V_n), (c_n) nonnegative adapted sequences with c_n measurable with respect to \mathcal F_{n-1}. Assume that \mathbb{E}[V_n \mid \mathcal F_{n-1}] \le (1 + a_n)\, V_{n-1} + b_n - c_n \quad \text{for all } n . Then V_n converges almost surely to a finite limit, and \sum_n c_n < \infty almost surely.

Proof.

  1. Let \alpha_n = \prod_{k \le n} (1 + a_k). It increases to a finite limit \alpha_\infty because \sum a_k < \infty, and \alpha_n \ge 1.
  2. Divide by \alpha_n: with V'_n = V_n/\alpha_n, b'_n = b_n/\alpha_n and c'_n = c_n/\alpha_n, \mathbb{E}[V'_n \mid \mathcal F_{n-1}] \le V'_{n-1} + b'_n - c'_n .
  3. Set U_n = V'_n + \sum_{k \le n} c'_k + \sum_{k > n} b'_k. Step 2 gives \mathbb{E}[U_n \mid \mathcal F_{n-1}] \le U_{n-1}. Since U_n \ge 0, Theorem 0.11 shows that U_n converges almost surely to a finite limit.
  4. Because V'_n \ge 0, the partial sums \sum_{k \le n} c'_k \le U_n are bounded, so \sum_k c'_k < \infty. Then V'_n converges, as a difference of convergent sequences.
  5. Multiplying back by \alpha_n \to \alpha_\infty, V_n converges, and \sum_k c_k \le \alpha_\infty \sum_k c'_k < \infty. ∎

4.4 Almost-sure convergence

Theorem 4.4 — Convergence of Robbins–Monro, Lyapunov form Let \theta^* be a root of h and c(\theta) = -\langle \theta - \theta^*, h(\theta) \rangle. Assume:

  1. c(\theta) \ge 0 for all \theta, and c is bounded below by a positive constant on every annulus \varepsilon \le \|\theta - \theta^*\| \le 1/\varepsilon, 0 < \varepsilon < 1;
  2. the growth condition holds: for all \theta, \mathbb{E}\|H(\theta, X)\|^2 \le C\,(1 + \|\theta - \theta^*\|^2) ;
  3. the step-size conditions of ch. 4.2.

Then \theta_n \to \theta^* almost surely.

Proof.

  1. Let V_n = \|\theta_n - \theta^*\|^2. Expanding the recursion, V_n = V_{n-1} + 2\gamma_n \langle \theta_{n-1} - \theta^*, H(\theta_{n-1}, X_n) \rangle + \gamma_n^2 \|H(\theta_{n-1}, X_n)\|^2 .
  2. Conditioning on \mathcal F_{n-1} and using assumption 2: \mathbb{E}[V_n \mid \mathcal F_{n-1}] \le (1 + C\gamma_n^2)\, V_{n-1} + C\gamma_n^2 - 2\gamma_n\, c(\theta_{n-1}) .
  3. Lemma 4.3, applied with a_n = b_n = C\gamma_n^2, gives V_n \to V_\infty almost surely, and the series \sum_n \gamma_n c(\theta_{n-1}) converges almost surely.
  4. Suppose V_\infty > 0 on an event of positive probability. On that event, \|\theta_n - \theta^*\| converges to \sqrt{V_\infty} > 0, so \theta_n eventually stays in an annulus \varepsilon \le \|\theta - \theta^*\| \le 1/\varepsilon, for some rational \varepsilon.
  5. There c(\theta_{n-1}) \ge \eta > 0 by assumption 1, so \sum_n \gamma_n c(\theta_{n-1}) = \infty because \sum_n \gamma_n = \infty. This contradicts step 3, hence V_\infty = 0 almost surely. ∎

Corollary 4.5 — Almost-sure convergence of SGD Let F be \mu-strongly convex with minimiser \theta^*. Assume that the stochastic gradients satisfy the growth condition of Theorem 4.4. Then unprojected SGD with \sum \gamma_n = \infty and \sum \gamma_n^2 < \infty converges almost surely to \theta^*.

Proof. Here h = -\nabla F, so Proposition 0.9 gives c(\theta) = \langle \nabla F(\theta), \theta - \theta^* \rangle \ge \mu \|\theta - \theta^*\|^2 . Assumption 1 holds, and Theorem 4.4 applies. ∎

For least squares, the growth condition holds as soon as the inputs have a finite fourth moment and the noise, independent of the inputs, a finite second moment. No bounded domain is needed, unlike Theorem 1.3.

Example 4.6 — Quantile estimation satisfies the assumptions For H(\theta, x) = \alpha - \mathbf 1\{x \le \theta\} with F_X continuous and strictly increasing:

  • c(\theta) = (\theta - \theta^*)(F_X(\theta) - \alpha) is positive for \theta \ne \theta^* and bounded below on every annulus;
  • |H| \le 1, so the growth condition holds with C = 1.

Theorem 4.4 shows that the recursive quantile estimator converges almost surely, without ever sorting the data.

4.5 The ODE method

When the mean field has several roots, as for non-convex SGD or for EM-like fixed points, no single quadratic Lyapunov function exists. The standard tool compares the iterates with the solutions of the ordinary differential equation \dot\theta = h(\theta): the steps \gamma_n play the role of time increments, and the noise averages out.

Theorem 4.7 — ODE method (statement) Assume:

  1. h is continuous, and there is a C^1 function V with \langle \nabla V(\theta), h(\theta) \rangle \le 0 for all \theta;
  2. the set \mathcal L of points where \langle \nabla V, h \rangle = 0 is such that V(\mathcal L) has empty interior;
  3. the sequence (\theta_n) stays almost surely in a compact set;
  4. \sum_n \gamma_n = \infty and the series \sum_n \gamma_n \xi_n converges almost surely.

Then the distance from \theta_n to \mathcal L tends to 0 almost surely. See Kushner and Yin (2003), Benaïm (1999), and Delyon, Lavielle and Moulines (1999) for the form used by SAEM.

For SGD, V = F and \mathcal L is the set of critical points. For SAEM, V is minus the log-likelihood read through the M-step map (Proposition 7.4).

Assumption 3, stability, is the delicate one in practice. A classical remedy is truncation on randomly varying bounds: the iterate is re-initialised whenever it leaves a compact set, and the compact set grows after each re-initialisation (Andrieu, Moulines and Priouret, 2005).

4.6 Rates and averaging

Theorem 4.8 — Central limit theorem (statement) Assume that \theta_n \to \theta^* and that the Jacobian A = Dh(\theta^*) has eigenvalues with negative real parts. Let \Gamma be the limiting covariance of the noise \xi_n, and take \gamma_n = \gamma_0 n^{-a}.

  • If 1/2 < a < 1, then \gamma_n^{-1/2}(\theta_n - \theta^*) converges in law to \mathcal N(0, \Sigma), where A\Sigma + \Sigma A^\top + \Gamma = 0.
  • If a = 1 and \gamma_0 A + \mathrm{Id}/2 also has eigenvalues with negative real parts, then \sqrt n\,(\theta_n - \theta^*) converges in law to a centred Gaussian.

In dimension 1, with h'(\theta^*) = -\lambda < 0 and a = 1, the asymptotic variance is \frac{\gamma_0^2\, \Gamma}{2\gamma_0 \lambda - 1} \qquad (\gamma_0 \lambda > 1/2), minimal at \gamma_0 = 1/\lambda where it equals \Gamma/\lambda^2. References: Benveniste, Métivier and Priouret (1990); Kushner and Yin (2003).

The optimal step 1/(\lambda n) requires the unknown slope \lambda; when \gamma_0\lambda < 1/2 the error decays only like n^{-\gamma_0\lambda}, the phenomenon of Remark 1.4. Averaging removes this dependence.

Theorem 4.9 — Polyak–Ruppert averaging (Polyak and Juditsky, 1992) Under the assumptions of Theorem 4.8 with 1/2 < a < 1, the average \bar\theta_n = \frac1n \sum_{k=1}^n \theta_k satisfies \sqrt n\, (\bar\theta_n - \theta^*) \xrightarrow{\ \mathcal L\ } \mathcal N\big(0,\ A^{-1}\Gamma A^{-\top}\big). This covariance is the smallest achievable by any such recursion, and it is reached without knowing A.

Proof. Sketch for a linear mean field h(\theta) = A(\theta - \theta^*).

  1. The recursion gives \theta_{k-1} - \theta^* = A^{-1}\Big[\frac{\theta_k - \theta_{k-1}}{\gamma_k} - \xi_k\Big] .
  2. Averaging over k \le n: \bar\theta_{n} - \theta^* \approx -A^{-1}\,\frac1n \sum_{k \le n} \xi_k + \frac{A^{-1}}{n} \sum_{k \le n} \frac{\theta_k - \theta_{k-1}}{\gamma_k} .
  3. An Abel summation shows that the second term is of order 1/(n\gamma_n) times the size of the iterates’ error. This is o(n^{-1/2}) precisely when a < 1.
  4. The martingale central limit theorem applied to the first term gives the covariance A^{-1}\Gamma A^{-\top}/n. ∎

Example 4.10 — The 0.9-quantile of an exponential law For X \sim \mathrm{Exp}(1) and \alpha = 0.9:

  • the target is \theta^* = \log 10 = 2.3026;
  • the slope is h'(\theta^*) = -f_X(\theta^*) = -0.1, so \lambda = 0.1;
  • the noise variance at \theta^* is \Gamma = \alpha(1 - \alpha) = 0.09;
  • the optimal asymptotic variance is \Gamma / \lambda^2 = 9, the same as for the empirical quantile.

With \gamma_n = 1/n, \gamma_0\lambda = 0.1 < 1/2 and the error decays like n^{-0.1} only. With \gamma_n = 10/n the step is optimal. Averaging with \gamma_n = n^{-2/3} needs no knowledge of \lambda.

import numpy as np

rng = np.random.default_rng(4)
alpha, N = 0.9, 100_000
target = np.log(10.0)                      # 0.9-quantile of Exp(1); f(target) = 0.1
X = rng.exponential(size=N)

def robbins_monro(step, average=False):
    th, avg = 0.0, 0.0
    for n in range(1, N + 1):
        th += step(n) * (alpha - (X[n - 1] <= th))   # H(theta, X) = alpha - 1{X <= theta}
        avg += (th - avg) / n
    return avg if average else th

for name, step, av in [("gamma_n = 1/n", lambda n: 1.0 / n, False),
                       ("gamma_n = 10/n", lambda n: 10.0 / n, False),
                       ("n^(-2/3), averaged", lambda n: n ** (-2 / 3), True)]:
    print(f"{name:20s} error = {robbins_monro(step, av) - target:+.4f}")

After N = 10^5 samples the errors are -0.300, +0.005 and -0.003. The optimal standard deviation is 3/\sqrt{N} \approx 0.0095: the badly scaled step is thirty standard deviations away, while the averaged iterate is within one. Exercise 10 checks the variance 9 over replications.

Key takeaways — chapter 4

  • Robbins–Monro finds a root of a mean field h(\theta) = \mathbb{E}[H(\theta, X)] from noisy evaluations, with \sum \gamma_n = \infty and \sum \gamma_n^2 < \infty.
  • The Robbins–Siegmund lemma turns an almost-supermartingale inequality into almost-sure convergence.
  • With a Lyapunov inequality around a unique root, the iterates converge almost surely; SGD and recursive quantiles are special cases.
  • The ODE method handles several roots, provided the iterates remain bounded.
  • Steps c/n are optimal only if c matches the unknown slope; Polyak–Ruppert averaging with slower steps reaches the optimal covariance A^{-1}\Gamma A^{-\top} automatically.

5. Simulation of random variables

Every stochastic algorithm of this course consumes random variables: the samples of SGD, the hidden variables drawn by stochastic EM, the proposals of MCMC, the synthetic data sets of ABC. This chapter builds non-uniform random variables from uniform ones, by inversion, transformation and rejection.

It then introduces importance sampling, which changes the sampling distribution instead of the samples.

5.1 Inversion

We assume a generator of independent uniform variables on (0, 1). NumPy’s default_rng uses the PCG64 generator; the Mersenne Twister (Matsumoto and Nishimura, 1998) is another standard choice.

Definition 5.1 — Generalised inverse For a distribution function F on \mathbb{R}, the generalised inverse is F^{-}(u) = \inf\{x \in \mathbb{R} : F(x) \ge u\}, \qquad u \in (0, 1). It coincides with F^{-1} when F is continuous and strictly increasing.

Proposition 5.2 — Inversion If U is uniform on (0, 1), then F^{-}(U) has distribution function F.

Proof. Because F is non-decreasing and right-continuous, F^{-}(u) \le x if and only if u \le F(x). Hence P(F^{-}(U) \le x) = P(U \le F(x)) = F(x). ∎

Examples follow directly.

Inversion needs F^{-} in closed form or a cheap numerical inverse. The Gaussian distribution function has neither, which motivates the next section.

5.2 Transformations

Proposition 5.3 — Box–Muller transform If U_1 and U_2 are independent and uniform on (0,1), set R = \sqrt{-2\log U_1} and \Phi = 2\pi U_2. Then (R\cos\Phi,\ R\sin\Phi) \text{ is a pair of independent } \mathcal N(0, 1) \text{ variables.} Sketch. In polar coordinates, a standard Gaussian vector of \mathbb{R}^2 has an angle uniform on [0, 2\pi), independent of its squared radius. The squared radius follows \mathrm{Exp}(1/2), which inversion generates as -2\log U_1.

Two further transformations are used constantly.

5.3 Rejection sampling

Algorithm 5.4 — Rejection sampling Let f be a target density known through \tilde f = Z f, with Z > 0 possibly unknown. Let g be a proposal density that can be sampled, with \tilde f \le M g everywhere. Repeat:

  1. draw X \sim g and U \sim \mathcal U(0, 1) independently;
  2. if U \le \tilde f(X) / (M g(X)), return X; otherwise start again.

Theorem 5.5 — Correctness and cost of rejection The returned variable has density f. The number of proposals N is geometric with success probability p = Z/M, so that \mathbb{E}[N] = \frac{M}{Z} . When \tilde f = f is normalised, the acceptance rate is 1/M.

Proof. For a measurable set A, one round accepts a point of A with probability P(X \in A,\ \text{accept}) = \int_A g(x)\, \frac{\tilde f(x)}{M g(x)}\, dx = \frac{Z}{M} \int_A f(x)\, dx . With A = \mathbb{R}^d, a round succeeds with probability Z/M. Dividing, P(X \in A \mid \text{accept}) = \int_A f. The rounds are independent, so N is geometric. ∎

Example 5.6 — A Gaussian from exponentials The half-normal target f(x) = \sqrt{2/\pi}\, e^{-x^2/2} on x \ge 0 can be dominated by the proposal g(x) = e^{-x}.

  • The ratio f/g = \sqrt{2/\pi}\, e^{x - x^2/2} is maximal at x = 1, so the best constant is M = \sqrt{2e/\pi} \approx 1.3155.
  • The acceptance probability is 1/M \approx 0.760, and the test U \le f(X)/(Mg(X)) simplifies to U \le e^{-(X-1)^2/2}.
  • Attaching an independent random sign gives a standard Gaussian variable.
import numpy as np

rng = np.random.default_rng(5)
M = np.sqrt(2 * np.e / np.pi)                      # sup f/g, attained at x = 1

def half_normal(size):
    out, tried = [], 0
    while sum(len(o) for o in out) < size:
        x = rng.exponential(size=size)             # proposals from g = Exp(1)
        u = rng.random(size)
        out.append(x[u <= np.exp(-0.5 * (x - 1.0) ** 2)])   # accept if U <= f / (M g)
        tried += size
    return np.concatenate(out)[:size], sum(len(o) for o in out) / tried

x, acc = half_normal(200_000)
z = x * rng.choice([-1.0, 1.0], size=x.size)       # random sign -> N(0, 1)
print(f"acceptance {acc:.4f} (1/M = {1 / M:.4f})")
print(f"mean of |Z| {x.mean():.4f} (sqrt(2/pi) = {np.sqrt(2 / np.pi):.4f}),  var of Z {z.var():.4f}")

The run prints an acceptance rate of 0.760, a mean of |Z| equal to 0.799 (exact value \sqrt{2/\pi} = 0.798) and a variance of Z equal to 1.004.

Proposition 5.7 — Rejection degrades exponentially with the dimension For the target \mathcal N(0, I_d) and the proposal \mathcal N(0, \sigma^2 I_d) with \sigma > 1, the best constant is M = \sigma^d. The acceptance rate is therefore \sigma^{-d}.

Proof. The ratio of densities is \sigma^d \exp\Big(-\frac{\|x\|^2}{2}\,(1 - \sigma^{-2})\Big), which is maximal at x = 0. ∎

With a proposal only 10 % wider than the target, in dimension 100, the acceptance rate is 1.1^{-100} \approx 7.3 \times 10^{-5} .

Rejection is therefore a tool for low dimension. In this course it samples full conditionals inside Gibbs samplers (ch. 6), and it is the ancestor of ABC (ch. 9). For log-concave densities in dimension one, adaptive rejection sampling (Gilks and Wild, 1992) builds the envelope automatically from tangents.

5.4 Importance sampling

Definition 5.8 — Importance sampling Let g be a proposal density that is positive wherever hf is nonzero, and let w = f/g be the importance weight. Then \mathbb{E}_f[h(X)] = \mathbb{E}_g[h(X) w(X)], and with X_1, \dots, X_n independent with density g, \hat I_n^{\mathrm{IS}} = \frac1n \sum_{i=1}^n h(X_i)\, w(X_i) is unbiased, with variance \mathrm{Var}\big(\hat I_n^{\mathrm{IS}}\big) = \frac1n\Big(\mathbb{E}_g[h^2 w^2] - (\mathbb{E}_f h)^2\Big) .

Proposition 5.9 — The optimal proposal Among all proposals, the variance of \hat I_n^{\mathrm{IS}} is minimal for g^* = \frac{|h|\, f}{\mathbb{E}_f |h|} . If h \ge 0, this proposal gives an estimator with zero variance.

Proof. By the Cauchy–Schwarz inequality, \mathbb{E}_g[h^2 w^2] \ge (\mathbb{E}_g |h| w)^2 = (\mathbb{E}_f |h|)^2 . Equality holds when |h| w is constant, which is the case for g = g^*. When h \ge 0 the lower bound equals (\mathbb{E}_f h)^2 and the variance vanishes. ∎

The optimal proposal involves the unknown integral, so it is never used as such. Its lesson is to put the samples where |h| f is large, not where f is large.

When f is known only up to a constant, the self-normalised estimator \hat I_n^{\mathrm{SN}} = \frac{\sum_i w(X_i)\, h(X_i)}{\sum_i w(X_i)} needs only the unnormalised weights. It is consistent, as a ratio of two convergent averages, with a bias of order 1/n.

The effective sample size (\sum_i w_i)^2 / \sum_i w_i^2, between 1 and n, is the standard diagnostic of weight degeneracy. ABC-SMC (ch. 9.3) relies on it.

Example 5.10 — A rare event The tail probability p = P(Z > 4) of a standard Gaussian variable equals 3.167 \times 10^{-5}.

  • Crude Monte Carlo with n = 10^5 samples expects 3.2 hits, so its relative standard error is about 1/\sqrt{np} \approx 0.56.
  • Importance sampling from \mathcal N(4, 1), a proposal centred on the event, has weight w(y) = \frac{\varphi(y)}{\varphi(y - 4)} = e^{-4y + 8} .
import numpy as np
from scipy.stats import norm

rng = np.random.default_rng(5)
n, p = 100_000, norm.sf(4.0)
naive = rng.standard_normal(n) > 4.0
y = rng.normal(4.0, 1.0, n)                        # proposal N(4, 1)
terms = (y > 4.0) * np.exp(-4.0 * y + 8.0)         # h(y) w(y)
print(f"exact {p:.4e} | naive {naive.mean():.4e} ({naive.sum()} hits) | "
      f"IS {terms.mean():.4e} +/- {1.96 * terms.std() / np.sqrt(n):.1e}")

The crude estimate rests on a handful of hits. The importance-sampling estimate has a 95 % half-width close to 4 \times 10^{-7}, about 1.3 % of p, with the same number of samples.

Key takeaways — chapter 5

  • Inversion: F^{-}(U) \sim F; transformations give Gaussians (Box–Muller, Cholesky) and mixtures (composition).
  • Rejection with \tilde f \le Mg is exact and needs on average M/Z proposals per accepted point.
  • Rejection degrades exponentially with the dimension, so it is a low-dimensional tool.
  • Importance sampling reweights samples from g; the variance is small when g follows |h| f, and the self-normalised version works with unnormalised targets.
  • The effective sample size of the weights detects degeneracy.

6. Markov chain Monte Carlo: Metropolis–Hastings and Gibbs

Rejection and importance sampling fail in high dimension because they draw independent points from a fixed proposal, which ignores where the target mass lies. Markov chain Monte Carlo draws dependent points instead. Each point is a local modification of the previous one, accepted or rejected so that the target distribution stays invariant.

This chapter builds the two classical samplers of the syllabus, Metropolis–Hastings and Gibbs, and the theory that justifies their averages.

6.1 Markov kernels, invariance and ergodicity

Definition 6.1 — Kernel, invariance, reversibility A Markov kernel P(x, A) gives, for each state x, a probability distribution of the next state. A chain (X_n) with kernel P satisfies P(X_n \in A \mid \mathcal F_{n-1}) = P(X_{n-1}, A).

A distribution \pi is invariant if \int \pi(dx) P(x, A) = \pi(A) for every set A. The kernel is reversible with respect to \pi, or satisfies detailed balance, if \pi(dx)\, P(x, dy) = \pi(dy)\, P(y, dx) .

Proposition 6.2 — Detailed balance implies invariance A kernel that is reversible with respect to \pi leaves \pi invariant.

Proof. Integrate detailed balance over x in the whole space and y \in A. The left side gives \int \pi(dx) P(x, A); the right side gives \int_A \pi(dy) P(y, \mathcal X) = \pi(A). ∎

Definition 6.3 — Irreducibility and aperiodicity A \pi-invariant kernel is \pi-irreducible if, from every starting point x, every set A with \pi(A) > 0 is reached with positive probability after some number of steps. It is aperiodic if the state space cannot be split into k \ge 2 sets visited cyclically.

Theorem 6.4 — Ergodic theorem for MCMC (statement) Let P be \pi-invariant, \pi-irreducible and aperiodic. Then, for \pi-almost every starting point x, \big\| P^n(x, \cdot) - \pi \big\|_{\mathrm{TV}} \longrightarrow 0 . If the chain is moreover Harris recurrent, then for every starting point and every h integrable under \pi, the average \frac1n \sum_{k \le n} h(X_k) converges almost surely to \pi(h).

See Tierney (1994), Meyn and Tweedie (2009), and Douc, Moulines, Priouret and Soulier (2018).

Theorem 6.5 — Central limit theorem for MCMC (statement) If the chain is geometrically ergodic and \pi(|h|^{2+\delta}) < \infty for some \delta > 0, then \sqrt n\,(\hat I_n - \pi(h)) converges in law to \mathcal N(0, \sigma_h^2), where \sigma_h^2 = \mathrm{Var}_\pi(h) \Big(1 + 2 \sum_{k \ge 1} \rho_k\Big) = \mathrm{Var}_\pi(h)\, \tau_h , \rho_k is the lag-k autocorrelation of h(X_n) at stationarity, and \tau_h is the integrated autocorrelation time.

A chain of length n is worth n/\tau_h independent samples: this is its effective sample size (ESS). Positive autocorrelations make \tau_h > 1, and every sampler below is judged by this number.

6.2 The Metropolis–Hastings algorithm

Algorithm 6.6 — Metropolis–Hastings (Metropolis et al., 1953; Hastings, 1970) The target \pi is known through an unnormalised density \tilde\pi. A proposal kernel has density q(x, y). From X_{n-1} = x:

  1. draw a candidate Y \sim q(x, \cdot);
  2. accept it with probability \alpha(x, y) = \min\Big(1,\ \frac{\tilde\pi(y)\, q(y, x)}{\tilde\pi(x)\, q(x, y)}\Big) ;
  3. set X_n = Y if it is accepted, and X_n = x otherwise.

Theorem 6.7 — Metropolis–Hastings is reversible The kernel of Algorithm 6.6 satisfies detailed balance with respect to \pi, hence leaves \pi invariant. The normalising constant of \pi is never needed.

Proof. The kernel is P(x, dy) = q(x, y)\alpha(x, y)\, dy + r(x)\, \delta_x(dy), where r(x) is the probability of rejection.

  1. For x \ne y, the flow from x to y is \pi(x)\, q(x, y)\, \alpha(x, y) = \min\big(\pi(x) q(x, y),\ \pi(y) q(y, x)\big), which is symmetric in (x, y).
  2. The rejection part puts mass only on the diagonal y = x, where detailed balance is trivial.
  3. Proposition 6.2 gives invariance. In the ratio defining \alpha, the unknown constant of \tilde\pi cancels. ∎

Irreducibility holds, for instance, when q(x, y) > 0 for all x and y in the support of \pi, and aperiodicity holds as soon as rejections have positive probability (Tierney, 1994). Two choices of proposal dominate practice.

Always compute \log \alpha rather than \alpha: densities in high dimension underflow.

Theorem 6.8 — Optimal scaling of random-walk Metropolis (Roberts, Gelman and Gilks, 1997; statement) Let the target be a product \pi(x) = \prod_{i=1}^d f(x_i) of a smooth density f, and let the proposal be \mathcal N(x, \frac{\ell^2}{d} I_d).

As d \to \infty, the first coordinate, accelerated by a factor d, converges to a Langevin diffusion with speed 2\ell^2\, \Phi(-\ell\sqrt{I}/2), where I = \mathbb{E}_f[((\log f)')^2]. The speed is maximal for \ell \approx 2.38/\sqrt{I}, where the acceptance rate equals 0.234 .

The practical rule is to tune the proposal scale to an acceptance rate of about 0.23 in high dimension, and about 0.44 in dimension one. The proposal covariance should be proportional to the target covariance, with factor 2.38^2/d (Gelman, Roberts and Gilks, 1996). Adaptive MCMC (ch. 8) automates both rules.

Example 6.9 — Proposal scale and efficiency Random-walk Metropolis on \mathcal N(0, I_{10}), with three proposal scales: too small, the optimal 2.38/\sqrt{10} = 0.753, and too large.

import numpy as np

rng = np.random.default_rng(6)

def ess(x):
    """Effective sample size: n / (1 + 2 sum of autocorrelations up to the first negative one)."""
    x = x - x.mean()
    n = x.size
    f = np.fft.rfft(x, 2 * n)
    acf = np.fft.irfft(f * np.conj(f))[:n] / (x.var() * n)
    neg = np.argmax(acf[1:] < 0) + 1
    return n / (1 + 2 * acf[1:neg].sum())

d, n = 10, 50_000
log_pi = lambda x: -0.5 * x @ x
for scale in [0.1, 2.38 / np.sqrt(d), 3.0]:
    x, lp, acc, chain = np.zeros(d), 0.0, 0, np.empty(n)
    for t in range(n):
        y = x + scale * rng.standard_normal(d)
        lpy = log_pi(y)
        if np.log(rng.random()) < lpy - lp:        # MH acceptance for a symmetric proposal
            x, lp, acc = y, lpy, acc + 1
        chain[t] = x[0]
    print(f"RWM scale {scale:.3f}: acceptance {acc / n:.3f}, ESS of x_1 = {ess(chain):7.0f} / {n}")

The small scale accepts almost everything but moves very little. The large scale proposes bold moves that are almost always rejected. The optimal scale accepts about a quarter of the proposals and gives an effective sample size more than ten times larger than either extreme.

6.3 The Gibbs sampler

Algorithm 6.10 — Gibbs sampler (Geman and Geman, 1984; Gelfand and Smith, 1990) Split the state into blocks, x = (x_1, \dots, x_p), and assume that every full conditional \pi(x_j \mid x_{-j}) can be sampled. A systematic-scan sweep updates, for j = 1, \dots, p, x_j \sim \pi(x_j \mid x_1, \dots, x_{j-1}, x_{j+1}, \dots, x_p) . A random-scan sampler updates one block chosen at random at each step.

Proposition 6.11 — Gibbs updates are Metropolis–Hastings moves that are always accepted Each update of block j leaves \pi invariant. The systematic sweep, a composition of such updates, is \pi-invariant; the random-scan sampler is moreover reversible.

Proof. The update of block j is an MH move with proposal q(x, y) = \pi(y_j \mid x_{-j}) for y_{-j} = x_{-j}. Since \pi(x) = \pi(x_j \mid x_{-j})\, \pi(x_{-j}) and y_{-j} = x_{-j}, \frac{\pi(y)\, q(y, x)}{\pi(x)\, q(x, y)} = \frac{\pi(y_j \mid x_{-j})\, \pi(x_{-j})\, \pi(x_j \mid x_{-j})}{\pi(x_j \mid x_{-j})\, \pi(x_{-j})\, \pi(y_j \mid x_{-j})} = 1 . The acceptance probability is 1, and Theorem 6.7 applies. A composition of invariant kernels is invariant; a mixture of reversible kernels is reversible. ∎

Example 6.12 — Gibbs is slow on correlated targets Take a bivariate Gaussian target with unit variances and correlation \rho. The full conditionals are X \mid Y = y \sim \mathcal N(\rho y,\ 1 - \rho^2), \qquad Y \mid X = x \sim \mathcal N(\rho x,\ 1 - \rho^2) .

  • Substituting one update into the other, the X-sequence is an autoregression X_n = \rho^2 X_{n-1} + \text{noise}.
  • Its autocorrelations are \rho_k = \rho^{2k}, so the integrated autocorrelation time is \tau = 1 + 2\sum_{k \ge 1} \rho^{2k} = \frac{1 + \rho^2}{1 - \rho^2} .
  • For \rho = 0.99, \tau \approx 99.5: a hundred Gibbs sweeps are worth one independent draw.
import numpy as np

rng = np.random.default_rng(6)

def ess(x):
    x = x - x.mean()
    n = x.size
    f = np.fft.rfft(x, 2 * n)
    acf = np.fft.irfft(f * np.conj(f))[:n] / (x.var() * n)
    neg = np.argmax(acf[1:] < 0) + 1
    return n / (1 + 2 * acf[1:neg].sum())

rho, n = 0.99, 50_000
xs, x, y = np.empty(n), 0.0, 0.0
for t in range(n):
    x = rho * y + np.sqrt(1 - rho ** 2) * rng.standard_normal()   # X | Y = y
    y = rho * x + np.sqrt(1 - rho ** 2) * rng.standard_normal()   # Y | X = x
    xs[t] = x
lag1 = np.corrcoef(xs[:-1], xs[1:])[0, 1]
print(f"lag-1 autocorrelation {lag1:.4f} (theory rho^2 = {rho ** 2:.4f})")
print(f"n / ESS = {n / ess(xs):.0f} (theory (1 + rho^2) / (1 - rho^2) = {(1 + rho ** 2) / (1 - rho ** 2):.1f})")

The empirical lag-1 autocorrelation matches \rho^2 = 0.9801, and n/\mathrm{ESS} is close to 100. Rotating the coordinates to (X + Y, X - Y)/\sqrt 2 makes the two blocks independent, and \tau drops to 1: reparametrisation and blocking are the standard cures.

Example 6.13 — Gibbs sampling for a Bayesian mixture by data augmentation For the Gaussian mixture of Example 3.8 with conjugate priors (Dirichlet on the weights, Gaussian on the means, inverse-gamma on the variances), Diebolt and Robert (1994) alternate two blocks:

  • the labels z_i, drawn independently with the responsibilities of the E-step as probabilities;
  • the parameters, drawn from their conjugate posteriors given the labels, with the counts n_k and the within-component sums as statistics.

EM averages over the labels; Gibbs draws them. This difference is the starting point of the stochastic versions of EM (ch. 7). The posterior is invariant under permutations of the labels, so a well-mixing sampler switches labels, and summaries must be computed after relabelling.

6.4 Practical diagnostics

The ergodic theorem says nothing about how long to wait. Practice relies on the following diagnostics, which can reveal a failure but never prove convergence.

Key takeaways — chapter 6

  • Detailed balance implies invariance; irreducibility and aperiodicity then give convergence in total variation and a law of large numbers.
  • The asymptotic variance of an MCMC average is \mathrm{Var}_\pi(h)\,\tau_h; the effective sample size is n/\tau_h.
  • Metropolis–Hastings accepts with probability \min(1, \tilde\pi(y)q(y,x) / (\tilde\pi(x)q(x,y))) and never needs the normalising constant.
  • Random-walk proposals should be tuned to an acceptance rate near 0.234 in high dimension.
  • Gibbs updates are MH moves with acceptance 1; strong correlations between blocks make Gibbs slow.

7. Stochastic versions of EM

The E-step of EM needs the conditional expectation \bar s(\theta) of the complete-data sufficient statistics (Algorithm 3.7). In a mixture it is a finite sum. In a nonlinear mixed-effects model, a deformable template model or a random-effects logistic regression it is an intractable integral.

The stochastic versions of EM replace this expectation by simulation: exact simulation when possible (ch. 5), MCMC otherwise (ch. 6). Stochastic approximation (ch. 4) then controls the resulting noise. Throughout, the complete data form the exponential family of ch. 3.3, with M-step map \bar\theta.

7.1 Monte Carlo EM

Algorithm 7.1 — Monte Carlo EM (Wei and Tanner, 1990) At iteration k, draw m_k independent samples z^{(1)}, \dots, z^{(m_k)} from p(z \mid y; \theta_{k-1}), then set s_k = \frac{1}{m_k} \sum_{j=1}^{m_k} S(y, z^{(j)}), \qquad \theta_k = \bar\theta(s_k) .

The Monte Carlo error of s_k is of order m_k^{-1/2} at every iteration and does not vanish unless m_k \to \infty. Monotonicity of the likelihood is lost, and the total cost \sum_k m_k is high. Booth and Hobert (1999) increase m_k automatically once the change in \theta falls below the Monte Carlo error.

7.2 Stochastic EM

Algorithm 7.2 — SEM (Celeux and Diebolt, 1985) At iteration k, draw a single z_k \sim p(z \mid y; \theta_{k-1}) and set \theta_k = \bar\theta(S(y, z_k)): the M-step is applied to the simulated complete data.

The sequence (\theta_k) is a Markov chain that never settles at a point: at every iteration, a new draw of the hidden variables moves it. Under conditions it is ergodic, with a stationary distribution concentrated near a maximum of the likelihood, and one estimates \theta by averaging the iterates after a burn-in.

The random perturbations help SEM escape saddle points and poor local maxima, which is why it is used to initialise EM. Exercise 14 shows why it cannot converge pointwise.

7.3 Stochastic approximation EM

Algorithm 7.3 — SAEM (Delyon, Lavielle and Moulines, 1999) Choose steps \gamma_k \in [0, 1] and an initial statistic s_0. At iteration k:

  1. Simulation: draw z_k \sim p(z \mid y; \theta_{k-1});
  2. Stochastic approximation: s_k = s_{k-1} + \gamma_k \big(S(y, z_k) - s_{k-1}\big) ;
  3. Maximisation: set \theta_k = \bar\theta(s_k).

With \gamma_k = 1 SAEM is SEM. With decreasing steps it averages the simulations over the iterations, so a single simulation per iteration is enough: the average does the work that the large m_k of MCEM did.

The recursion is a Robbins–Monro algorithm (Definition 4.1) on the statistic s, with mean field h(s) = \bar s\big(\bar\theta(s)\big) - s and martingale increments \xi_k = S(y, z_k) - \bar s(\bar\theta(s_{k-1})). The roots of h are the fixed points of EM written in statistics, s^* = \bar s(\bar\theta(s^*)).

Proposition 7.4 — The likelihood is a Lyapunov function for SAEM (Delyon, Lavielle and Moulines, 1999) Assume that \varphi, \psi and \bar\theta are continuously differentiable. Write J_\varphi for the Jacobian of \varphi at \bar\theta(s).

Write also H(s) for the Hessian in \theta of the M-step objective \langle \varphi(\theta), s\rangle - \psi(\theta) at \bar\theta(s), assumed negative definite.

Then W(s) = \ell(\bar\theta(s)) satisfies \langle \nabla W(s), h(s) \rangle = \big(J_\varphi^\top h(s)\big)^\top \big(-H(s)\big)^{-1} \big(J_\varphi^\top h(s)\big) \ \ge\ 0, with equality if and only if \bar\theta(s) is a stationary point of \ell.

Proof.

  1. Fisher’s identity. Differentiating \ell(\theta) = \log \int p(y, z; \theta)\, dz under the integral gives the conditional expectation of the complete score: \nabla \ell(\theta) = J_\varphi(\theta)^\top \bar s(\theta) - \nabla\psi(\theta) .
  2. M-step. The maximiser \bar\theta(s) satisfies the first-order condition J_\varphi^\top s - \nabla\psi = 0 at \bar\theta(s). Subtracting it from step 1 at \theta = \bar\theta(s): \nabla \ell(\bar\theta(s)) = J_\varphi^\top\, h(s) .
  3. Implicit differentiation. Differentiating the first-order condition in s gives J_\varphi^\top + H(s)\, J_{\bar\theta}(s) = 0, so the Jacobian of the M-step map is J_{\bar\theta}(s) = -H(s)^{-1} J_\varphi^\top.
  4. Chain rule. Steps 2 and 3 give \nabla W(s) = J_{\bar\theta}(s)^\top \nabla\ell(\bar\theta(s)) = -J_\varphi\, H(s)^{-1} J_\varphi^\top h(s) . Taking the inner product with h(s) gives the formula, which is nonnegative because -H(s) is positive definite.
  5. Equality case. The quadratic form vanishes if and only if J_\varphi^\top h(s) = 0, that is, by step 2, if and only if \nabla\ell(\bar\theta(s)) = 0. ∎

Along the mean ODE \dot s = h(s), the likelihood increases, exactly as along EM iterations. The ODE method (Theorem 4.7) with V = -W then gives the convergence of SAEM.

Theorem 7.5 — Convergence of SAEM (Delyon, Lavielle and Moulines, 1999; statement) Assume the exponential-family structure and the smoothness of Proposition 7.4. Assume also that the set of values of \ell at its stationary points has empty interior, and that the step sizes satisfy the Robbins–Monro conditions.

If the sequence (s_k) stays almost surely in a compact set, then the distance from \theta_k to the set of stationary points of \ell tends to 0 almost surely. Under additional conditions, the limits are local maxima: the simulation noise pushes the iterates away from unstable stationary points.

In practice, one takes \gamma_k = 1 during a first phase of K_1 iterations, which explores like SEM. Then \gamma_k = (k - K_1)^{-a} with 1/2 < a \le 1 makes the iterates settle. Stability is enforced by truncation on random bounds (ch. 4.5) when needed.

7.4 MCMC-SAEM

When p(z \mid y; \theta) cannot be sampled exactly, the simulation step becomes a few steps of an MCMC kernel \Pi_\theta whose invariant distribution is p(\cdot \mid y; \theta): z_k \sim \Pi_{\theta_{k-1}}(z_{k-1}, \cdot) . The chain of hidden variables continues from one iteration to the next, while its target moves slowly with \theta_k.

Theorem 7.6 — Convergence of MCMC-SAEM (Kuhn and Lavielle, 2004; statement) Assume the conditions of Theorem 7.5. Assume also that the kernels \Pi_\theta are uniformly ergodic, uniformly for \theta in compact sets, and depend smoothly on \theta. Then the conclusion of Theorem 7.5 holds for MCMC-SAEM.

The noise is now Markovian rather than a martingale increment. The proof decomposes it, through the solution of a Poisson equation, into a martingale increment plus a remainder that vanishes thanks to the slow variation of \theta_k (Benveniste, Métivier and Priouret, 1990).

Example 7.7 — A random-effects logistic model Subject i = 1, \dots, N has a hidden ability \varphi_i \sim \mathcal N(\mu, \omega^2) and answers m questions, each correctly with probability \mathrm{logit}^{-1}(\varphi_i).

  • Data. N = 200 subjects, m = 10 questions, true values \mu = -0.5 and \omega = 1.
  • Statistics. The complete data are Gaussian in \varphi, so S = (\sum_i \varphi_i, \sum_i \varphi_i^2), and the M-step is \mu = S_1/N, \omega^2 = S_2/N - \mu^2.
  • Simulation. Five random-walk Metropolis steps per subject, all subjects in parallel. The target is the conditional law of \varphi_i given y_i, proportional to the likelihood p(y_i \mid \varphi_i) times the Gaussian density of \varphi_i.
  • Reference. Each \varphi_i is one-dimensional, so the exact maximum-likelihood estimate can be computed by Gauss–Hermite quadrature, for comparison.
import numpy as np
from scipy.optimize import minimize
from scipy.special import expit, logsumexp

rng = np.random.default_rng(7)
N, m, mu_true, om_true = 200, 10, -0.5, 1.0
phi_true = rng.normal(mu_true, om_true, N)                 # random effects (never observed)
k = (rng.random((N, m)) < expit(phi_true)[:, None]).sum(1)  # successes per subject

def loglik_y(phi, kk):          # log p(y_i | phi_i) up to a constant
    return kk * phi - m * np.logaddexp(0.0, phi)

# MCMC-SAEM: S(z) = (sum phi_i, sum phi_i^2), M-step mu = S1/N, omega^2 = S2/N - mu^2
K_burn, K = 200, 1000
mu, om2, s1, s2 = 0.0, 4.0, 0.0, 0.0
phi = np.zeros(N)
for it in range(1, K + 1):
    for _ in range(5):                                      # simulation: 5 RWM steps per subject
        prop = phi + 0.8 * rng.standard_normal(N)
        log_r = (loglik_y(prop, k) - loglik_y(phi, k)
                 - ((prop - mu) ** 2 - (phi - mu) ** 2) / (2 * om2))
        phi = np.where(np.log(rng.random(N)) < log_r, prop, phi)
    gamma = 1.0 if it <= K_burn else 1.0 / (it - K_burn)   # stochastic approximation step
    s1 += gamma * (phi.sum() - s1)
    s2 += gamma * ((phi ** 2).sum() - s2)
    mu, om2 = s1 / N, s2 / N - (s1 / N) ** 2               # maximisation
print(f"MCMC-SAEM          : mu = {mu:+.3f}, omega = {np.sqrt(om2):.3f}")

# Reference: exact maximum likelihood, integral over phi_i by Gauss-Hermite quadrature
nodes, weights = np.polynomial.hermite_e.hermegauss(60)   # weight exp(-x^2 / 2)
def neg_loglik(p):
    ph = p[0] + np.exp(p[1]) * nodes                        # change of variables phi = mu + omega x
    terms = loglik_y(ph[None, :], k[:, None]) + np.log(weights)[None, :]
    return -(logsumexp(terms, axis=1) - 0.5 * np.log(2 * np.pi)).sum()
res = minimize(neg_loglik, x0=[0.0, 0.0], method="Nelder-Mead", options={"xatol": 1e-6, "fatol": 1e-8})
print(f"Gauss-Hermite MLE  : mu = {res.x[0]:+.3f}, omega = {np.exp(res.x[1]):.3f}")

MCMC-SAEM returns (\hat\mu, \hat\omega) = (-0.659, 0.973), and the exact maximum-likelihood estimate is (-0.659, 0.970).

Both differ from the true values (-0.5, 1) by the statistical error of 200 subjects, not by an algorithmic error. With K_1 = 100 and K = 600 instead, \hat\omega = 0.938: the averaging phase must be long enough for the slowly mixing hidden variables.

Where SAEM is used SAEM is the standard estimation algorithm for nonlinear mixed-effects models in pharmacometrics, see Biostatistics. In computational anatomy, Allassonnière, Kuhn and Trouvé (2010) estimate Bayesian deformable templates of images with MCMC-SAEM and prove its convergence; ch. 10.7 returns to this line of work. Online EM (Cappé and Moulines, 2009) applies the same stochastic approximation of \bar s to data streams.

Key takeaways — chapter 7

  • MCEM averages many simulations per iteration; SEM uses one and never converges pointwise; SAEM uses one and averages across iterations.
  • SAEM is a Robbins–Monro algorithm on the sufficient statistics, with mean field h(s) = \bar s(\bar\theta(s)) - s whose roots are the fixed points of EM.
  • The log-likelihood read through the M-step, \ell(\bar\theta(s)), increases along the mean field: SAEM converges to stationary points of \ell.
  • MCMC-SAEM replaces exact simulation by a few steps of an MCMC kernel targeting p(z \mid y; \theta).
  • Practice: a first phase with \gamma_k = 1, then decreasing steps, and a long enough averaging phase.

8. Adaptive MCMC and parallel tempering

The efficiency of Metropolis–Hastings depends on its proposal. Example 6.9 lost a factor of more than ten with a badly scaled random walk, and Example 8.8 below shows a sampler that never leaves the mode it starts in.

Adaptive MCMC learns the proposal from the chain’s own history. Parallel tempering crosses energy barriers through a ladder of flattened targets. Both are recent advances named in the syllabus, and both rely on stochastic approximation (ch. 4).

8.1 Adaptive Metropolis

Theorem 6.8 and its extensions recommend a Gaussian random-walk proposal with covariance \frac{2.38^2}{d}\Sigma_\pi, where \Sigma_\pi is the covariance of the target. The covariance \Sigma_\pi is unknown, but the chain itself produces samples from which it can be estimated.

Algorithm 8.1 — Adaptive Metropolis (Haario, Saksman and Tamminen, 2001) Run random-walk Metropolis with a Gaussian proposal centred at X_n, with covariance s_d(\Sigma_n + \varepsilon I_d), where s_d = 2.38^2/d and \varepsilon > 0 is small. After each step, update the running mean and covariance: m_{n+1} = m_n + \gamma_{n+1}(X_{n+1} - m_n), \qquad \Sigma_{n+1} = \Sigma_n + \gamma_{n+1}\big[(X_{n+1} - m_n)(X_{n+1} - m_n)^\top - \Sigma_n\big] .

With \gamma_n = 1/(n+1), (m_n, \Sigma_n) is essentially the empirical mean and covariance of the past states. This is a Robbins–Monro recursion whose mean field vanishes at the mean and covariance of \pi. The term \varepsilon I_d keeps the proposal non-degenerate.

A second, widespread adaptation tunes the global scale \sigma towards a target acceptance rate \alpha^* = 0.234 (Andrieu and Thoms, 2008; Roberts and Rosenthal, 2009): \log\sigma_{n+1} = \log\sigma_n + \gamma_{n+1}\big(\alpha(X_n, Y_{n+1}) - \alpha^*\big) . It is a Robbins–Monro algorithm for the root of \sigma \mapsto \bar\alpha(\sigma) - \alpha^*, where \bar\alpha is the mean acceptance rate.

Example 8.2 — Learning an anisotropic Gaussian The target is a Gaussian in dimension 8, with standard deviations spread from 0.1 to 10 along randomly rotated axes. The fixed proposal \frac{2.38^2}{d} I_d is compared with Algorithm 8.1, on the second half of chains of length 30 000.

import numpy as np

rng = np.random.default_rng(8)

def ess(x):
    x = x - x.mean(); n = x.size
    f = np.fft.rfft(x, 2 * n)
    acf = np.fft.irfft(f * np.conj(f))[:n] / (x.var() * n)
    neg = np.argmax(acf[1:] < 0) + 1
    return n / (1 + 2 * acf[1:neg].sum())

# Target N(0, Sigma) in d = 8 with standard deviations from 0.1 to 10, random rotation
d, n = 8, 30_000
Q, _ = np.linalg.qr(rng.standard_normal((d, d)))
Sigma = Q @ np.diag(np.logspace(-1, 1, d) ** 2) @ Q.T
P = np.linalg.inv(Sigma)
log_pi = lambda x: -0.5 * x @ P @ x
sd = 2.38 ** 2 / d

def metropolis(adaptive):
    x, lp = np.zeros(d), 0.0
    mean, cov = np.zeros(d), np.eye(d)
    chain, acc = np.empty((n, d)), 0
    for t in range(1, n + 1):
        C = sd * (cov + 1e-6 * np.eye(d)) if adaptive else sd * np.eye(d)
        y = x + np.linalg.cholesky(C) @ rng.standard_normal(d)
        lpy = log_pi(y)
        if np.log(rng.random()) < lpy - lp:
            x, lp, acc = y, lpy, acc + 1
        chain[t - 1] = x
        if adaptive:                               # Robbins-Monro updates, step 1/(t+1)
            g = 1.0 / (t + 1)
            diff = x - mean
            mean = mean + g * diff
            cov = cov + g * (np.outer(diff, diff) - cov)
    second = chain[n // 2:]
    u = np.linalg.eigh(Sigma)[1][:, -1]           # direction of largest variance
    return acc / n, ess(second @ u)

for name, ad in [("RWM, proposal (2.38^2/d) I", False), ("Adaptive Metropolis", True)]:
    a, e = metropolis(ad)
    print(f"{name:28s} acceptance {a:.3f}  ESS along the widest axis {e:6.0f} / {n // 2}")

The isotropic proposal is too wide for the narrow directions: it accepts 2 % of its moves and gives an effective sample size of 6 along the widest axis. Adaptive Metropolis accepts 29 % and reaches an ESS of about 560 on the same budget.

8.2 When adaptation is safe

Each kernel used by an adaptive chain may be \pi-invariant while the adaptive chain is not, because the choice of kernel depends on the past.

Example 8.3 — Adaptation that breaks invariance On the two states \{0, 1\}, let \pi = (1/2, 1/2) and consider two \pi-reversible kernels: P_a = \begin{pmatrix} 1 - \varepsilon & \varepsilon \\ \varepsilon & 1 - \varepsilon \end{pmatrix}, \qquad P_b = \begin{pmatrix} 1/2 & 1/2 \\ 1/2 & 1/2 \end{pmatrix} .

  • Adaptive rule: use P_a when the chain is at 0, and P_b when it is at 1.
  • The resulting chain has transition matrix with rows (1 - \varepsilon, \varepsilon) and (1/2, 1/2).
  • Its stationary distribution solves \pi'(0)\,\varepsilon = \pi'(1)/2, which gives \pi'(0) = \frac{1}{1 + 2\varepsilon} .
  • For \varepsilon = 0.01, the chain spends 98 % of its time at state 0 instead of 50 %.

Theorem 8.4 — Ergodicity of adaptive MCMC (Roberts and Rosenthal, 2007; statement) Let \{P_\gamma\} be a family of \pi-invariant kernels, and \Gamma_n the index chosen by the adaptation at time n. Assume:

  1. Diminishing adaptation: the largest total-variation distance between P_{\Gamma_{n+1}}(x, \cdot) and P_{\Gamma_n}(x, \cdot), over x, tends to 0 in probability;
  2. Containment: for every \varepsilon > 0, the number of steps that P_{\Gamma_n} needs from X_n to come within \varepsilon of \pi in total variation is bounded in probability.

Then the law of X_n converges to \pi in total variation, and a weak law of large numbers holds for bounded functions.

Adaptive Metropolis satisfies diminishing adaptation because \gamma_n \to 0: the covariance changes by O(1/n) per step. Containment holds on compact state spaces, and on unbounded spaces under tail conditions (Saksman and Vihola, 2010).

In Example 8.3 the kernel keeps switching at full amplitude, so adaptation never diminishes. A simple safe alternative is to adapt during the burn-in only, then freeze the proposal: the remaining chain is an ordinary MCMC chain.

8.3 Multimodality and tempering

Write \tilde\pi = e^{-U}, with U the energy. A random walk that must cross a barrier of height \Delta U between two modes needs a number of steps of order e^{\Delta U}.

For the mixture \frac12\mathcal N(-5, 1) + \frac12\mathcal N(5, 1), the energy at the midpoint exceeds the energy at a mode by 12.5 - \log 2 \approx 11.8. Crossings are so rare that no realistic run observes one.

Definition 8.5 — Tempered targets For an inverse temperature 0 < \beta \le 1, the tempered target is \pi_\beta \propto \tilde\pi^{\,\beta} = e^{-\beta U}. It has the same modes as \pi, but its barriers have height \beta\,\Delta U: hot chains, with small \beta, move freely between modes.

Algorithm 8.6 — Parallel tempering (Swendsen and Wang, 1986; Geyer, 1991) Choose inverse temperatures 1 = \beta_0 > \beta_1 > \dots > \beta_K. The state is (x_0, \dots, x_K), and the joint target is \Pi(x_0, \dots, x_K) \propto \prod_{k=0}^{K} \tilde\pi(x_k)^{\beta_k} . At each iteration:

  1. update every x_k with a \pi_{\beta_k}-invariant MCMC move, in parallel;
  2. choose an adjacent pair (k, k+1) and propose to exchange x_k and x_{k+1}, accepting with probability \alpha_{\mathrm{swap}} = \min\Big(1,\ \Big(\frac{\tilde\pi(x_{k+1})}{\tilde\pi(x_k)}\Big)^{\beta_k - \beta_{k+1}}\Big) .

The cold chain x_0 provides the samples from \pi.

Proposition 8.7 — Swaps preserve the joint target The swap move is a Metropolis–Hastings move for \Pi. Hence \Pi is invariant for parallel tempering, and the marginal law of x_0 under \Pi is \pi.

Proof. The proposal exchanges two coordinates. It is deterministic and equal to its own inverse, so it is symmetric and the proposal densities cancel. The ratio of joint targets is \frac{\tilde\pi(x_{k+1})^{\beta_k}\, \tilde\pi(x_k)^{\beta_{k+1}}}{\tilde\pi(x_k)^{\beta_k}\, \tilde\pi(x_{k+1})^{\beta_{k+1}}} = \Big(\frac{\tilde\pi(x_{k+1})}{\tilde\pi(x_k)}\Big)^{\beta_k - \beta_{k+1}} , so \alpha_{\mathrm{swap}} is the MH acceptance probability, and Theorem 6.7 applies. The local moves leave each factor of \Pi invariant. ∎

When a hot chain sits in a mode that the cold chain has never visited, a swap is accepted with high probability, and the cold chain jumps to that mode at once (Exercise 12).

Example 8.8 — Crossing a barrier The target is \frac12\mathcal N(-5, 1) + \frac12\mathcal N(5, 1), and every chain starts in the left mode. One random-walk chain is compared with parallel tempering at inverse temperatures (1, 0.3, 0.1, 0.03), with local proposal scales 1/\sqrt{\beta_k}.

import numpy as np

rng = np.random.default_rng(9)

def log_pi(x):          # 0.5 N(-5, 1) + 0.5 N(5, 1), up to a constant
    return np.logaddexp(-0.5 * (x + 5.0) ** 2, -0.5 * (x - 5.0) ** 2)

n = 20_000
betas = np.array([1.0, 0.3, 0.1, 0.03])        # inverse temperatures, beta_0 = 1
scales = 1.0 / np.sqrt(betas)                  # wider local moves when hotter

def run(tempering):
    K = len(betas) if tempering else 1
    x = np.full(K, -5.0)                       # every chain starts in the left mode
    cold, swaps, tries = np.empty(n), np.zeros(K - 1), np.zeros(K - 1)
    for t in range(n):
        y = x + scales[:K] * rng.standard_normal(K)          # local RWM move at each level
        acc = np.log(rng.random(K)) < betas[:K] * (log_pi(y) - log_pi(x))
        x = np.where(acc, y, x)
        if tempering:                                        # swap a random adjacent pair
            k = rng.integers(K - 1)
            log_a = (betas[k] - betas[k + 1]) * (log_pi(x[k + 1]) - log_pi(x[k]))
            tries[k] += 1
            if np.log(rng.random()) < log_a:
                x[k], x[k + 1] = x[k + 1], x[k]
                swaps[k] += 1
        cold[t] = x[0]
    return cold, swaps / np.maximum(tries, 1)

for name, tempering in [("single RWM chain", False), ("parallel tempering", True)]:
    cold, rates = run(tempering)
    print(f"{name:20s} fraction of time in the right mode {np.mean(cold > 0):.3f} (target 0.5)"
          + (f", swap rates {np.round(rates, 2)}" if tempering else ""))

The single chain spends a fraction 0.000 of its time in the right mode. The cold chain of parallel tempering spends 0.49 of its time there, close to the correct 0.5, with swap acceptance rates between 0.64 and 0.73.

The ladder is a compromise. Gaps that are too large make swaps fail; gaps that are too small require many chains. For product targets in dimension d, Atchadé, Roberts and Rosenthal (2011) show that the swap acceptance rate between neighbours should be about 0.234, and the number of levels needed grows like \sqrt d.

8.4 Adaptive parallel tempering

Choosing the ladder by hand requires knowing where the barriers are. Miasojedow, Moulines and Vihola (2013) adapt it with stochastic approximation, together with the local proposals.

Algorithm 8.9 — Adaptive parallel tempering (outline, after Miasojedow, Moulines and Vihola, 2013)

  1. Temperatures. Parametrise the gaps by real numbers \rho_k, for instance through \beta_{k+1} = \beta_k \exp(-e^{\rho_k}), which keeps the ladder decreasing.
  2. Ladder update. After each swap attempt between levels k and k+1, \rho_k \leftarrow \rho_k + \gamma_n\big(\alpha_{\mathrm{swap},k} - \alpha^*\big), \qquad \alpha^* = 0.234 . Swaps that succeed too often widen the gap; swaps that fail too often narrow it.
  3. Local proposals. At each level, adapt the random-walk covariance and scale by Algorithm 8.1 and the acceptance-rate rule of ch. 8.1.

The step sizes decrease, so the adaptation diminishes, and the authors prove the convergence of the adapted parameters and a law of large numbers for the cold chain. The result is a sampler whose only inputs are the target, the number of levels and the target acceptance rates.

Key takeaways — chapter 8

  • Adaptive Metropolis estimates the target covariance on the fly with Robbins–Monro updates and uses the 2.38^2/d rule.
  • State-dependent adaptation can destroy invariance even when every kernel is \pi-invariant (Example 8.3).
  • Diminishing adaptation plus containment guarantee ergodicity (Roberts and Rosenthal, 2007); freezing after burn-in is always safe.
  • Parallel tempering runs chains at inverse temperatures \beta_k and swaps neighbours by a Metropolis–Hastings move: the ratio \tilde\pi(x_{k+1})/\tilde\pi(x_k) raised to the power \beta_k - \beta_{k+1}.
  • Adaptive parallel tempering tunes the ladder by stochastic approximation towards a swap rate near 0.234.

9. Approximate Bayesian computation

Some models can be simulated but not evaluated. The likelihood of a genealogy in population genetics, of a stochastic epidemic, or of a distribution defined by its quantile function has no tractable expression, so Metropolis–Hastings cannot compute its acceptance ratio.

Approximate Bayesian computation (ABC) replaces the evaluation of the likelihood by simulation and comparison. It is the last of the recent advances in the syllabus, and it builds directly on rejection sampling (ch. 5.3) and MCMC (ch. 6).

9.1 Rejection ABC

Algorithm 9.1 — Rejection ABC (Tavaré et al., 1997; Pritchard et al., 1999) Choose a summary statistic s : \mathcal Y \to \mathbb{R}^q, a distance \|\cdot\| and a tolerance \varepsilon > 0. Repeat:

  1. draw \theta \sim \pi from the prior;
  2. simulate a data set y' \sim p(\cdot \mid \theta);
  3. keep \theta if \|s(y') - s(y)\| \le \varepsilon.

Proposition 9.2 — What rejection ABC samples The accepted parameters have the ABC posterior density \pi_\varepsilon(\theta \mid y) \propto \pi(\theta)\ P_\theta\big(\|s(Y') - s(y)\| \le \varepsilon\big) . If the density f_\theta of s(Y') is continuous, then \pi_\varepsilon(\cdot \mid y) converges to \pi(\cdot \mid s(y)) as \varepsilon \to 0.

If s is sufficient, the limit is the exact posterior: \pi(\cdot \mid s(y)) = \pi(\cdot \mid y) .

Proof.

  1. Algorithm 9.1 is rejection sampling (Theorem 5.5) on the pair (\theta, y'). The proposal is \pi(\theta)p(y' \mid \theta), and the target is the same density multiplied by the indicator of \|s(y') - s(y)\| \le \varepsilon, with M = 1. The \theta-marginal of the target is the claimed density.
  2. The acceptance probability equals the integral of f_\theta over the ball of radius \varepsilon around s(y). Divided by the volume of the ball, it tends to f_\theta(s(y)), and the volume cancels in the normalisation.
  3. If s is sufficient, the factorisation theorem writes p(y \mid \theta) = g(s(y), \theta)\, r(y), so both posteriors are proportional to \pi(\theta)\, g(s(y), \theta). ∎

For discrete data and \varepsilon = 0 with s the identity, the acceptance probability is exactly p(y \mid \theta) and rejection ABC is exact. For continuous data, the tolerance trades accuracy against acceptance rate.

Example 9.3 — A Gaussian mean, where the exact posterior is known Observe n = 20 values y_i \sim \mathcal N(\theta, 1) with prior \theta \sim \mathcal N(0, 3^2). The sample mean is sufficient, and the exact posterior is Gaussian, with variance (1/9 + 20)^{-1}.

import numpy as np

rng = np.random.default_rng(10)
n_obs, tau = 20, 3.0                          # y_i ~ N(theta, 1), prior theta ~ N(0, 3^2)
y_obs = rng.normal(1.5, 1.0, n_obs)
s_obs = y_obs.mean()                          # sufficient statistic
post_var = 1.0 / (1.0 / tau ** 2 + n_obs)     # exact conjugate posterior
post_mean = post_var * n_obs * s_obs
print(f"exact posterior: mean {post_mean:.3f}, sd {np.sqrt(post_var):.3f}")

n_sim = 500_000
theta = rng.normal(0.0, tau, n_sim)                                      # 1. prior draws
s_sim = (theta[:, None] + rng.standard_normal((n_sim, n_obs))).mean(1)   # 2. simulated data sets
dist = np.abs(s_sim - s_obs)
for eps in [1.0, 0.3, 0.1, 0.03]:
    keep = dist <= eps                                                   # 3. accept if close
    th = theta[keep]
    print(f"eps = {eps:4.2f}: acceptance {keep.mean():.4f}, ABC mean {th.mean():.3f}, sd {th.std():.3f}")

# Regression adjustment (Beaumont, Zhang and Balding, 2002) at the loosest tolerance
keep = dist <= 1.0
beta = np.polyfit(s_sim[keep] - s_obs, theta[keep], 1)[0]
adj = theta[keep] - beta * (s_sim[keep] - s_obs)
print(f"eps = 1.00 + regression adjustment: mean {adj.mean():.3f}, sd {adj.std():.3f}")

The exact posterior has mean 1.188 and standard deviation 0.223. The ABC standard deviation shrinks with the tolerance: 0.610, 0.281, 0.229 and 0.224 for \varepsilon = 1, 0.3, 0.1 and 0.03. Meanwhile the acceptance rate falls from 24 % to 0.7 %.

The regression adjustment of ch. 9.2 recovers mean 1.188 and standard deviation 0.223 from the loosest tolerance, at an acceptance rate of 24 %.

9.2 Tolerance, dimension and summary statistics

Proposition 9.4 — The curse of dimension of ABC (heuristic) Consider the estimation of a posterior mean from N simulations with q summary statistics, for smooth models.

  • The bias of \pi_\varepsilon is of order \varepsilon^2: with a symmetric acceptance region, the first-order term cancels.
  • The acceptance rate is of order \varepsilon^q, so the variance is of order 1/(N\varepsilon^q).
  • Balancing \varepsilon^4 against 1/(N\varepsilon^q) gives \varepsilon \propto N^{-1/(q+4)} and a mean squared error of order N^{-4/(q+4)} .

Precise statements are in Blum (2010) and in Fearnhead and Prangle (2012).

With q = 1 the mean squared error decreases like N^{-0.8}, close to the Monte Carlo rate N^{-1}. With q = 20 it decreases like N^{-1/6}. Summaries must therefore be few and informative.

9.3 ABC-MCMC and ABC-SMC

Rejection ABC proposes from the prior, which wastes simulations when the posterior is much narrower than the prior. Two remedies follow the two ideas of ch. 5–6: Markov chains, and sequential importance sampling.

Algorithm 9.5 — ABC-MCMC (Marjoram, Molitor, Plagnol and Tavaré, 2003) From the current \theta:

  1. propose \theta' \sim q(\theta, \cdot) and simulate y' \sim p(\cdot \mid \theta');
  2. if \|s(y') - s(y)\| > \varepsilon, stay at \theta;
  3. otherwise move to \theta' with probability \min\Big(1,\ \frac{\pi(\theta')\, q(\theta', \theta)}{\pi(\theta)\, q(\theta, \theta')}\Big) .

Proposition 9.6 — ABC-MCMC targets the ABC posterior The \theta-marginal of the stationary distribution of Algorithm 9.5 is \pi_\varepsilon(\theta \mid y).

Proof. Consider the chain on pairs (\theta, y'), with target proportional to \pi(\theta)\, p(y' \mid \theta) times the acceptance indicator, and proposal q(\theta, \theta')\, p(y'_{\mathrm{new}} \mid \theta').

In the Metropolis–Hastings ratio, the intractable likelihood of the new data set appears in the target and in the proposal, and cancels. So does the likelihood of the current data set. The indicator of the current state equals 1.

What remains is the ratio of step 3, multiplied by the indicator of the new state, which is step 2. Theorem 6.7 concludes. ∎

The same cancellation underlies pseudo-marginal MCMC (Andrieu and Roberts, 2009), where an unbiased estimate of the likelihood replaces the likelihood in the acceptance ratio.

In the tails of the posterior, almost every simulated data set is rejected, so an ABC-MCMC chain can stick for very long periods.

Algorithm 9.7 — ABC-SMC, or ABC population Monte Carlo (Sisson, Fan and Tanaka, 2007; Beaumont, Cornuet, Marin and Robert, 2009) Choose decreasing tolerances \varepsilon_1 > \varepsilon_2 > \dots > \varepsilon_T and a population size N.

  1. Stage 1. Run rejection ABC with \varepsilon_1 to get N particles with equal weights.
  2. Stage t. Repeat until N particles are accepted: pick a particle of stage t-1 according to its weight, perturb it with a Gaussian kernel K_t, simulate a data set, and accept if its summary lies within \varepsilon_t.
  3. Weights. Give each accepted particle \theta_t^{(i)} the importance weight w_t^{(i)} \propto \frac{\pi(\theta_t^{(i)})}{\sum_j w_{t-1}^{(j)}\, K_t\big(\theta_t^{(i)} \mid \theta_{t-1}^{(j)}\big)} .

The weights are those of importance sampling (Definition 5.8): the proposal is the mixture of kernels centred on the previous population. Beaumont and coauthors take for K_t a Gaussian with twice the weighted empirical variance of the previous population. The tolerances can be set adaptively, for instance as a quantile of the previous distances, and the effective sample size of the weights monitors degeneracy.

9.4 Caveats

Key takeaways — chapter 9

  • Rejection ABC samples \pi_\varepsilon(\theta \mid y): the prior times the probability that simulated summaries fall within \varepsilon of the observed ones. It tends to \pi(\theta \mid s(y)) as \varepsilon \to 0.
  • The error behaves like N^{-4/(q+4)} with q summaries: few, informative summaries are essential.
  • Regression adjustment corrects the first-order effect of the tolerance.
  • ABC-MCMC is Metropolis–Hastings on pairs (\theta, y'), where the intractable likelihoods cancel.
  • ABC-SMC lowers the tolerance progressively and reweights particles by importance sampling.

10. Research directions and open problems

This self-study chapter connects the course to current research. Each section names published work, states what is known, and ends with questions that remain open. It assumes ch. 1–9.

10.1 Gradient-based samplers

The Langevin diffusion dX_t = \nabla \log\pi(X_t)\, dt + \sqrt 2\, dW_t leaves \pi invariant. Its Euler discretisation with step h is the unadjusted Langevin algorithm (ULA): X_{k+1} = X_k + h\, \nabla\log\pi(X_k) + \sqrt{2h}\ \xi_{k+1}, \qquad \xi_{k+1} \sim \mathcal N(0, I_d) . ULA is biased for every h > 0. Using its step as a Metropolis–Hastings proposal removes the bias: this is MALA, the Metropolis-adjusted Langevin algorithm (Roberts and Tweedie, 1996).

import numpy as np

rng = np.random.default_rng(17)
d, n = 100, 5_000
grad_log_pi = lambda x: -x                          # target N(0, I_d)
log_pi = lambda x: -0.5 * x @ x

def run(kind, h):
    x, acc, first = rng.standard_normal(d), 0, np.empty(n)
    for t in range(n):
        if kind == "RWM":
            y = x + np.sqrt(h) * rng.standard_normal(d)
            log_q = 0.0
        else:                                       # MALA: Langevin proposal + MH correction
            mean_x = x + h * grad_log_pi(x)
            y = mean_x + np.sqrt(2 * h) * rng.standard_normal(d)
            mean_y = y + h * grad_log_pi(y)
            log_q = (-np.sum((x - mean_y) ** 2) + np.sum((y - mean_x) ** 2)) / (4 * h)
        if np.log(rng.random()) < log_pi(y) - log_pi(x) + log_q:
            x, acc = y, acc + 1
        first[t] = x[0]
    return acc / n, np.corrcoef(first[:-1], first[1:])[0, 1]

print("RWM , h = 2.38^2/d     : acceptance %.3f, lag-1 autocorrelation of x_1 %.3f" % run("RWM", 2.38 ** 2 / d))
print("MALA, h = 1.3 d^(-1/3) : acceptance %.3f, lag-1 autocorrelation of x_1 %.3f" % run("MALA", 1.3 * d ** (-1 / 3)))

In dimension 100, the optimally scaled random walk has a lag-1 autocorrelation of 0.995; MALA, at an acceptance rate near 0.59, has 0.80. One gradient evaluation per step buys a large gain in mixing.

Open questions: sharp mixing times for targets that are not log-concave; samplers whose cost does not grow with the separation of the modes; the links between Langevin sampling and the score-based generative models of Diffusion and Multiscale Models in Artificial Intelligence and Stochastic Calculus in Machine Learning.

10.2 Stochastic gradients inside samplers

Stochastic gradient Langevin dynamics (Welling and Teh, 2011) runs ULA with mini-batch estimates of \nabla\log\pi and decreasing steps. It merges ch. 1 and ch. 6: the data size no longer limits the cost of an iteration.

The price is a bias that no accept–reject step can remove, since the acceptance ratio would need the full likelihood. Open question: how to trade bias, variance and cost optimally, and how to certify the accuracy of such samplers on large models.

10.3 Stochastic approximation with Markovian noise

SAEM with MCMC simulation (ch. 7.4), adaptive MCMC (ch. 8) and online EM all run Robbins–Monro recursions whose noise is Markovian and biased, not a martingale increment. Asymptotic theory follows the Poisson-equation route of Benveniste, Métivier and Priouret (1990).

Non-asymptotic bounds are more recent: Karimi, Miasojedow, Moulines and Wai (2019) give finite-time rates for biased stochastic approximation with Markovian noise. Open questions: stability without truncation; explicit rates for MCMC-SAEM in high dimension.

10.4 Theory of EM

Wu’s theorem (Theorem 3.9) only promises stationary points. Balakrishnan, Wainwright and Yu (2017) separate a population EM operator from its sample version and prove geometric convergence inside a basin of attraction, with statistical error bounds.

For a balanced mixture of two Gaussians with known covariance, Daskalakis, Tzamos and Zampetakis (2017) show that EM converges from almost any initialisation. With three or more components, Jin, Zhang, Balakrishnan, Wainwright and Jordan (2016) exhibit bad local maxima, with arbitrarily small likelihood relative to the global one, that attract EM from random initialisations with high probability. Open question: which initialisations or stochastic versions of EM provably avoid such maxima.

10.5 Tempering and multimodality

Parallel tempering with reversible swaps moves information along the ladder diffusively. Syed, Bouchard-Côté, Deligiannidis and Doucet (2022) propose a non-reversible swap scheme whose round-trip time scales better with the number of chains, and tune the ladder from the estimated communication barrier.

Woodard, Schmidler and Huber (2009) show, conversely, that tempering can mix torpidly on some multimodal targets, for instance when the modes have different widths. Open question: dimension-robust guarantees for multimodal sampling.

10.6 Simulation-based inference beyond ABC

Neural methods learn a conditional density estimator of \theta given y from simulated pairs, instead of rejecting simulations (Papamakarios and Murray, 2016). Cranmer, Brehmer and Louppe (2020) survey this field of simulation-based inference.

Within ABC, Bernton, Jacob, Gerber and Robert (2019) replace summary statistics by Wasserstein distances between empirical distributions, and Gutmann and Corander (2016) use Bayesian optimisation to reduce the number of simulations. Open questions: calibration of the resulting posteriors, and robustness when the simulator is misspecified.

10.7 Stochastic algorithms in computational anatomy

Allassonnière, Amit and Trouvé (2007) formulate the estimation of a deformable template, an average image together with its typical deformations, as maximum likelihood in a Bayesian latent-variable model. The deformation of each observed image is the hidden variable.

Allassonnière, Kuhn and Trouvé (2010) estimate such models with an MCMC-SAEM algorithm, with a Gibbs-type sampler for the deformations, and prove its convergence. The whole chain of this course appears there: a Bayesian model (ch. 2), hidden variables (ch. 3), stochastic approximation (ch. 4), MCMC (ch. 6) and SAEM (ch. 7). Related courses: Medical Image Analysis Based on Generative, Geometric and Biophysical Models and Geometry and Shape Spaces.

10.8 Removing the burn-in bias

Every MCMC estimator is biased at finite length, because the chain starts out of equilibrium. Jacob, O’Leary and Atchadé (2020) couple two chains so that they meet exactly after a random time, and build unbiased estimators from the coupled path. Independent replicas can then run in parallel, and their average has a valid confidence interval. Open question: couplings that meet quickly in high dimension.

Key takeaways — chapter 10

  • Gradient-based samplers (MALA, HMC, NUTS) scale better with the dimension than random walks; ULA has explicit non-asymptotic bounds for log-concave targets.
  • Stochastic-gradient MCMC and Markovian stochastic approximation are where ch. 1, 4 and 6 meet; their non-asymptotic theory is active.
  • EM has local guarantees and provable failures; global guarantees remain open beyond simple mixtures.
  • Tempering, neural simulation-based inference and unbiased MCMC address multimodality, intractable likelihoods and burn-in bias.
  • Deformable template estimation by MCMC-SAEM uses every tool of the course.

Exercises

The exercises are sorted by level: ★ applies the course, ★★ combines results or proves a short statement, ★★★ is open-ended or research-flavoured. The session plan says after which session each one fits.

  1. ★ How many Monte Carlo samples? (ch. 0) You estimate a probability p \approx 0.3 by the frequency of an event in n independent trials. How large must n be for a 95 % confidence half-width of 0.01? Same question for p \approx 10^{-4} and a half-width of 10 % of p.

    Solution. The half-width is 1.96\sqrt{p(1-p)/n} (Proposition 0.2).

    For p = 0.3 and half-width 0.01, n \ge 1.96^2 \times 0.21 / 10^{-4} \approx 8068.

    For p = 10^{-4} and half-width 10^{-5}, n \ge \frac{1.96^2 \times p(1 - p)}{10^{-10}} \approx 3.8 \times 10^6 . The relative error of crude Monte Carlo is about 1/\sqrt{np}: rare events call for importance sampling (Example 5.10).

  2. ★ SGD computes a mean. (ch. 1) Take f(\theta, Z) = \frac12(\theta - Z)^2 with \mathbb{E}Z = m and \mathrm{Var}\,Z = \sigma^2. Show that SGD with \gamma_t = 1/t returns the running mean of Z_1, \dots, Z_t from any \theta_0. Compare its exact error with the bound of Theorem 1.3.

    Solution. The gradient is \theta - Z and F is 1-strongly convex, so \gamma_t = 1/(\mu t) = 1/t. The update reads \theta_t = (1 - 1/t)\theta_{t-1} + Z_t/t.

    At t = 1, \theta_1 = Z_1 and \theta_0 is forgotten; by induction, t\theta_t = (t-1)\theta_{t-1} + Z_t = \sum_{s \le t} Z_s. The exact error is \mathbb{E}(\theta_t - m)^2 = \sigma^2/t.

    The bound of Theorem 1.3 is B^2/t, where B^2 must dominate the second moment of the gradient: B^2 \ge \mathbb{E}(\theta - Z)^2 = (\theta - m)^2 + \sigma^2 \ge \sigma^2 . The bound is therefore tight up to the size of the domain.

  3. ★ Gamma–Poisson. (ch. 2) Let y_1, \dots, y_n be independent Poisson with mean \lambda, and let the prior be \mathrm{Gamma}(a, b) with density proportional to \lambda^{a-1}e^{-b\lambda}. Find the posterior.

    With a = 2, b = 1, n = 5 and \sum_i y_i = 13, compute the posterior mean, mode and standard deviation, and the maximum-likelihood estimate.

    Solution. The posterior is proportional to the likelihood times the prior, \lambda^{\sum_i y_i} e^{-n\lambda} \cdot \lambda^{a-1} e^{-b\lambda}, so it is \mathrm{Gamma}(a + \sum_i y_i,\ b + n), here \mathrm{Gamma}(15, 6).

    Mean 15/6 = 2.5, mode 14/6 \approx 2.333, standard deviation \sqrt{15}/6 \approx 0.645, and maximum-likelihood estimate 13/5 = 2.6.

    The posterior mean is the weighted average \frac16 \times 2 + \frac56 \times 2.6 of the prior mean and the data mean.

  4. ★ Inversion. (ch. 5) Give inversion formulas for the Pareto law, with distribution function 1 - (x_m/x)^\alpha for x \ge x_m; for the Weibull law, with distribution function 1 - \exp(-(x/\lambda)^k); and for the geometric law on \{1, 2, \dots\} with parameter p.

    Solution. Using that 1 - U is uniform: Pareto, x_m U^{-1/\alpha}; Weibull, \lambda(-\log U)^{1/k}.

    Geometric: X = \lceil \log U / \log(1-p) \rceil. Indeed X > k if and only if \log U < k\log(1 - p), since \log(1-p) < 0. This has probability (1-p)^k, the geometric tail.

  5. ★ Rejection for Beta laws. (ch. 5) Sample \mathrm{Beta}(2, 2), with density 6x(1-x), by rejection from the uniform proposal: find M and the acceptance rate. Then do the same for \mathrm{Beta}(2.7, 6.3), and propose a better proposal.

    Solution. For \mathrm{Beta}(2,2), M = \max 6x(1-x) = 1.5 at x = 1/2, and the acceptance rate is 2/3.

    For \mathrm{Beta}(2.7, 6.3), M is the density at the mode 1.7/7 \approx 0.243, that is M \approx 2.67, and the acceptance rate is 0.375.

    The proposal \mathrm{Beta}(2, 6), easy to simulate with integer parameters, gives a density ratio proportional to x^{0.7}(1-x)^{0.3}, maximal at x = 0.7. Then M \approx 1.67 and the acceptance rate rises to 0.60.

  6. ★ Gibbs on a correlated Gaussian (Python). (ch. 6) Run the Gibbs sampler of Example 6.12 for \rho \in \{0, 0.5, 0.9, 0.99\} and compare n/\mathrm{ESS} with (1 + \rho^2)/(1 - \rho^2). Then explain how to make the sampler efficient for every \rho.

    Solution.

    import numpy as np
    
    rng = np.random.default_rng(11)
    
    def ess(x):
        x = x - x.mean(); n = x.size
        f = np.fft.rfft(x, 2 * n)
        acf = np.fft.irfft(f * np.conj(f))[:n] / (x.var() * n)
        neg = np.argmax(acf[1:] < 0) + 1
        return n / (1 + 2 * acf[1:neg].sum())
    
    n = 20_000
    for rho in [0.0, 0.5, 0.9, 0.99]:
        xs, x, y, c = np.empty(n), 0.0, 0.0, np.sqrt(1 - rho ** 2)
        for t in range(n):
            x = rho * y + c * rng.standard_normal()
            y = rho * x + c * rng.standard_normal()
            xs[t] = x
        print(f"rho = {rho:4.2f}: n/ESS = {n / ess(xs):6.1f}   theory {(1 + rho**2) / (1 - rho**2):6.1f}")

    The run gives about 1.0, 1.7, 9.3 and 104, against 1, 1.67, 9.53 and 99.5 in theory.

    The rotated coordinates (X + Y)/\sqrt2 and (X - Y)/\sqrt2 are independent. A Gibbs sampler in those coordinates, or a single block update of (X, Y), therefore has \tau = 1 for every \rho.

  7. ★★ A step size that is too small. (ch. 1) Take F(\theta) = \mu\theta^2/2 with exact gradients and steps \gamma_t = c/t, where 2\mu c < 1. Prove that, for a constant C > 0, |\theta_t| \ge C\,|\theta_0|\, t^{-\mu c} . What is the error after 10^6 iterations when \mu c = 0.1?

    Solution. The iterates are \theta_t = \theta_0 \prod_{s=1}^t (1 - \mu c/s), with factors in [1/2, 1) because \mu c < 1/2.

    For x \in [0, 1/2], \log(1 - x) \ge -x - x^2. Hence the logarithm of the product is at least -\mu c\sum_{s \le t} 1/s - (\mu c)^2 \sum_s 1/s^2, which is at least -\mu c(1 + \log t) - (\mu c)^2\pi^2/6.

    Exponentiating gives the bound with C = e^{-\mu c - (\mu c)^2\pi^2/6}. With \mu c = 0.1, t^{-0.1} = 10^{-0.6} \approx 0.25 after 10^6 steps: the squared error is still of order 0.06\,\theta_0^2.

    With c = 1/\mu, by contrast, the first step lands exactly on the minimiser, and with noise Theorem 1.3 gives an error of order 1/t (Remark 1.4).

  8. ★★ Majorize–Minimize for least absolute deviations. (ch. 3) Using Example 3.3, derive the MM iteration for minimising F(\theta) = \sum_i |y_i - x_i^\top\theta| and prove that F decreases. Run three iterations by hand for the median of (1, 2, 10) from \theta_0 = 5.

    Solution. With r_i(\theta) = y_i - x_i^\top\theta and weights w_i = 1/|r_i(\theta_k)|, the surrogate is \frac12\sum_i w_i r_i(\theta)^2 plus a constant. Its minimiser is the weighted least-squares solution \theta_{k+1} = (X^\top W_k X)^{-1} X^\top W_k\, y . F decreases by Proposition 3.2. This is iteratively reweighted least squares; in practice |r_i| is replaced by \max(|r_i|, \delta), which majorizes a smoothed objective.

    For the median (x_i = 1), \theta_{k+1} is the average of the y_i with weights 1/|y_i - \theta_k|.

    From \theta_0 = 5, the iterates are 3.723, 2.820 and 2.296. Meanwhile F goes from 12 through 10.72 and 9.82 to 9.30, towards the minimum F(2) = 9.

  9. ★★ EM for censored lifetimes. (ch. 3) Lifetimes T_i \sim \mathrm{Exp}(\lambda) are censored at times c_i: one observes y_i = \min(T_i, c_i) and \delta_i = \mathbf 1\{T_i \le c_i\}. Derive EM with the T_i as complete data, find its fixed point, and compute its rate.

    Iterate from \lambda_0 = 1 with n = 10, r = \sum_i \delta_i = 6 and \sum_i y_i = 15.

    Solution. The complete log-likelihood is n\log\lambda - \lambda\sum_i T_i. By the memoryless property, \mathbb{E}[T_i \mid T_i > c_i] = c_i + 1/\lambda_k. Hence \lambda_{k+1} = \frac{n}{\sum_i y_i + (n - r)/\lambda_k} . The fixed point solves \lambda\sum_i y_i + n - r = n, so \lambda^* = r/\sum_i y_i = 0.4, the closed-form maximum-likelihood estimate.

    The derivative of the EM map at \lambda^* is (n - r)/n = 0.4, the fraction of censored data, as Proposition 3.10 predicts.

    The iterates are 0.526, 0.442, 0.416, 0.406 and 0.402: the error shrinks by a factor approaching 0.4.

  10. ★★ Averaging in practice (Python). (ch. 4) Estimate by simulation the variance of \sqrt N(\bar\theta_N - \theta^*) for the averaged quantile recursion of Example 4.10 with steps n^{-2/3}, over 200 replications, and compare with Theorem 4.9.

    Solution.

    import numpy as np
    
    rng = np.random.default_rng(12)
    alpha, N, R = 0.9, 100_000, 200
    target = np.log(10.0)                            # true 0.9-quantile of Exp(1)
    th, avg = np.zeros(R), np.zeros(R)               # R independent replications, vectorised
    for n in range(1, N + 1):
        x = rng.exponential(size=R)
        th += n ** (-2 / 3) * (alpha - (x <= th))
        avg += (th - avg) / n
    print(f"N Var(averaged RM) = {N * np.var(avg - target):.2f}   (theory alpha(1-alpha)/f^2 = 9)")

    The run gives about 8.8, against the optimal value \alpha(1-\alpha)/f(\theta^*)^2 = 0.09/0.01 = 9, which is also the asymptotic variance of the empirical quantile. With only N = 10^4 steps the value is noticeably higher: the initial transient of the average has not yet faded.

  11. ★★ Other acceptance rules. (ch. 6) (a) Show that Barker’s acceptance probability r/(1 + r), where r is the Metropolis–Hastings ratio, also gives a \pi-reversible kernel. (b) Compare it with \min(1, r). (c) For the standard Gaussian target and an independent Gaussian proposal \mathcal N(0, \sigma^2), for which \sigma is the chain uniformly ergodic?

    Solution. (a) With a = \pi(x)q(x,y) and b = \pi(y)q(y,x), the flow from x to y is a \cdot \frac{b/a}{1 + b/a} = \frac{ab}{a + b}, which is symmetric in (x, y).

    (b) r/(1+r) \le \min(1, r), so Barker’s rule rejects more often. By Peskun’s ordering (Peskun, 1973), Metropolis–Hastings then has a smaller asymptotic variance for every function.

    (c) The weight w(x) = \varphi(x)/g(x) is proportional to \exp(-x^2(1 - \sigma^{-2})/2). It is bounded if and only if \sigma \ge 1, which is the condition for uniform ergodicity (ch. 6.2). For \sigma < 1, a chain in the tails, where w is huge, almost never leaves.

  12. ★★ The swap move in numbers. (ch. 8) In Example 8.8, the cold chain sits at x_0 = -5. Compute the swap acceptance probability with the level \beta_1 = 0.3 when x_1 = 5, and when x_1 = 0. Explain why a direct swap between \beta = 1 and \beta = 0.03 would rarely be accepted.

    Solution. Up to a constant, the log-target is \log\tilde\pi(x) = \log\big(e^{-(x+5)^2/2} + e^{-(x-5)^2/2}\big) . Two cases arise.

    • for x_1 = 5, the two values of \tilde\pi are equal, the ratio is 1, and the swap is always accepted: the cold chain jumps to the other mode;
    • for x_1 = 0, the log-ratio is \log\tilde\pi(0) - \log\tilde\pi(-5) \approx -12.5 + \log 2 = -11.81 , and the acceptance probability is e^{-0.7 \times 11.81} \approx 2.6 \times 10^{-4}.

    A chain at \beta = 0.03 wanders far from both modes, where \log\tilde\pi is very negative. Exchanging it with the cold chain multiplies a large energy difference by 0.97, so the swap is almost never accepted: the intermediate levels are necessary.

  13. ★★ ABC for the g-and-k distribution (Python). (ch. 9) The g-and-k distribution is defined by its quantile function Q(u) = A + B\big[1 + 0.8\tanh(g z_u/2)\big](1 + z_u^2)^k\, z_u, \qquad z_u = \Phi^{-1}(u), and has no closed-form density (Allingham, King and Mengersen, 2009). With B = 1 and k = 0.5 known, estimate (A, g) from 200 observations by rejection ABC, using the median and two quantile-based skewness measures as summaries.

    Solution. Sampling is inversion (ch. 5.1) with z_u replaced by a standard Gaussian draw.

    import numpy as np
    
    rng = np.random.default_rng(13)
    
    def gk_sample(A, B, g, k, size):
        z = rng.standard_normal(size)                # z = Phi^{-1}(U): inversion of the quantile function
        return A + B * (1 + 0.8 * np.tanh(g * z / 2)) * (1 + z ** 2) ** k * z
    
    def summaries(y):                                # median and two quantile skewness measures, row-wise
        q = np.sort(y, axis=-1)
        m = y.shape[-1]
        qq = lambda p: q[..., int(p * (m - 1))]
        q25, q40, q50, q60, q75 = (qq(p) for p in (0.25, 0.4, 0.5, 0.6, 0.75))
        return np.stack([q50, (q75 + q25 - 2 * q50) / (q75 - q25),
                         (q60 + q40 - 2 * q50) / (q60 - q40)], axis=-1)
    
    n, B, k = 200, 1.0, 0.5
    y_obs = gk_sample(3.0, B, 2.0, k, n)              # true (A, g) = (3, 2)
    s_obs = summaries(y_obs)
    
    N = 40_000
    A = rng.uniform(0, 10, N); g = rng.uniform(0, 5, N)       # uniform priors
    s = summaries(gk_sample(A[:, None], B, g[:, None], k, (N, n)))
    scale = s.std(axis=0)
    d = np.sqrt((((s - s_obs) / scale) ** 2).sum(axis=1))
    keep = d <= np.quantile(d, 0.01)                           # keep the closest 1 %
    print(f"A: mean {A[keep].mean():.2f}, sd {A[keep].std():.2f} | "
          f"g: mean {g[keep].mean():.2f}, sd {g[keep].std():.2f}  (truth A = 3, g = 2)")

    The ABC posterior has mean about 3.1 for A and 2.4 for g, with standard deviations of about 0.5 and 0.8. The truth lies within one standard deviation.

    The skewness of the quartiles saturates for large g, because \tanh does, which is why an inner skewness measure helps. Regression adjustment (ch. 9.2) sharpens both marginals.

  14. ★★★ SEM, SAEM and the Lyapunov function on a mixture. (ch. 7) Consider the mixture, with equal weights, of two unit-variance Gaussians with unknown means \mu_1 and \mu_2. (a) Write S, \bar\theta and \bar s. (b) Compute \langle \nabla W(s), h(s)\rangle of Proposition 7.4 explicitly. (c) Prove that SEM cannot converge almost surely.

    Solution. (a) The complete log-likelihood is \sum_i \sum_j \mathbf 1\{z_i = j\}(y_i\mu_j - \mu_j^2/2) plus a constant. So S = (n_1, \sum_{z_i = 1} y_i, n_2, \sum_{z_i = 2} y_i) and \bar\theta(s) = (s_2/s_1,\ s_4/s_3). The expectation \bar s replaces the indicators by the responsibilities r_i and 1 - r_i.

    (b) Here \varphi(\theta) = (-\mu_1^2/2,\ \mu_1,\ -\mu_2^2/2,\ \mu_2), \qquad H(s) = \mathrm{diag}(-s_1, -s_3) . A direct computation gives \langle \nabla W(s), h(s)\rangle = \frac{\bar s_1^2}{s_1}\big(\mu_1^{\mathrm{EM}} - \mu_1\big)^2 + \frac{\bar s_3^2}{s_3}\big(\mu_2^{\mathrm{EM}} - \mu_2\big)^2 , where \mu^{\mathrm{EM}} is one EM update from \bar\theta(s). It vanishes exactly at the fixed points of EM.

    (c) Suppose that (\theta_k) converges with positive probability. On that event the iterates eventually stay in a compact set, where the responsibilities lie in [\eta, 1 - \eta] for some \eta > 0. Every labelling then has probability at least \eta^n, and two labellings give means at least 2\delta apart, for some \delta > 0. Hence, eventually, P\big(|\theta_k - \theta_{k-1}| > \delta \mid \mathcal F_{k-1}\big) \ge \eta^n . By Lévy’s conditional Borel–Cantelli lemma, jumps larger than \delta occur infinitely often on that event, which contradicts convergence.

  15. ★★★ Making a bad adaptation safe. (ch. 8) (a) In Example 8.3, check that each kernel is \pi-reversible, and compute the stationary law of the adaptive chain for \varepsilon = 0.1. (b) Modify the rule so that at time n the state-dependent choice is used only with probability 1/n, and P_b otherwise. Show that Theorem 8.4 applies. (c) Discuss what plays the role of \varepsilon I_d in Algorithm 8.1.

    Solution. (a) Both matrices are symmetric with rows summing to 1, hence reversible for the uniform law. The adaptive chain has \pi'(0) = 1/(1 + 2\varepsilon) = 0.833 instead of 0.5.

    (b) At time n, the chain now uses the state-dependent kernel with probability 1/n, and P_b otherwise. Every kernel used is still one of the two kernels of (a), hence \pi-invariant. Two consecutive kernels differ only if one of them comes from the state-dependent choice, which has probability at most 2/n: adaptation diminishes in probability.

    Containment holds because only two kernels are ever used, and both are uniformly ergodic: P_b reaches \pi in one step, and P_a comes within any fixed distance of \pi after a fixed number of steps, since its second eigenvalue is 1 - 2\varepsilon. Theorem 8.4 then gives convergence to \pi.

    (c) Without \varepsilon I_d, a chain that stays still for a while makes \Sigma_n shrink, smaller proposals make it move less, and the proposal can collapse. The regularisation keeps a minimal proposal scale, which is the containment condition in disguise (Saksman and Vihola, 2010).

  16. ★★★ Optimal scaling, empirically (Python). (ch. 6, 8, 10) For random-walk Metropolis on \mathcal N(0, I_{20}) with proposal \mathcal N(x, \frac{\ell^2}{d} I_d), plot the efficiency \mathrm{ESS}/n of x_1 against the acceptance rate as \ell varies. Is the optimum near 0.234? Open part: repeat in dimension 1 and 5, on a correlated Gaussian, and on the mixture of Example 8.8, and compare with MALA (ch. 10.1).

    Hints and expected result.

    import numpy as np
    
    rng = np.random.default_rng(16)
    
    def ess(x):
        x = x - x.mean(); n = x.size
        f = np.fft.rfft(x, 2 * n)
        acf = np.fft.irfft(f * np.conj(f))[:n] / (x.var() * n)
        neg = np.argmax(acf[1:] < 0) + 1
        return n / (1 + 2 * acf[1:neg].sum())
    
    d, n = 20, 20_000
    for ell in [0.5, 1.0, 1.7, 2.38, 3.5, 5.0]:
        x, lp, acc, chain = np.zeros(d), 0.0, 0, np.empty(n)
        z = rng.standard_normal((n, d)) * ell / np.sqrt(d)
        logu = np.log(rng.random(n))
        for t in range(n):
            y = x + z[t]
            lpy = -0.5 * y @ y
            if logu[t] < lpy - lp:
                x, lp, acc = y, lpy, acc + 1
            chain[t] = x[0]
        print(f"ell = {ell:4.2f}: acceptance {acc / n:.3f}, ESS/n = {ess(chain) / n:.4f}")

    The acceptance rates go from about 0.81 to 0.02 as \ell grows. The efficiency peaks near \ell = 2.38, with acceptance about 0.25, on a flat plateau between \ell = 1.7 and 3.5.

    In dimension 1 the optimum moves to an acceptance rate near 0.44. For correlated targets the rule holds only after rescaling by the target covariance, which is what adaptive Metropolis provides. For the mixture no scale works, and tempering is needed.

Projects and assessment

The official assessment, on master-mva.com, has two parts. Homework following each training session, four assignments in total (“(4)” on the page), counts for 2/3 of the grade. The oral presentation of one scientific paper, prepared as team work with no written report, counts for 1/3. The Université Paris-Saclay course detail describes the assessment as “Evaluation Continue non Intégrale”.

The solo subjects below are sized like an extended homework. The group subjects are paper studies for a team of two that end, as in the official format, with an oral presentation and no report. The written exam is a self-assessment proposal: no written exam is announced.

Solo projects

  1. [Solo · ≈ 20 h] Step sizes and averaging in SGD. How sensitive is SGD to its step-size constant, and does averaging remove that sensitivity? A paper study of Nemirovski, Juditsky, Lan and Shapiro (2009), with Polyak and Juditsky (1992).
    • Implement: SGD for \ell_2-regularised logistic regression with steps c/t over a grid of c, a constant step, and averaged steps t^{-1/2} and t^{-2/3}.
    • Data: the breast-cancer data set bundled with scikit-learn (569 samples, 30 features, standardised before use); reference optimum by SciPy’s L-BFGS.
    • Deliverables: code, 4–6 page report, 10-minute talk. Chapters: ch. 1, 4.
    • Success criterion: reproduce the t^{-2\mu c} slowdown of Remark 1.4, and show averaged SGD within a factor 2 of the best tuned c/t.
  2. [Solo · ≈ 20 h] Optimal scaling of random-walk Metropolis. Does the 0.234 rule hold in moderate dimension and beyond product targets? A paper study of Roberts, Gelman and Gilks (1997).
    • Implement: random-walk Metropolis with an ESS estimator, on Gaussian product targets in dimensions 1, 5, 20 and 100, then on a correlated Gaussian and a two-component mixture.
    • Deliverables: code, 4–6 page report with efficiency-versus-acceptance curves, 10-minute talk. Chapters: ch. 6, 8.
    • Success criterion: the efficiency peak moves from about 0.44 in dimension 1 to about 0.23 in dimension 100, within the Monte Carlo error.
  3. [Solo · ≈ 20 h] EM, SEM and SAEM on a hard mixture. Which algorithm finds the global maximum of a mixture likelihood most often, and how fast? A paper study of Celeux and Diebolt (1985) and Delyon, Lavielle and Moulines (1999).
    • Implement: the three algorithms for a one-dimensional three-component Gaussian mixture with overlapping components (for instance equal weights, means 0, 1.5 and 3, unit variances, 500 synthetic points), each from the same 100 random initialisations.
    • Deliverables: code, 4–6 page report, 10-minute talk. Chapters: ch. 3, 7.
    • Success criterion: a table giving, for each algorithm, how often it reaches the best likelihood found and after how many iterations; the empirical linear rate of EM near its limit matches the spectral radius of I_c^{-1} I_m (Proposition 3.10) within 10 %.

Group projects

  1. [Group of 2 · ≈ 25 h each] MCMC-SAEM for a pharmacokinetic mixed-effects model. Can MCMC-SAEM recover population parameters and their standard errors in a nonlinear mixed-effects model? A paper study of Kuhn and Lavielle (2004) and Delyon, Lavielle and Moulines (1999).
    • Model and data: a one-compartment model with first-order absorption and log-normal random effects on absorption rate, volume and elimination rate; 20 synthetic data sets of 50 subjects with 10 samples each.
    • Split: member A writes the model, the simulator and the MCMC kernel; member B writes the stochastic approximation, the M-step and the Fisher information by Louis’ formula.
    • Deliverables: code and a 20-minute joint presentation, no report. Chapters: ch. 3, 4, 6, 7.
    • Success criterion: the 95 % intervals cover the true values in at least 17 of the 20 data sets, the range expected for a 95 % coverage.
  2. [Group of 2 · ≈ 25 h each] Adaptive parallel tempering. Does an adaptive temperature ladder match a hand-tuned one on strongly multimodal targets? A paper study of Miasojedow, Moulines and Vihola (2013).
    • Implement: parallel tempering with the ladder adaptation of Algorithm 8.9 and adaptive Metropolis at every level.
    • Targets: a two-dimensional mixture of 20 well-separated Gaussians, and a bimodal Gaussian mixture in dimension 10.
    • Split: member A writes the sampler and the local adaptation; member B writes the ladder adaptation and the diagnostics (mode-visit frequencies, swap rates, ESS).
    • Deliverables: code and a 20-minute joint presentation, no report. Chapters: ch. 6, 8. Success criterion: every mode visited with its correct frequency within 10 %.
  3. [Group of 2 · ≈ 25 h each] Likelihood-free inference for the g-and-k distribution. How many simulations do rejection ABC, ABC-MCMC and ABC-SMC need for the same accuracy? A paper study of Beaumont, Cornuet, Marin and Robert (2009), with Allingham, King and Mengersen (2009) for the model.
    • Implement: the three samplers with regression adjustment, and an exact-likelihood MCMC baseline that evaluates the density by numerical inversion of the quantile function.
    • Split: member A writes rejection ABC and ABC-MCMC; member B writes ABC-SMC and the exact baseline.
    • Deliverables: code and a 20-minute joint presentation, no report. Chapters: ch. 5, 6, 9.
    • Success criterion: posterior means within 0.1 posterior standard deviation of the exact ones, reported against the number of simulations.

Written exam (proposal)

Two hours, one handwritten A4 sheet allowed, no calculator needed; four independent questions.

  1. Question (5 points). State the Metropolis–Hastings algorithm for a target known up to a constant. Prove that its kernel satisfies detailed balance, and explain why the normalising constant is not needed. What goes wrong with a random-walk proposal that is too small, or too large?

    Expected: Algorithm 6.6; the flow \min(\pi(x)q(x,y), \pi(y)q(y,x)) is symmetric and rejections sit on the diagonal (Theorem 6.7); the constant cancels in the ratio. Too small: high acceptance, tiny moves, high autocorrelation. Too large: almost all rejected. Rule of thumb: acceptance near 0.234.

  2. Question (6 points). Observations y_1, \dots, y_n come from a mixture of two Poisson laws: \mathrm{Poisson}(\lambda_1) with weight w and \mathrm{Poisson}(\lambda_2) with weight 1 - w. Write the complete-data log-likelihood, the E-step and the M-step of EM, and prove in three lines that the likelihood does not decrease.

    Expected: responsibilities r_i proportional to w\, e^{-\lambda_1}\lambda_1^{y_i} against (1 - w)\, e^{-\lambda_2}\lambda_2^{y_i}; updates w = \frac1n\sum_i r_i and \lambda_1 = \sum_i r_i y_i / \sum_i r_i, and symmetrically for \lambda_2.

    Monotonicity follows from the lower bound \mathcal L(q, \theta) and Gibbs’ inequality (Theorem 3.6).

  3. Question (5 points). Let F be \mu-strongly convex on a compact convex set \Theta, with stochastic gradients of second moment at most B^2. Prove that projected SGD with steps 1/(\mu t) satisfies \mathbb{E}\|\theta_t - \theta^*\|^2 \le B^2/(\mu^2 t).

    Expected: non-expansiveness of the projection; the one-step recursion \delta_t \le (1 - 2\mu\gamma_t)\,\delta_{t-1} + \gamma_t^2 B^2 from strong monotonicity and optimality; the induction of Theorem 1.3, including the case t = 1.

  4. Question (4 points). (a) Sample \mathrm{Beta}(2, 2) by rejection from the uniform law: give M, the acceptance rate and the mean number of proposals. (b) Show that rejection ABC with discrete data, s the identity and \varepsilon = 0 samples the exact posterior.

    Expected: (a) M = 3/2, acceptance 2/3, mean 3/2 proposals (Theorem 5.5). (b) A draw \theta is accepted with probability P_\theta(Y' = y) = p(y \mid \theta), so accepted values have density proportional to \pi(\theta)p(y \mid \theta) (Proposition 9.2).

Total: 5 + 6 + 5 + 4 = 20 points.

Grading rubric (proposal)

Criterion Weight What earns the marks
Understanding of the method or paper 25 % The problem, the algorithm and its assumptions are stated precisely; the key theorem is explained, with its proof idea
Correctness of the implementation 25 % The code runs from a fixed seed, is checked on a case with a known answer, and matches the paper’s setting
Experimental design and analysis 20 % Comparisons at equal cost, Monte Carlo error bars, effective sample sizes, honest reporting of failures
Oral presentation 20 % Clear structure within the time limit, readable figures, and a correct answer to the question “why does it work?”
Questions and teamwork 10 % Precise answers to questions; for groups, a visible and balanced split of the work

References

Official references. Neither the master-mva.com course page nor the Université Paris-Saclay course detail lists a bibliography for 2026–2027. The works below are standard sources for the topics of the official description.

Textbooks

Stochastic gradient and stochastic approximation (ch. 1, 4)

EM, MM and their stochastic versions (ch. 3, 7)

Simulation and MCMC (ch. 5, 6)

Adaptive MCMC and tempering (ch. 8)

Approximate Bayesian computation (ch. 9)

Research directions (ch. 10)