ES98A · Course contents

Week 4: Computing expectations with Monte Carlo and Markov chains

A posterior is useful only if we can extract a prediction from it. Even after specifying a law μ\mu, an integral such as Eμ[f]\mathbb E_\mu[f] may be inaccessible analytically. Could repeated draws replace a high-dimensional integration grid?

Imagine estimating the probability of an event by counting its frequency. Monte Carlo applies exactly that idea to a general integrand. We first distinguish three promises (correct average, eventual convergence and finite-sample accuracy), then ask what survives when independent draws are unavailable.

Week 4: Monte Carlo methods

Monte Carlo methods

We now focus very much on estimating integrals of the form

Q(f):=Ex∼μ[f(x)]=∫Rdf(x) μ(dx),Q(f) := \mathbb{E}_{x\sim\mu}[f(x)] = \int_{\mathbb{R}^d} f(x)\,\mu(dx),

where xx is an Rd\mathbb{R}^d-valued r.v. and f:Rd→Rf:\mathbb{R}^d\to\mathbb{R} (or at least defined on the range of xx); μ\mu is the law of xx, and we usually assume that μ\mu has PDF ρ:Rd→[0,∞]\rho:\mathbb{R}^d\to[0,\infty] with

∫Rdρ(x) dx=1.\int_{\mathbb{R}^d}\rho(x)\,dx = 1.

We often call μ\mu the target distribution and ρ\rho the target density.

Key assumption: the integral defining Q(f)Q(f) actually converges, i.e.

Ex∼μ[∣f(x)∣]<∞.\mathbb{E}_{x\sim\mu}[|f(x)|] < \infty.

"Vanilla" Monte Carlo

Key enabling assumption: We can draw as many independent samples x1,x2,x3,…x_1,x_2,x_3,\ldots as we like from the target distr. μ\mu.

In this situation, we approximate Q(f)Q(f) by the Monte Carlo estimator

Q^J(f):=1J∑j=1Jf(xj).\hat{Q}_J(f) := \frac{1}{J}\sum_{j=1}^J f(x_j).

Unbiasedness and LLN

E ⁣[Q^J(f)]=E ⁣[1J∑j=1Jf(xj)]=1J∑j=1JE[f(xj)]=1J J Q(f)=Q(f).\begin{aligned} \mathbb{E}\!\left[\hat{Q}_J(f)\right] &= \mathbb{E}\!\left[\frac{1}{J}\sum_{j=1}^J f(x_j)\right] \\ &= \frac{1}{J}\sum_{j=1}^J \mathbb{E}[f(x_j)] \\ &= \frac{1}{J}\,J\,Q(f) \\ &= Q(f). \end{aligned}

(since x1,…,xJx_1,\ldots,x_J have the same law)

We also have convergence as the number of samples tends to infinity by the law of large numbers (LLN): so long as Q(f)Q(f) exists (i.e. E[∣f(x)∣]<∞\mathbb{E}[|f(x)|]<\infty), Q^J(f)\hat{Q}_J(f) converges to Q(f)Q(f) almost surely as J→∞J\to\infty, i.e.

P ⁣[lim⁡J→∞Q^J(f)=Q(f)]=1.\mathbb{P}\!\left[\lim_{J\to\infty}\hat{Q}_J(f)=Q(f)\right]=1.

When f∈L2(μ)f\in L^2(\mu), MC estimators converge in root mean square at a that is independent of the dimension dd; the rate is the inverse square root of the no. of samples taken, i.e. like J−1/2J^{-1/2}.

Let's examine the random quadrature error

EJ(f):=Q^J(f)−Q(f),E_J(f) := \hat{Q}_J(f) - Q(f),

which has mean zero and variance

E[∣EJ(f)∣2]=E ⁣[∣Q^J(f)−E[Q^J(f)]∣2]=V[Q^J(f)]=1J2 J V[f(x)]=1J V[f(x)].\mathbb{E}[|E_J(f)|^2] = \mathbb{E}\!\left[\left|\hat{Q}_J(f)-\mathbb{E}[\hat{Q}_J(f)]\right|^2\right] = \mathbb{V}[\hat{Q}_J(f)] = \frac{1}{J^2}\,J\,\mathbb{V}[f(x)] = \frac{1}{J}\,\mathbb{V}[f(x)].

i.e. the root mean square error is

E[∣EJ(f)∣2]=V[f(x)]J.\sqrt{\mathbb{E}[|E_J(f)|^2]} = \frac{\sqrt{\mathbb{V}[f(x)]}}{\sqrt{J}}.

(For bounded ff, one can often do much better using tools from concentration of measure.)

Watch a single running estimate accumulate evidence. The reference line is the exact integral; the shrinking envelope is the theoretical RMSE scale, so crossing it is not a failure of the estimator.

An integral emerges from samples

Sample the integrand

0101uniform draw xf(x)=x²

Running estimate

116000.85draw count Jestimate

J=1, estimate=0.075, exact integral=1/3

New samples change one running average. The amber envelope is a scale for random error, not a promise that every running estimate stays inside it.

