Monte Carlo methods use randomness to solve deterministic problems. Most of them compute an integral written as an expectation,
where is a random variable with probability density , a non-negative function that integrates to 1. If are independent samples of , the law of large numbers says that their sample mean converges to the expectation:
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.integrate import quad
rng = np.random.default_rng(37830)Example: estimating ¶
The unit disk has area and lies inside the square , which has area 4. If is uniformly distributed on the square, then
where the indicator function is 1 inside the disk and 0 outside. So is about 4 times the fraction of random points in the square that land in the disk.
n = 1000
U = rng.uniform(-1, 1, size=(n, 2))
inside = np.sum(U**2, axis=1) < 1
plt.figure(figsize=(5, 5))
plt.scatter(U[~inside, 0], U[~inside, 1], s=4)
plt.scatter(U[inside, 0], U[inside, 1], s=4)
plt.gca().set_aspect('equal')
plt.show()
estimate = 4 * np.mean(inside)
print(f"estimate {estimate}, error {estimate - np.pi:+.4f}")The error of Monte Carlo¶
The estimate is random, and so is its error. Since the are independent, the variance of their sum is the sum of their variances:
The typical (root-mean-square) error is therefore . The central limit theorem says for large , is approximately normally distributed, with mean and standard deviation .
The rate is slow, since each additional correct digit costs 100 times as many samples. But it doesn’t depend on the dimension of or on the smoothness of . A quadrature rule of order that uses points in dimensions has an error of , so Monte Carlo is more accurate when , and integrals in many dimensions are almost always computed by Monte Carlo.
We check the central limit theorem by repeating the experiment 2000 times. Each sample is 4 with probability and 0 otherwise, so .
n, repeats = 1000, 2000
hits = np.sum(rng.uniform(-1, 1, size=(repeats, n, 2))**2, axis=2) < 1 # (repeats, n)
estimates = 4 * np.mean(hits, axis=1)
sigma = 4 * np.sqrt(np.pi / 4 * (1 - np.pi / 4))
bins = 4 * (np.arange(730, 842, 3) + 0.5) / n # estimates are multiples of 4/n
x = np.linspace(2.9, 3.4, 300)
plt.hist(estimates, bins=bins, density=True, alpha=0.5, label=f'{repeats} estimates with $n = {n}$')
plt.plot(x, stats.norm.pdf(x, loc=np.pi, scale=sigma / np.sqrt(n)), 'k',
label=r'normal, mean $\pi$, std. $\sigma/\sqrt{n}$')
plt.legend(loc='upper left')
plt.show()Finally, let’s look at how the error converges with :
ns = np.int32(np.logspace(0,6,100))
errs = []
for n in ns:
xs = 2*np.random.rand(2,n)-1
ids = np.linalg.norm(xs,axis=0)<1
errs.append((4*sum(ids)/n)-np.pi)
plt.loglog(ns,np.abs(errs),'o-')
plt.loglog(ns,1/np.sqrt(ns),'k--')
plt.xlabel('n')
plt.ylabel('Error')
plt.show()Error bars¶
We usually don’t know , but we can estimate it from the same samples by the sample standard deviation . The standard error then estimates the error, and by the central limit theorem
is an approximate 95% confidence interval (see SciPy stats). A Monte Carlo estimate should always be reported with an error bar like this, and it costs nothing extra to compute.
def mc_estimate(fx):
"""
sample mean and standard error of the array of samples fx
"""
return np.mean(fx), np.std(fx, ddof=1) / np.sqrt(len(fx))
for m in [10**2, 10**4, 10**6]:
U = rng.uniform(-1, 1, size=(m, 2))
est, se = mc_estimate(4 * (np.sum(U**2, axis=1) < 1))
print(f"n = {m:>7d}: pi = {est:.5f} +/- {1.96 * se:.5f}, actual error {est - np.pi:+.5f}")About 95% of these intervals should contain . We check with the 2000 repetitions above:
se = 4 * np.std(hits, axis=1, ddof=1) / np.sqrt(n)
covered = np.abs(estimates - np.pi) < 1.96 * se
print(f"{np.mean(covered):.1%} of the intervals contain pi")The error bar is only as good as the estimate of . It can be badly wrong when is very large with a small probability, as in an example below.
Importance sampling¶
Suppose we want the integral of a sharply peaked function,
The integrand is negligible outside , so we could write with uniform on . But the peak has a width of about 0.01, so almost every sample misses it, and has a large variance compared with its mean.
Instead, draw samples from a density that puts more of them where is large, and correct for this with a weight:
This is importance sampling. The estimate is unbiased for any density that is positive wherever is nonzero, but its variance depends on . We try normal distributions with several standard deviations , and measure the root-mean-square error over 50 repetitions.
f = lambda x: np.exp(-1e4*x*x)
xs = np.linspace(-1,1,1000)
plt.plot(xs,f(xs))
plt.show()exact = np.sqrt(np.pi) / 100
ns = 2 ** np.arange(4, 17)
trials = 50
def rms_relative_error(sample, weight):
"""
RMS relative error of the estimate mean(weight(Y)) over the trials, for each n in ns
sample(size) returns an array of samples Y with the given shape
"""
errors = []
for n in ns:
est = np.mean(weight(sample((trials, n))), axis=1)
errors.append(np.sqrt(np.mean((est - exact)**2)) / exact)
return np.array(errors)
plt.figure(figsize=(7, 4.5))
err = rms_relative_error(lambda size: rng.uniform(-1, 1, size), lambda y: 2 * f(y))
plt.loglog(ns, err, 'k*--', label='uniform on $[-1, 1]$')
for s in [1, 0.1, 0.01, 0.005]:
q = stats.norm(scale=s)
err = rms_relative_error(lambda size: q.rvs(size=size, random_state=rng), lambda y: f(y) / q.pdf(y))
plt.loglog(ns, err, 'o-', label=f'normal, $s = {s}$')
plt.loglog(ns, 1 / np.sqrt(ns), 'k:', label=r'$n^{-1/2}$')
plt.xlabel('$n$')
plt.ylabel('RMS relative error')
plt.legend()
plt.show()The best of these proposals is . Its error is more than 20 times smaller than that of uniform sampling. The choice would be even better. Of course, normalizing requires knowing , but we should aim for to have roughly the shape of .
Markov chain Monte Carlo¶
Often we want for a density we can’t sample from directly. A common case, in statistical physics and in Bayesian statistics, is
where we can evaluate , but the normalizing constant is unknown, because it is itself a hard integral in high dimensions.
Markov chain Monte Carlo (MCMC) generates a sequence in which each is drawn at random given only . Such a sequence is a Markov chain. We design the chain so that its stationary distribution is : after many steps the are distributed according to , and averages along the chain converge to .
The Metropolis algorithm¶
Starting from :
Propose a move , where and is a step size.
Accept it, , with probability . Otherwise reject it and stay put: .
Moves to higher probability are always accepted, and moves to lower probability only sometimes. The ratio doesn’t involve . This is a specialization of the Metropolis-Hastings algorithm, you can check the stationary probability is .
def metropolis(V, x0, delta, nsteps, rng):
"""
Metropolis chain for the density proportional to exp(-V(x)), started at x0
returns the chain X_0, ..., X_nsteps and the fraction of proposals accepted
"""
X = np.empty(nsteps + 1)
X[0] = x0
xi = rng.standard_normal(nsteps) # draw the random numbers in bulk
u = rng.random(nsteps)
accepted = 0
for i in range(nsteps):
y = X[i] + delta * xi[i]
if u[i] < np.exp(V(X[i]) - V(y)): # same as u < min(1, ratio), since u < 1
X[i + 1] = y
accepted += 1
else:
X[i + 1] = X[i]
return X, accepted / nstepsWe sample from with , which has two shallow wells at , and compare with the exact density, normalized by quadrature.
V = lambda x: x**4 - x**2
Z = quad(lambda x: np.exp(-V(x)), -np.inf, np.inf)[0]
X, acceptance = metropolis(V, x0=0.0, delta=1.0, nsteps=100_000, rng=rng)
X = X[1000:] # discard a burn-in period, see below
x = np.linspace(-2, 2, 300)
plt.hist(X, bins=60, density=True, alpha=0.5, label='Metropolis samples')
plt.plot(x, np.exp(-V(x)) / Z, 'k', label=r'$e^{-V(x)}/Z$')
plt.legend()
plt.show()
exact_x2 = quad(lambda x: x**2 * np.exp(-V(x)), -np.inf, np.inf)[0] / Z
print(f"acceptance rate {acceptance:.2f}")
print(f"E[X^2]: MCMC {np.mean(X**2):.4f}, quadrature {exact_x2:.4f}")Choosing the step size¶
Successive states of a Markov chain are correlated, and the step size controls how strongly. Trace plots of chains started far from the wells, at , show the trade-off.
fig, ax = plt.subplots(3, 1, figsize=(10, 6), sharex=True)
for a, delta in zip(ax, [0.05, 1.0, 20.0]):
chain, acceptance = metropolis(V, x0=3.0, delta=delta, nsteps=2000, rng=rng)
a.plot(chain, lw=0.7)
a.set_ylabel('$X_i$')
a.set_title(rf'$\delta = {delta}$, acceptance rate {acceptance:.2f}')
ax[-1].set_xlabel('step $i$')
plt.tight_layout()
plt.show()With a small step, almost every proposal is accepted, but the chain moves like a random walk with tiny steps. It needs many steps just to reach the wells from , and it rarely moves from one well to the other.
With a large step, almost every proposal lands where is tiny and is rejected, so the chain is stuck for long stretches.
A moderate step explores the distribution quickly.
The first part of a chain, before it has forgotten its starting point, doesn’t sample and should be discarded as burn-in.
Exercises¶
Exercise 1¶
The unit ball in dimensions has volume (scipy.special.gamma). Estimate it as times the fraction of uniform points in that land in the ball, for . Report each estimate with an error bar, and plot the relative error against . Why does the relative error grow with , even though the rate doesn’t depend on the dimension?
# Your code here