Play once, pause, or scrub to inspect an intermediate state.

Ready to explore.
Seeded independent pseudorandom uniform samples estimate ∫₀¹x²dx=1/3. The displayed ±1-RMSE envelope uses the exact variance 4/45, not an estimated confidence interval or a guaranteed bound on this one trace. ↗

We can also obtain a probabilistic error bound using Chebyshev's inequality: for any ε>0\varepsilon>0,

P ⁣[∣EJ(f)∣>ε]=P ⁣[∣Q^J(f)−Q(f)∣>ε]≤V[Q^J(f)]ε2=V[f(x)]Jε2.\mathbb{P}\!\left[|E_J(f)|>\varepsilon\right] = \mathbb{P}\!\left[|\hat{Q}_J(f)-Q(f)|>\varepsilon\right] \le \frac{\mathbb{V}[\hat{Q}_J(f)]}{\varepsilon^2} = \frac{\mathbb{V}[f(x)]}{J\varepsilon^2}.

The Jε2J\varepsilon^2 part highlights the basic inverse sq. root cost-accuracy tradeoff in MC methods: if you want ε/2\varepsilon/2 instead of ε\varepsilon (i.e. to double the accuracy), then you must quadruple JJ since

4=1(1/2)2.4 = \frac{1}{(1/2)^2}.

The exponent is independent of dimension. The variance of ff and the cost of producing a draw can nevertheless grow with dimension; this is not a dimension-free computational guarantee.

But how can we apply the MC method if we cannot easily draw samples from μ\mu / ρ\rho. This spurs the Markov chain Monte Carlo (MCMC) methods we consider next.

Note that because

Q^J(f):=1J∑j=1Jf(zj)\hat{Q}_J(f):=\frac{1}{J}\sum_{j=1}^J f(z_j)

uses only the values f(zj)f(z_j) and does not care about the spacing of the nodes zjz_j, the performance of Q^J\hat{Q}_J is robust to poor features of ff (roughness, high-dim domain, ...), but it is also unable to leverage any nice features of ff (e.g. smoothness).

→\to quasi-Monte Carlo methods try to have the best of both worlds.

Before replacing independent samples by a chain, compare the cost of precision with the cost of correlation.

Independent samplingIndependent samplingdraws JRMSE (unit variance)110001solid: RMSE = 1 / √J
Stationary correlationStationary correlationlag kcorrelation03001solid: lag correlation 0.9ᵏdashed: lag correlation 0.2ᵏ
Left: exact iid RMSE for an observable of variance one. Right: illustrative stationary correlation sequences; these are analytic models, not simulated chains. ↗

Four times as many iid draws halve RMSE. A slowly decaying lag correlation can undo much of that gain: many recorded states need not mean many independent pieces of information.

Markov chain Monte Carlo

Setup: We have a formula for evaluating the target dens. ρ\rho but drawing samples from ρ\rho is hard/impossible. Our idea is to construct a random walk (more precisely, a Markov chain) of states z1,z2,…,zt,…z_1,z_2,\ldots,z_t,\ldots in Rd\mathbb{R}^d such that

  1. as t→∞t\to\infty, the distribution of ztz_t should approach/converge to the target dist. μ\mu / its PDF ρ\rho;

  2. correlations of relevant observables should decay with increasing lag. In stationarity, Cov⁡(f(zt),f(zt+1))\operatorname{Cov}(f(z_t),f(z_{t+1})) is independent of tt and need not vanish;

  3. we want to approximate integrals:

Q(f):=∫Rdf(x)ρ(x) dx=lim⁡T→∞1T∑t=1Tf(zt).Q(f) := \int_{\mathbb{R}^d} f(x)\rho(x)\,dx = \lim_{T\to\infty}\frac{1}{T}\sum_{t=1}^T f(z_t).

(space average == time average)

Stationarity alone cannot ensure convergence of a time average: a chain that never moves preserves any starting law. For a stationary chain, write γk=Cov⁡(f(z0),f(zk))\gamma_k=\operatorname{Cov}(f(z_0),f(z_k)). Expanding the variance of the sum gives

Var⁡ ⁣[1T∑t=1Tf(zt)]=1T[γ0+2∑k=1T−1(1−kT)γk].\operatorname{Var}\!\left[\frac1T\sum_{t=1}^T f(z_t)\right] =\frac1T\left[\gamma_0+2\sum_{k=1}^{T-1}\left(1-\frac{k}{T}\right)\gamma_k\right].

Positive serial correlation inflates uncertainty. Under absolute summability the bracket tends to the asymptotic variance; it is not generally γ0\gamma_0. Ergodicity and suitable moment assumptions, rather than invariance alone, justify the limiting time-average identity.

How do we construct such sequences (zt)t(z_t)_t? We use a transition kernel / Markov kernel

χ(x,A):=P[zt+1∈A∣zt=x]\chi(x,A) := \mathbb{P}[z_{t+1}\in A \mid z_t=x]

telling us the prob. dist. of the next state given the current one.

One minimal requirement (necessary but not sufficient for (i)–(iii)) is that the target μ\mu be invariant under χ\chi, i.e. that if zt∼μz_t\sim\mu, then zt+1∼χ(zt,⋅)z_{t+1}\sim\chi(z_t,\cdot) should be μ\mu-distributed as well:

∫Rdχ(x,A) μ(dx)=μ(A)for all measurable A⊆Rd.\int_{\mathbb{R}^d}\chi(x,A)\,\mu(dx) = \mu(A) \qquad\text{for all measurable }A\subseteq\mathbb{R}^d.

In practice, to construct a χ\chi that has μ\mu as an invariant/equilibrium distn., we often construct a χ\chi that satisfies detailed balance / reversibility w.r.t. μ\mu:

∫Aχ(x,B) μ(dx)=∫Bχ(x,A) μ(dx)for all measurable A,B⊆Rd.\int_A \chi(x,B)\,\mu(dx) = \int_B \chi(x,A)\,\mu(dx) \qquad\text{for all measurable }A,B\subseteq\mathbb{R}^d.

Proof that reversibility ⇒\Rightarrow invariance. Suppose that χ\chi is μ\mu-reversible, and let A⊆RdA\subseteq\mathbb{R}^d.

∫Rdχ(x,A) μ(dx)=∫Aχ(x,Rd) μ(dx)=∫A1 μ(dx)=μ(A).\int_{\mathbb{R}^d}\chi(x,A)\,\mu(dx) = \int_A \chi(x,\mathbb{R}^d)\,\mu(dx) = \int_A 1\,\mu(dx) = \mu(A).

□\square

The Metropolis–Hastings (MH) scheme

The Metropolis–Hastings (MH) scheme offers a simple implementation of a μ\mu-reversible (and hence μ\mu-invariant) transition kernel χ\chi, in two steps.

We need one further prob. distn., called the proposal distribution Q(x,A)Q(x,A) with PDF q(x,x′)q(x,x').

  1. Given that zt=xz_t=x, draw a proposed new state z′z' with PDF q(x,⋅)q(x,\cdot). (here we need the proposal to be quick and easy to sample)

  2. Calculate the acceptance probability α(zt,z′)\alpha(z_t,z'), where

α(x,x′):=min⁡ ⁣(1, ρ(x′) q(x′,x)ρ(x) q(x,x′)).\alpha(x,x') := \min\!\left(1,\ \frac{\rho(x')\,q(x',x)}{\rho(x)\,q(x,x')}\right).

In practice compute log⁡α=min⁡(0,log⁡ρ(x′)−log⁡ρ(x)+log⁡q(x′,x)−log⁡q(x,x′))\log\alpha=\min(0,\log\rho(x')-\log\rho(x)+\log q(x',x)-\log q(x,x')) and accept when log⁡U≤log⁡α\log U\le\log\alpha. Initialise in the positive-density support; proposals with zero reverse probability are rejected. This avoids underflow and requires no normalising constant for ρ\rho.

  1. Draw z∼Unif([0,1])z\sim\mathrm{Unif}([0,1]).
    1. if z≤α(zt,z′)z\le \alpha(z_t,z'), then we accept the proposal and set zt+1:=z′z_{t+1}:=z';
    2. if z>α(zt,z′)z>\alpha(z_t,z'), then we reject the proposal and set zt+1:=ztz_{t+1}:=z_t.

FACT: The MH scheme always yields a kernel χMH\chi_{\mathrm{MH}}, i.e. a rule for sampling zt+1z_{t+1} given ztz_t, that is reversible w.r.t. μ\mu and hence has the target as an invariant distn.

Trace the algorithm one proposal at a time. When a proposal is rejected, watch both the point on the target density and the next entry in the time series. A rejected proposal still consumes an iteration.

A rejection is a real step of the chain

Target and current proposal

-4.504.500.45state xtarget density

Chain including rejected steps

060-4.504.5iterationstate

Step 1: proposed -2.446; accepted

Amber hollow proposals were rejected. Their iterations remain in the chain as repeated states; deleting them would change the sampling law.

Play once, pause, or scrub to inspect an intermediate state.

Ready to explore.
Seeded random-walk Metropolis targeting N(0,1), with a symmetric uniform proposal of half-width 2.5. Hollow markers indicate rejected proposals; the state trace repeats its previous value. This short teaching run is not evidence of convergence. ↗

Why rejection is part of the algorithm

For distinct states the accepted probability flow is

ρ(x)q(x,x′)α(x,x′)=min⁡{ρ(x)q(x,x′),ρ(x′)q(x′,x)},\rho(x)q(x,x')\alpha(x,x') =\min\{\rho(x)q(x,x'),\rho(x')q(x',x)\},

which is symmetric in x,x′x,x'. Rejected proposals supply a self-transition; the diagonal flow is automatically symmetric. This proves detailed balance, and the earlier proof then gives invariance. Deleting rejected states changes the chain and generally changes its invariant law.

Thought experiment. A reversible chain alternates deterministically between two states. Is it mixing? Its invariant law is uniform, but a point initial distribution oscillates forever. In Week 5, the Markov operator lets us recognise this obstruction as an eigenvalue −1-1.