24.8 Bayesian Computation
Throughout the Basics part of this book, we trained each model to a single parameter vector, either by maximum likelihood or, with a regularizer, by the maximum a posteriori (MAP) estimate at the peak of the posterior. In Section 24.6, we went a step further and placed an error bar on that estimate. Even then, our predictions still came from that single vector, despite the fact that many other parameter vectors explain the training data almost as well. How much do those plausible models disagree, and what should we predict when they do?
Consider a concrete example: logistic regression with an intercept and a slope, fitted to twenty labeled points whose inputs lie between and . At a test input of , well below the training data, the fitted MAP line assigns the label a probability of about four in a thousand. Yet other parameter vectors that fit the twenty points nearly as well disagree there by orders of magnitude. If we average their predictions, weighting each vector by how plausible it is given the data, the resulting probability is almost five times larger. At an input of , right inside the training data, the single-vector and averaged predictions agree to within . For a rare event, such as a fraud alert or a medical diagnosis, a factor of five in the predicted probability can change the decision we make.
That weighted average is the Bayesian prediction, and computing it is a problem as old as Bayes' rule itself. The posterior distribution divides by the evidence, an integral over all parameter vectors that rarely has a closed form. In 1774, Laplace bypassed the integral by replacing the posterior of a proportion with the Gaussian that matches its peak. In 1953, Metropolis and his colleagues showed how to let a random walk visit states in proportion to a distribution whose normalizing constant is unknown (Metropolis et al., 1953). By the 1990s, researchers had also turned the integration problem into an optimization problem. One unifying trick runs through all of these methods: we can average over a distribution known only up to a normalizing constant because every method relies solely on ratios of densities, where the unknown constant cancels.
In this section, we develop four approaches by asking four questions in turn. First, can we approximate the posterior by the Gaussian that matches its peak? Second, can we draw from a simpler distribution and correct each draw? Third, can a random walk spend time in each region in proportion to its posterior mass? Fourth, can we optimize a simple distribution to be as close to the posterior as possible? Each of the first three methods remedies a limitation of the one before it, while the fourth replaces sampling with optimization. A low-dimensional posterior is the cleanest setting for a distribution known only up to a constant, though the same ideas reappear across the book; Section 24.8.5 maps out where each returns. All four methods aim to compute the posterior predictive distribution of a label at a new input ,
which averages the predictions of every parameter vector, weighted by its posterior density given the data .
24.8.1 The Posterior of Bayesian Logistic Regression#
To compare approximation methods fairly, we need a posterior that has no closed form yet can still be checked against the exact answer. Recall that a prior is conjugate to a likelihood when the posterior stays in the same family as the prior, just as a Beta prior on a coin stays Beta after any number of flips (Section 24.4). A Gaussian prior is not conjugate to the logistic likelihood: we can evaluate the unnormalized posterior at any parameter vector, but we cannot integrate it analytically. Because our running example has only two parameters, however, a fine two-dimensional grid still gives an exact reference against which every approximation can be judged.
24.8.1.1 The Model and Its Unnormalized Posterior#
In one-dimensional logistic regression, each binary label has a probability determined by a linear function of the input ,
where . The predicted probability crosses where the linear function crosses zero, at , while the slope controls how sharply the curve rises there. We place independent Gaussian priors on the intercept and slope, with prior standard deviation . By Bayes' rule, the posterior is proportional to the likelihood of the labels times the prior:
The bracketed product is the likelihood and the exponential factor is the prior. The missing normalizing constant is the evidence , an integral over all parameter vectors that has no closed form. We denote the right-hand side by , the unnormalized posterior, so that the normalized posterior is simply .
For our running dataset, we take inputs drawn uniformly from and
generate labels from the true parameter vector ,
whose probability curve crosses at and rises from
at to
at . We set the prior variance to
. With twenty data points, the posterior remains wide enough for
every approximation effect in this section to stand out clearly. Rather than
drawing a fresh dataset on each run, we fix one representative draw of twenty
points (selected as the most typical among 1,500 simulated datasets on the
posterior summaries measured below) so that we can quote concrete reference
numbers. Every sampler we run still uses fresh random numbers, so sampler
results are reported as typical ranges. In code, log_joint evaluates
, using logaddexp(0, z) for to prevent
overflow at large logits.
rng = np.random.default_rng()
n, prior_var = 20, 4.0 # prior_var is tau^2
theta_star = np.array([-3.0, 1.5])
def sigmoid(z):
return np.exp(-np.logaddexp(0.0, -z))
x = np.array([0.1, 0.3, 0.3, 0.4, 0.8, 1.4, 1.5, 1.6, 1.8, 2.1,
2.2, 2.3, 2.6, 2.7, 3.0, 3.1, 3.4, 3.5, 3.6, 3.7])
y = np.array([0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1])
Z = np.column_stack([np.ones(n), x]) # rows z_i = (1, x_i)
def log_joint(theta, Z=Z, y=y, prior_var=prior_var):
"""log p(D, theta) up to a constant; theta has final dimension 2."""
logits = np.einsum('...d,nd->...n', theta, Z)
log_lik = (y * logits - np.logaddexp(0.0, logits)).sum(axis=-1)
return log_lik - 0.5 * (theta**2).sum(axis=-1) / prior_var
print(f'{n} points, {y.sum()} of them labeled 1')
20 points, 10 of them labeled 1
24.8.1.2 The Gradient and the Hessian#
Several methods below rely on the slope and curvature of , so it pays to derive them once up front. Differentiating each log-likelihood term gives , where , while the Gaussian prior contributes . Stacking the input rows into the matrix , we obtain the gradient . Its geometry is transparent: each training point nudges along in proportion to its prediction residual , and the prior gently pulls the parameters back toward the origin. Differentiating a second time yields the negative Hessian
Here the data term is a weighted Gram matrix of the inputs. Because each weight peaks at , the points the model is most uncertain about contribute the most curvature. Adding the prior term lifts every eigenvalue by at least , so is strictly positive definite everywhere. Thus the log posterior is strictly concave and has a unique maximum. Even when the training data are linearly separable, that maximum stays finite, because the log-likelihood is never positive while the quadratic prior penalty drops without bound in every direction.
def grad_log_joint(theta, Z=Z, y=y, prior_var=prior_var):
"""Gradient of log p(D, theta); one row per row of theta."""
theta = np.atleast_2d(theta)
return (y - sigmoid(theta @ Z.T)) @ Z - theta / prior_var
def neg_hessian(theta, Z=Z, y=y, prior_var=prior_var):
"""H(theta) = Z^T diag(p (1 - p)) Z + I / tau^2."""
p = sigmoid(Z @ theta)
return Z.T @ (Z * (p * (1 - p))[:, None]) + np.eye(2) / prior_var
With only two parameters, writing these derivatives by hand is painless. For larger models, we would implement only and let automatic differentiation supply the gradient and Hessian.
Notice that every method in this section accesses the posterior solely through , whether via its values, its gradient, or its Hessian.
24.8.1.3 The Posterior Mode and the Laplace Approximation#
Our first and cheapest approximation builds directly on an optimization we already know how to run. The peak of the posterior is the MAP estimate, the penalized fit from Section 24.6, and Newton's method, , reaches it in just a few iterations. One extra Hessian evaluation then turns that point estimate into a Gaussian distribution.
Specifically, we fit a Gaussian centered at the mode . Expanding to second order around , with , gives
There is no linear term because the gradient vanishes at the mode. Up to an additive constant, the right-hand side is simply the log density of a Gaussian with mean and covariance . Exponentiating therefore gives the Laplace approximation,
For this approximation to be well defined, must be twice differentiable at an interior mode with a positive definite negative Hessian , both of which hold here. Intuitively, a sharp peak has large curvature and therefore produces a narrow Gaussian with small variance. The Gaussian matches the location and local curvature of the posterior's peak, and nothing else.
A one-dimensional example makes the behavior immediately visible. Consider the skewed posterior , whose unnormalized density is for . Its log density, , has derivative , which vanishes at the mode , and negative second derivative there. The Laplace approximation is therefore , with standard deviation . Because the exact posterior has mean and variance , the Gaussian sits too far to the left, is too narrow, and even places of its mass below , where the true density is zero (Figure 24.8.1).
Applying the same calculation to a coin that landed 9 heads and 4 tails under a uniform prior recovers the maximum likelihood estimate and its standard error from Section 24.6.3.2. Under a flat prior, in fact, the Laplace approximation is simply the MLE paired with its asymptotic error bar (Exercise 3).
The Laplace approximation for a skewed one-dimensional posterior, the Gamma(4,1) density with mode 3. Left: the quadratic fit to the log density matches its value, slope, and curvature at the mode and nothing else. Right: after exponentiating, the Laplace Gaussian matches the peak but misses the skew, placing 4.2% of its mass (shaded orange) below the support boundary where the posterior is zero, while underestimating the right tail; the true mean is 4.
Notice that the unknown evidence never enters the calculation: is an additive constant in , so it vanishes upon differentiation. Better still, integrating the exponential of the right-hand side of (24.8.4) even yields an estimate of the evidence itself, in dimensions (Exercise 6).
Because the Laplace approximation uses only local derivatives at a single peak, it is blind to skewness, heavy tails, parameter boundaries, and additional modes, and it centers the distribution at the mode rather than the mean. Scaling is also an issue: for a neural network with parameters, has entries, so practical applications typically keep only its diagonal or restrict the approximation to the last layer.
In code, ten Newton steps starting from the origin locate the mode, and a single matrix inverse yields the Laplace covariance.
theta_map = np.zeros(2)
for _ in range(10): # Newton's method
theta_map += np.linalg.solve(neg_hessian(theta_map),
grad_log_joint(theta_map)[0])
laplace_cov = np.linalg.inv(neg_hessian(theta_map))
laplace_sd = np.sqrt(np.diag(laplace_cov))
laplace_rho = laplace_cov[0, 1] / (laplace_sd[0] * laplace_sd[1])
print('MAP :', theta_map.round(3))
print('Laplace sd :', laplace_sd.round(3))
print('Laplace correlation:', round(laplace_rho, 3))
MAP : [-2.138 1.117]
Laplace sd : [1.004 0.457]
Laplace correlation: -0.861
The posterior mode lies at , a shallower line than the generating parameters . The Laplace standard deviations are for the intercept and for the slope, placing the true values a little less than one standard deviation away in each coordinate. Notice also the strong negative correlation, : a steeper line must start lower to pass through the same cloud of points.
24.8.1.4 A Grid Reference#
To see how accurate the Laplace approximation really is, we need the exact posterior as a benchmark. With only two parameters, we can evaluate on a fine grid, subtract the maximum for numerical stability, exponentiate, and normalize the weights to sum to one. In dimensions, such a lattice requires evaluations, so grid integration is purely a low-dimensional reference. Even in two dimensions we must know where to place the box: we center the grid at and span seven Laplace standard deviations in each direction, leaving only a negligible tail outside.
k, m = 7, 241 # half-width in Laplace sds, points per axis
grid_axes = [np.linspace(c - k * s, c + k * s, m)
for c, s in zip(theta_map, laplace_sd)]
B0, B1 = np.meshgrid(*grid_axes, indexing='ij')
grid_theta = np.stack([B0.ravel(), B1.ravel()], axis=1)
grid_logp = log_joint(grid_theta)
grid_weight = np.exp(grid_logp - grid_logp.max())
grid_weight /= grid_weight.sum()
post_mean = grid_weight @ grid_theta
centered = grid_theta - post_mean
post_cov = (centered * grid_weight[:, None]).T @ centered
post_sd = np.sqrt(np.diag(post_cov))
post_rho = post_cov[0, 1] / (post_sd[0] * post_sd[1])
print('grid mean :', post_mean.round(3), ' MAP:', theta_map.round(3))
print('grid sd :', post_sd.round(3), ' Laplace:', laplace_sd.round(3))
print('grid correlation:', round(post_rho, 3))
print('(mean - MAP)/sd :', ((post_mean - theta_map) / post_sd).round(2))
grid mean : [-2.347 1.237] MAP: [-2.138 1.117]
grid sd : [1.042 0.48 ] Laplace: [1.004 0.457]
grid correlation: -0.858
(mean - MAP)/sd : [-0.2 0.25]
The grid exposes the skewness that Laplace missed. The posterior mean of the slope, , sits a quarter of a posterior standard deviation above the MAP estimate of , while the intercept's mean, , sits a fifth of a standard deviation below its MAP. The Laplace standard deviations are to too narrow, and the correlation agrees to two digits. Those width errors are modest; the more consequential discrepancy is that the posterior is skewed toward steeper lines, so its mean and its mode do not coincide.
24.8.1.5 The Plug-in and the Posterior Predictive#
We can now answer our opening question directly. The plug-in prediction relies on the mode alone, whereas the posterior predictive (24.8.1) averages across the grid using the posterior weights. Let us compare both predictions at three test inputs, , lying below, inside, and above the training data, alongside the interval containing the middle 90% of predictions across plausible parameter vectors.
x_new = np.array([-3.0, 2.0, 7.0])
Z_new = np.column_stack([np.ones(len(x_new)), x_new])
grid_probs = sigmoid(grid_theta @ Z_new.T) # each grid vector's answer
plug_in = sigmoid(Z_new @ theta_map)
predictive = grid_weight @ grid_probs
for j, x0 in enumerate(x_new):
order = np.argsort(grid_probs[:, j])
cdf = np.cumsum(grid_weight[order])
lo, hi = grid_probs[order[np.searchsorted(cdf, [0.05, 0.95])], j]
print(f'x={x0:+.0f}: plug-in {plug_in[j]:.4f}, predictive '
f'{predictive[j]:.4f}, middle 90%: [{lo:.2g}, {hi:.4f}]')
a = grid_theta @ Z_new[0] # logits at x = -3
mu = grid_weight @ a
s2 = grid_weight @ (a - mu)**2
print(f'x=-3, log scale: plug-in {np.log(plug_in[0]):.2f}, '
f'mean logit {mu:.2f}, plus s^2/2 {mu + s2 / 2:.2f},')
print(f' log E[e^a] {np.log(grid_weight @ np.exp(a)):.2f}, '
f'predictive {np.log(predictive[0]):.2f}')
x=-3: plug-in 0.0041, predictive 0.0187, middle 90%: [3.8e-05, 0.0887]
x=+2: plug-in 0.5238, predictive 0.5292, middle 90%: [0.32, 0.7364]
x=+7: plug-in 0.9966, predictive 0.9826, middle 90%: [0.92, 1.0000]
x=-3, log scale: plug-in -5.49, mean logit -6.06, plus s^2/2 -3.19,
log E[e^a] -3.66, predictive -3.98
Inside the training range at , the two predictions ( and ) agree to within , and the plausible parameter vectors span a moderate range from to . Far outside the data at , the middle 90% of plausible predictions stretch across more than three orders of magnitude, from to , and the posterior predictive () is times the plug-in value (). At , the same amplification occurs for the probability of label ( versus ). Because probabilities this close to or are easiest to compare on the log-odds scale , we plot both curves across a wider range with the training inputs marked along the bottom.
def log_odds(p):
return np.log(p) - np.log1p(-p)
xs = np.linspace(-4, 8, 121)
Z_xs = np.column_stack([np.ones_like(xs), xs])
plug_xs = Z_xs @ theta_map # log-odds of the plug-in
pred_xs = log_odds(grid_weight @ sigmoid(grid_theta @ Z_xs.T))
rug = np.full(n, min(plug_xs.min(), pred_xs.min()) - 1)
d2l.plot([xs, xs, x], [plug_xs, pred_xs, rug],
xlabel='x', ylabel='log-odds of y = 1', fmts=('-', 'm--', 'k|'),
legend=['plug-in (MAP)', 'posterior predictive', 'training inputs'],
figsize=(5, 3))On the log-odds scale, the plug-in prediction is simply the straight line . Inside , the posterior predictive hugs that line; outside the training data, it bends back toward zero. Two competing effects create this gap. First, the posterior mean has a steeper slope than the MAP estimate, which pushes extreme predictions away from . Second, averaging the sigmoid over a spread of logits pulls predictions toward : far from the data, plausible parameter vectors with shallower slopes produce much larger probabilities than the typical vector, and those larger probabilities dominate the average.
Which effect wins, and by how much? A quick back-of-the-envelope calculation estimates the size of the averaging effect. Where the probability is small, , so the predictive probability is roughly the posterior average of for the logit . If were Gaussian with mean and variance , its moment generating function would give , raising the log-probability by above the value at the mean logit. At , the grid gives , which would predict a factor of . Yet the actual factor is , a rise of only on the log scale. Where did the missing nats go? The last two lines of the code above walk from the plug-in to the posterior predictive one step at a time:
| step at | log-probability | change |
|---|---|---|
| plug-in: the logit at the mode | ||
| the posterior mean of the logit | ||
| add , as for a Gaussian logit | ||
| average over the logit's actual distribution | ||
| average instead of : the predictive |
Three downward corrections account for the entire difference between and . First, the boost starts from the mean logit rather than the plug-in logit, and the steeper posterior mean sits lower. Second, the logit is skewed rather than Gaussian: it has a long tail toward very negative values and a shorter tail toward zero, where the average of gets almost all of its mass, trimming another . Third, the vectors that dominate the average have probabilities at that are no longer tiny, so the sigmoid bends below and subtracts the final . Altogether, .
The Gaussian calculation is therefore a useful guide rather than an exact law: it gets the direction, the rough scale, and the asymptotic dependence on right. Specifically, the logit variance grows quadratically with distance from the data, whereas the mean shift grows only linearly. Far from the training inputs, the variance term inevitably wins, while inside the data both effects remain negligible (Exercise 4).
Notice that the larger predictive probability is not necessarily closer to the data-generating truth. The true line gives at , which lies below both the plug-in and the posterior predictive because twenty points cannot pin down the slope and the prior shrinks it toward zero. That true probability does fall comfortably inside the 90% posterior interval, as expected for a typical dataset. The posterior predictive does not claim to know the true parameter; rather, it gives the exact probability of averaged over all parameter vectors consistent with the prior and the twenty observations. The rest of this section asks how to compute such averages when the parameter space is too large for a grid.
24.8.2 Rejection and Importance Sampling#
The Laplace approximation is fast, but it centers on the mode and ignores skewness. If we could draw samples directly from the exact posterior, their empirical average would estimate any posterior expectation cleanly, capturing skewness and tails automatically. The two methods in this section turn draws from a tractable proposal distribution into exact or weighted draws from the posterior, relying only on the ratio .
24.8.2.1 Rejection Sampling#
The simplest exact sampler draws candidates from , keeps some, and discards the rest. Choose a proposal that is easy to sample and evaluate, along with a constant such that for every , forming an envelope above the unnormalized posterior. For each draw , we keep it with probability
Geometrically, the acceptance probability is the ratio of the target height to the envelope height at the proposed point. Every accepted draw is an exact sample from , and the overall acceptance rate is . The verification takes two lines: a proposal lands in an infinitesimal region around with probability and is accepted with probability , so the joint probability of landing there and being kept is . Integrating over all yields the marginal acceptance probability , and dividing the joint density by this marginal gives the conditional density of a kept draw, .
Crucially, the unknown evidence appears only in the acceptance rate, never in the accept-or-reject rule itself. If we choose the prior as the proposal , then is simply the likelihood and is its maximum value: we draw parameter vectors from the prior and keep each with probability equal to its likelihood divided by the maximum likelihood.
To see how quickly rejection sampling degrades as data accumulate, consider the coin with 9 heads and 4 tails under a uniform prior. The likelihood peaks at with height , while the evidence is , giving an acceptance rate of . Multiply the data by ten (90 heads and 40 tails) and the acceptance rate falls to ; multiply by a hundred and it drops to . Because the posterior width shrinks like while the prior stays fixed, the acceptance rate decays as in one dimension and as in dimensions. A quick simulation with 100,000 draws from the uniform prior confirms the calculation.
N = 100_000
theta_coin = rng.random(N) # draws from the uniform prior
lik = theta_coin**9 * (1 - theta_coin)**4 # likelihood of 9 heads, 4 tails
M = (9 / 13)**9 * (4 / 13)**4 # its maximum, at theta = 9/13
kept = theta_coin[rng.random(N) < lik / M]
print(f'acceptance {len(kept) / N:.3f}, mean {kept.mean():.3f}, '
f'sd {kept.std():.3f}')acceptance 0.304, mean 0.666, sd 0.118
Two serious obstacles limit rejection sampling in practice. First, we must know a valid upper bound , which is rarely available outside simple models. Second, even with a fixed number of observations per parameter, the acceptance rate decays at least exponentially with the dimension .
24.8.2.2 Importance Weights#
Rejection sampling throws away most of the draws it generates. Rather than using the ratio to flip a coin and discard candidates, we can keep every draw and weight it by . To see why this works, express any posterior expectation as a ratio of two integrals and multiply and divide by inside both:
The denominator equals the unknown evidence , and we never need to compute it explicitly because the same normalizing constant scales both numerator and denominator. Replacing the two expectations with sample averages over draws gives self-normalized importance sampling, . By the law of large numbers, this ratio converges to the exact posterior expectation as , though at finite it carries a small bias because it is a ratio of two random averages. Since products of many likelihood terms quickly underflow in floating point, we always compute log-weights and subtract the largest log-weight before exponentiating, just as in the log-sum-exp trick. When is the prior, the importance weight reduces to the likelihood: every prior draw is weighted by how well it explains the observed data.
24.8.2.3 The Effective Sample Size#
Keeping every draw does not mean every draw helps equally. A weighted sample in which a single draw carries nearly all the weight is effectively worth just one draw, no matter how large is. To quantify this, we define the effective sample size (ESS) from the normalized weights :
When all weights are equal (), ; when one draw takes all the weight, . Roughly speaking, the ESS estimates how many independent draws from the exact posterior the weighted sample is worth. As we will soon see, however, it can still mislead in two important ways.
Proposition. As ,
where is the normalized posterior. For the same proposal , this limiting efficiency is always at least the acceptance rate of rejection sampling.
Proof. Dividing numerator and denominator of (24.8.8) by gives , and the law of large numbers applies to both averages. Substituting yields and , giving the -divergence expression. Finally, since , we have , so the limit is at least .
The ESS is therefore an empirical measure of how closely matches . In the large- limit, importance sampling retains at least as many effective draws as rejection sampling accepts, without ever needing an envelope bound . Returning to the coin with a uniform prior proposal, , which gives a limiting ESS fraction of compared with the rejection acceptance rate of . We can reuse the exact same draws from the rejection cell and simply reweight them instead of discarding two-thirds of them.
w = lik / lik.sum() # normalized weights
post_coin = w @ theta_coin
print(f'ESS fraction {1 / (w @ w) / N:.3f}, mean {post_coin:.3f}, '
f'sd {np.sqrt(w @ (theta_coin - post_coin)**2):.3f}')ESS fraction 0.420, mean 0.666, sd 0.118
The limiting formula also exposes how sharply a poorly scaled proposal can fail. For a one-dimensional Gaussian target with standard deviation and a centered Gaussian proposal with standard deviation , the limiting ESS fraction is (Exercise 5). That curve equals at , peaks at when , and declines gently to at and at . For , however, it collapses abruptly to zero because . A proposal that is too narrow fails far more catastrophically than one that is too wide.
Two conditions guarantee that the importance identity (24.8.7) holds: everywhere , and . For a central limit theorem, and hence error bars, we additionally need and to be finite. Even when those conditions hold, the finite-sample ESS can be dangerously optimistic, as Figure 24.8.2 illustrates.
Importance sampling of a two-mode target using two different proposals; stems show the normalized weights of 24 draws. Left: a narrow proposal never visits the right-hand mode, so its weights look nearly uniform (ESS 23 of 24) even though its estimate is badly wrong. Right: a broader proposal covers both modes; its weights are less uniform (ESS 17 of 24), yet its estimate is far more accurate. The ESS measures weight inequality, not whether the proposal found all of the posterior mass.
24.8.2.4 Proposals for the Logistic Posterior#
How should we choose a proposal for our logistic regression posterior? Let us compare two Gaussians, the prior with 20,000 draws and the Laplace approximation with 5,000 draws, by recording the ESS as a fraction of the draws, the largest normalized weight, and the error in the estimated posterior mean relative to the grid reference, measured in units of posterior standard deviations.
def gaussian_logpdf(samples, mean, cov):
diff = samples - mean
_, logdet = np.linalg.slogdet(cov)
maha = np.einsum('ni,ij,nj->n', diff, np.linalg.inv(cov), diff)
return -0.5 * (len(mean) * np.log(2 * np.pi) + logdet + maha)
def importance(log_target, mean, cov, N):
"""Self-normalized importance sampling from a Gaussian proposal."""
samples = rng.multivariate_normal(mean, cov, N)
log_w = log_target(samples) - gaussian_logpdf(samples, mean, cov)
w = np.exp(log_w - log_w.max())
w /= w.sum()
return w @ samples, 1 / (w @ w), w.max()
for name, mean, cov, N in [('prior', np.zeros(2), prior_var * np.eye(2), 20000),
('Laplace', theta_map, laplace_cov, 5000)]:
estimate, ess, w_max = importance(log_joint, mean, cov, N)
error = np.abs(estimate - post_mean) / post_sd
print(f'{name:8s}: ESS {ess / N:.1%} of {N}, largest weight '
f'{w_max:.4f}, error in sds {error.round(3)}')prior : ESS 4.2% of 20000, largest weight 0.0025, error in sds [0.013 0.001]
Laplace : ESS 85.5% of 5000, largest weight 0.0030, error in sds [0.006 0.003]
Using the prior as the proposal yields an ESS of only about 4% of the draws, because most prior samples land where the likelihood is negligible. Aiming the proposal at the posterior with the Laplace Gaussian raises the ESS dramatically: typically 80% to 90% of the draws are effective, although an occasional run falls far lower. Both proposals usually estimate the posterior mean within a few hundredths of a posterior standard deviation of the grid reference, and rarely err by more than .
Yet the Laplace proposal hides a subtle defect that a typical ESS printout never reveals. Far from the origin, the posterior's tails are governed by the prior: along any ray , the log-likelihood decays at most linearly in (Exercise 8), whereas the log prior decays quadratically as . Consequently, for a Gaussian proposal , the integral diverges whenever any eigenvalue of falls below . Here both eigenvalues of the Laplace covariance (roughly and ) lie well below , so the importance weights have infinite variance in every direction, not just along a single thin axis.
Why did our 5,000-draw run look so healthy? Because the region where the weights blow up sits many Laplace standard deviations away, so most runs of 5,000 draws never stumble into it. In a few runs out of a hundred, however, a single distant draw captures a huge share of the total weight and the ESS plummets. A single run cannot expose this instability; only repeated runs or a tail analysis can. Two simple fixes restore finite weight variance: replacing the Gaussian with a heavier-tailed Student- proposal (Exercise 8), or using a defensive mixture such as . Because the mixture density is always at least one-tenth of the prior density, every weight is bounded above by ten times the likelihood, which never exceeds .
Importance sampling cancels the unknown evidence automatically, but it still demands a single global proposal that covers the entire posterior. In high dimensions, no simple global distribution can do that.
24.8.3 Markov Chain Monte Carlo#
Rather than searching for one global proposal that blankets the whole posterior, we can explore the parameter space through local moves, designing a random walk that spends time in each region in proportion to its posterior mass. Such a walk is a Markov chain: its next state depends only on its current state through a transition rule , the probability of moving from to . A distribution is stationary for the chain if drawing the current state from leaves the next state distributed as as well:
where the sum becomes an integral for continuous parameters. Our goal is to construct a simple transition rule whose stationary distribution is the posterior.
24.8.3.1 The Metropolis Rule#
The Metropolis algorithm builds such a chain from any symmetric proposal , such as a local Gaussian step . From the current state , we propose a candidate . If the candidate has higher or equal posterior density, , we always move to . If it moves downhill, we accept it with probability and otherwise remain at . Crucially, a rejected proposal repeats the current state, and that repeat counts as the next state in the chain (Figure 24.8.3).
A Metropolis random walk on posterior contours. From the starting square, each step proposes a local move: uphill moves are always accepted (path), downhill moves are accepted probabilistically, and rejected proposals (crosses) leave the chain in place for another step. In the long run, the fraction of time spent in any region matches its posterior mass.
Hastings (Hastings, 1970) generalized the rule to asymmetric proposals by multiplying the density ratio by a correction factor, , that compensates for any directional bias in the proposal. A candidate is then accepted with probability
Moves toward states that the proposal rarely visits are accepted more readily, and when is symmetric the correction factor equals . Once again, the unknown evidence cancels in the ratio of values.
The smallest possible chain illustrates why counting rejections is essential. Consider two states with target distribution , and a symmetric proposal that always suggests the other state. From state , the target ratio is , so the chain always jumps to state . From state , the ratio is , so it jumps to state with probability and stays at state with probability . Writing the transition matrix with rows for the current state, we can check stationarity directly:
If we discarded rejections and recorded only accepted moves, the sequence would simply alternate , yielding instead of . It is precisely the repeated visits to state after rejections that give state its proper weight (Figure 24.8.4).
The two-state Metropolis chain with target . The probability flow from state 1 to state 2 is and the return flow is ; both equal , so the occupation is preserved at every step. The self-loop represents rejected moves from state 2; recording only accepted moves would give .
24.8.3.2 Detailed Balance and Stationarity#
Figure 24.8.4 captures the core mechanism behind Metropolis–Hastings: in one step, the probability mass flowing from state to state equals the probability mass flowing back, so neither state gains nor loses probability. When this pairwise equilibrium holds for every pair of states, the target distribution is guaranteed to be stationary. If you remember one theoretical result from this section, make it this one.
Proposition. If a transition rule satisfies detailed balance,
then is stationary for the chain. Moreover, the Metropolis–Hastings chain satisfies detailed balance with .
Proof. Summing both sides of (24.8.12) over yields the left-hand side of (24.8.10), while the right-hand side simplifies to because the transition probabilities from sum to . For the second claim, detailed balance is automatic when . When , a move occurs if and only if is proposed and accepted, so
which is visibly symmetric in and . Because the normalizing constant of cancels inside , we can substitute for .
The key algebraic step is pulling inside the minimum, which reveals the symmetry at a glance. On a continuous state space, the point mass of rejected moves requires slightly more care (Exercise 1).
Stationarity alone does not guarantee that a chain converges to from an arbitrary starting point. The chain must also be able to reach every region of positive posterior mass, and it must not cycle deterministically between regions. Under these two mild conditions, the long-run fraction of time the chain spends in any region converges to its posterior probability.
Implementing Metropolis takes only a few lines. Below we shape the Gaussian proposal using the Cholesky factor of the Laplace covariance, .
def metropolis(log_target, start, proposal_chol, n_steps):
current = np.array(start, dtype=float)
current_logp = log_target(current)
states, accepted = np.empty((n_steps, len(current))), 0
for t in range(n_steps):
proposal = current + proposal_chol @ rng.standard_normal(len(current))
proposal_logp = log_target(proposal)
if np.log(rng.random()) < proposal_logp - current_logp: # accept
current, current_logp = proposal, proposal_logp
accepted += 1
states[t] = current # a rejection repeats the state
return states, accepted / n_steps
We launch four independent chains of 12,000 steps each from over-dispersed starting points scattered twice as widely as the Laplace Gaussian, , proposing steps of size . Because early states still remember where each chain began, we discard the first 2,000 iterations of each chain, the warm-up period, before computing averages.
def run_chains(scale, n_chains=4, n_steps=12000, warmup=2000):
L = np.linalg.cholesky(laplace_cov)
chains, rates = [], []
for _ in range(n_chains):
start = theta_map + 2 * L @ rng.standard_normal(2) # over-dispersed
states, rate = metropolis(log_joint, start, scale * L, n_steps)
chains.append(states[warmup:])
rates.append(rate)
return np.array(chains), np.array(rates)
chains, rates = run_chains(1.1)
print('acceptance rates:', rates.round(3))acceptance rates: [0.523 0.529 0.533 0.526]
Roughly half of all proposals are accepted across every chain. Remember that the Metropolis acceptance rule, not the Gaussian proposal, determines the stationary distribution, so a badly shaped proposal would slow the chain down without introducing bias.
24.8.3.3 Diagnostics for Markov Chain Mixing#
Unlike independent samples, consecutive states in a Markov chain are correlated, and every chain begins wherever we initialize it. Before trusting any average computed from a chain, we ask three diagnostic questions and answer each with a concrete metric.
Have the chains forgotten their starting points and converged to the same distribution? Visually, a trace plot of each chain exposes sticking or drift, while quantifies disagreement across chains. Given multiple chains of states each, let denote the average within-chain variance and denote times the variance of the chain means. Then
The numerator estimates the total posterior variance and tends to overestimate it while the chains remain separated, whereas underestimates it while each chain has explored only a piece of the posterior. Thus compares two variance estimates and approaches as the chains mix together. In practice, we compute split by splitting every chain into two halves first, so that even a single drifting chain registers as two disagreeing chains. Staying within of is necessary before trusting the output, though never sufficient on its own: chains that all miss the same distant mode will happily agree with one another.
How many independent draws are these correlated states actually worth? Let be the autocorrelation between states steps apart. The integrated autocorrelation time counts how many chain steps carry the same information as a single independent draw. Consequently, chains of states each yield an effective sample size of , carrying the same meaning and symbol as in importance sampling.
The simplest model of serial correlation is the first-order autoregressive process, AR(1), given by with independent noise and : at each step the chain retains a fraction of its previous value. Its lag- autocorrelation is , which gives
At , we get , meaning 10,000 states are worth only about 530 independent draws; at , , leaving barely 50 independent draws.
Because estimated autocorrelations at very large lags are dominated by noise, our implementation groups them into consecutive pairs and truncates the sum at the first negative pair. Production inference packages refine both diagnostics further, using rank-normalized and separate effective sample sizes for the bulk and tails of the distribution.
How accurate is our estimated posterior mean? By the Markov chain central limit theorem, the Monte Carlo standard error (MCSE) of an estimated posterior mean is the posterior standard deviation divided by .
def split_rhat(chains):
"""Split R-hat per coordinate; chains has shape (c, N, d)."""
half = chains.shape[1] // 2
halves = np.concatenate([chains[:, :half], chains[:, half:2 * half]])
W = halves.var(axis=1, ddof=1).mean(axis=0)
B = half * halves.mean(axis=1).var(axis=0, ddof=1)
return np.sqrt(((half - 1) / half * W + B / half) / W)
def autocorrelation(x):
"""rho_k of one sequence for k = 0, ..., N - 1, by FFT."""
x = x - x.mean()
f = np.fft.rfft(x, n=2 * len(x))
acov = np.fft.irfft(f * np.conj(f))[:len(x)]
return acov / acov[0]
def chain_ess(chains):
"""c N / kappa per coordinate, summing rho in pairs (Geyer)."""
c, N, d = chains.shape
ess = np.empty(d)
for j in range(d):
rho = np.mean([autocorrelation(chain[:, j]) for chain in chains],
axis=0)
pairs = rho[:N - 1:2] + rho[1:N:2] # rho_2k + rho_2k+1
negative = np.flatnonzero(pairs < 0)
n_pairs = negative[0] if len(negative) else len(pairs)
ess[j] = c * N / (-1 + 2 * pairs[:n_pairs].sum())
return ess
Let us put these diagnostics to the test. If our error bar is calibrated, the MCMC mean from our four chains should sit within roughly one MCSE of the exact grid mean. We also check how closely the measured autocorrelation time of the slope matches the AR(1) formula evaluated at the lag-1 autocorrelation .
flat = chains.reshape(-1, 2)
ess = chain_ess(chains)
mcmc_mean, mcmc_sd = flat.mean(axis=0), flat.std(axis=0, ddof=1)
mcse = mcmc_sd / np.sqrt(ess)
rho1 = np.mean([autocorrelation(chain[:, 1])[1] for chain in chains])
print('split R-hat :', split_rhat(chains).round(3))
print('ESS :', ess.round().astype(int), 'of', len(flat))
print('(MCMC - grid)/MCSE:', ((mcmc_mean - post_mean) / mcse).round(1))
print(f'slope: rho_1 {rho1:.2f}, AR(1) kappa {(1 + rho1) / (1 - rho1):.1f},'
f' measured kappa {len(flat) / ess[1]:.1f}')split R-hat : [1.001 1.001]
ESS : [3798 3697] of 40000
(MCMC - grid)/MCSE: [ 0.6 -0.4]
slope: rho_1 0.81, AR(1) kappa 9.4, measured kappa 10.8
A trace plot of the first 600 post-warm-up iterations for the slope rounds out our diagnostic checks.
d2l.plot(np.arange(600), [chain[:600, 1] for chain in chains],
xlabel='iteration', ylabel='slope', figsize=(6, 2.5))The diagnostics look clean: split sits within of , and the four trace plots interleave closely. The ESS is roughly one-tenth of the 40,000 kept states, giving , right in line with the AR(1) prediction from the lag-1 autocorrelation . Most reassuringly, the MCMC mean differs from the exact grid mean by roughly one MCSE, verifying that our uncertainty estimate actually matches the true estimation error.
24.8.3.4 Proposal Scale and Mixing Failures#
The acceptance rate is the easiest number to print from a Metropolis run, yet by itself it tells us very little. Let us rerun the four chains with the proposal scale set to and to instead of . Before looking at the numbers, pause and guess which of the two extremes produces fewer effective draws.
for scale in [0.05, 10]:
bad_chains, bad_rates = run_chains(scale)
print(f'scale {scale:5}: acceptance {bad_rates.mean():.3f}, max R-hat '
f'{split_rhat(bad_chains).max():.2f}, '
f'min ESS {chain_ess(bad_chains).min():.0f}')scale 0.05: acceptance 0.975, max R-hat 1.13, min ESS 43
scale 10: acceptance 0.020, max R-hat 1.00, min ESS 689
With tiny steps (scale ), roughly 97% of proposals are accepted, yet rises well above and 40,000 iterations yield only a few dozen effective draws because each step barely moves. With huge steps (scale ), only about 2% of proposals are accepted and the chain gets stuck repeating states for long stretches, though it still achieves a few hundred effective draws. The optimal step size lies comfortably between these two extremes (Exercise 2). More fundamentally, a blind random walk moves uphill only by luck, whereas a proposal guided by the gradient of drifts uphill by design. Such gradient-informed moves arise from Langevin dynamics (Section 26.6.2), and their Metropolis-adjusted version is developed in Exercise 9.
24.8.4 Variational Inference#
Sampling methods estimate each posterior expectation anew and always carry Monte Carlo noise. Variational inference takes a fundamentally different route, turning integration into optimization. We choose a tractable family of distributions indexed by variational parameters , optimize so that approximates the posterior as closely as possible, and then compute expectations under either in closed form or by fast independent sampling.
24.8.4.1 The Evidence Lower Bound#
To optimize , we need an objective that measures closeness to the posterior without requiring the unknown normalizing constant . Fortunately, we already derived such an objective in Section 24.7, where an approximating distribution over a latent variable gave a lower bound on the log evidence whose gap was a KL divergence. Treating the parameter vector as the latent variable and the dataset as the observation yields the exact same identity:
Since the KL divergence is always non-negative, is the evidence lower bound (ELBO) of ,
Because the two terms on the right-hand side of (24.8.14) sum to the fixed constant , every unit increase in decreases by exactly one unit. Maximizing the ELBO over is therefore equivalent to minimizing the KL divergence, with the unknown evidence dropping out as an additive constant. Every term inside the expectation can be evaluated pointwise, and the expectation itself can be estimated easily using draws from .
24.8.4.2 The Direction of the KL Divergence#
Notice the order of arguments in (24.8.14): variational inference minimizes , the reverse KL divergence, with in the first slot. Because its integrand blows up wherever while , reverse KL penalizes heavily for placing mass where the posterior has none. As a result, shrinks away from low-density regions and tends to lock onto a single mode: reverse KL is mode-seeking. By contrast, the forward divergence penalizes regions where and , forcing to stretch across all of the posterior's mass: forward KL is mass-covering. For a Gaussian family, minimizing forward KL simply matches the posterior's exact mean and covariance, but computing it requires expectations under the intractable posterior , whereas reverse KL needs only expectations under . Figure 24.8.5 contrasts the two behaviors on a bimodal target.
The direction of the KL divergence determines how an overly simple approximation fails. On a two-mode target, the reverse-KL Gaussian found by variational inference locks onto a single mode and underestimates uncertainty, whereas the forward-KL Gaussian covers both modes and places its peak in the low-density valley between them.
24.8.4.3 A Mean-Field Gaussian Fit#
The simplest variational family is the mean-field Gaussian , which models the parameters as independent. To compute gradients of the ELBO with respect to and , we reparameterize a draw as with . Because the noise distribution does not depend on the variational parameters, we can move the gradient inside the expectation (Section 22.7.3). The entropy equals up to an additive constant, giving the unbiased gradient formulas
where comes from differentiating the entropy with respect to . The first gradient shifts the mean uphill on average; the second expands until the entropy's outward push balances the posterior's downward curvature. Before running the optimizer on our logistic posterior, we can predict what will happen by solving the Gaussian target case exactly.
Proposition. For a Gaussian target with precision matrix , the mean-field Gaussian minimizing has mean and variances , the conditional variances of the target. In two dimensions with correlation , each is times the true marginal standard deviation.
Proof. Dropping constants independent of , . Because the coordinates are independent under with means and variances , all cross terms in the fluctuations vanish in expectation, leaving . Since is positive definite, the quadratic in is minimized at . Setting the derivative with respect to to zero, , gives . For , inverting the covariance matrix yields , where is the marginal standard deviation.
A diagonal Gaussian cannot rotate its axes to align with a correlated posterior, and under reverse KL it pays a steep penalty for spilling into low-density corners. It therefore contracts to the width of a conditional slice through the posterior rather than the full marginal width (Figure 24.8.6). Notice that this contraction is specifically a consequence of combining a factorized family with reverse KL: a full-covariance Gaussian fitted by the exact same ELBO objective to a Gaussian target recovers it without error. In our logistic regression example, , so the proposition predicts that mean-field standard deviations will be roughly times the true marginal standard deviations, about half as wide.
Diagonal Gaussians fitted to a correlated Gaussian posterior with standard deviations and correlation , shown as 2-sd ellipses. Because a factorized family cannot tilt, reverse KL (orange) contracts to the conditional width, times the marginal standard deviation, whereas forward KL (green) preserves the marginal width while spilling into low-density regions.
Let us check this prediction numerically. We initialize at the Laplace approximation and run 3,000 iterations of stochastic gradient ascent using (24.8.16), with 256 reparameterized draws per step and a learning rate decaying as . Averaging the final 1,000 iterates smooths out optimization noise, letting us compare the fitted standard deviations directly against the proposition's prediction using the grid correlation .
m_vi, log_s_vi = theta_map.copy(), np.log(laplace_sd)
m_avg, log_s_avg = np.zeros(2), np.zeros(2)
n_steps, n_avg = 3000, 1000
for t in range(1, n_steps + 1):
eps = rng.standard_normal((256, 2))
s_vi = np.exp(log_s_vi)
g = grad_log_joint(m_vi + s_vi * eps) # at theta = m + s * eps
lr = 0.05 / np.sqrt(t)
m_vi += lr * g.mean(axis=0)
log_s_vi += lr * ((g * eps * s_vi).mean(axis=0) + 1)
if t > n_steps - n_avg: # average the last iterates
m_avg += m_vi / n_avg
log_s_avg += log_s_vi / n_avg
s_avg = np.exp(log_s_avg)
print(' mean sd')
print('grid ', post_mean.round(3), post_sd.round(3))
print('Laplace ', theta_map.round(3), laplace_sd.round(3))
print('mean-field', m_avg.round(3), s_avg.round(3))
print('predicted sd, grid sd * sqrt(1 - rho^2):',
(post_sd * np.sqrt(1 - post_rho**2)).round(3)) mean sd
grid [-2.347 1.237] [1.042 0.48 ]
Laplace [-2.138 1.117] [1.004 0.457]
mean-field [-2.276 1.218] [0.533 0.244]
predicted sd, grid sd * sqrt(1 - rho^2): [0.536 0.247]
The mean-field mean lands within roughly a tenth of a posterior standard deviation of the grid mean, while its standard deviations shrink to about half the true widths, matching our analytical predictions ( and ) to within . The optimizer has converged cleanly, so the remaining discrepancy comes entirely from the restrictive variational family. Richer families, such as full-covariance Gaussians, mixtures, or normalizing flows, close that gap at higher computational cost. Keep in mind that a converged ELBO only confirms that optimization has finished within the chosen family; by itself, it never certifies that the family actually fits the posterior.
24.8.5 Comparison of the Methods#
We now have four distinct approximations to the exact same posterior. A single plot brings them side by side on the marginal density of the slope : the exact grid curve, the Laplace and mean-field Gaussians, and a histogram of the Metropolis samples.
def gauss_pdf(t, mean, sd):
return np.exp(-0.5 * ((t - mean) / sd)**2) / (sd * np.sqrt(2 * np.pi))
b1 = grid_axes[1]
exact = grid_weight.reshape(m, m).sum(axis=0) / (b1[1] - b1[0])
hist, edges = np.histogram(flat[:, 1], bins=60, density=True)
d2l.plot([b1, b1, b1, (edges[:-1] + edges[1:]) / 2],
[exact, gauss_pdf(b1, theta_map[1], laplace_sd[1]),
gauss_pdf(b1, m_avg[1], s_avg[1]), hist],
xlabel='slope', ylabel='density', figsize=(5, 3),
xlim=(post_mean[1] - 4 * post_sd[1], post_mean[1] + 4 * post_sd[1]),
legend=['grid (exact)', 'Laplace', 'mean-field', 'Metropolis'])The Metropolis histogram tracks the exact posterior faithfully, skewness and all. The Laplace curve sits centered at the mode to the left of the true mean and is slightly too narrow. The mean-field Gaussian is roughly half as wide as the exact marginal, and by construction it reports a correlation of zero against the true .
| Method | Representation | Main diagnostic | Characteristic failure |
|---|---|---|---|
| Grid | weighted points on a lattice | mass at the edge of the grid | cost in dimension |
| Laplace | one Gaussian at the mode | comparison with samples | skew, tails, boundaries, other modes |
| Rejection sampling | independent exact draws | acceptance rate | rate falls like ; needs a bound |
| Importance sampling | independent weighted draws | weight ESS, largest weight, reruns | light-tailed or misplaced proposal |
| MCMC | correlated posterior draws | traces, split , ESS, MCSE | slow mixing, unvisited modes |
| Variational inference | optimized member of a family | comparison with samples | family too narrow; factorized too confident |
Which method should you reach for in practice? With only a handful of parameters, use a grid. For a smooth, unimodal posterior, the Laplace approximation gives a fast first answer and a strong starting proposal. When an expectation requires a trustworthy error bar, turn to MCMC paired with its three diagnostics. Variational inference shines when posterior approximation must sit inside a larger optimization loop, provided you remember that factorized families underestimate uncertainty. Because neither Gaussian approximation provides a self-contained accuracy check, both should be validated against a sampler whenever feasible.
It is worth being candid about scale: none of these four methods scales cleanly to the full parameter posterior of a large neural network. Importance weights collapse as dimension grows, random-walk MCMC needs progressively more steps per independent draw, the full Hessian has entries, and mean-field understates uncertainty by the correlation factor we just derived. Worse still, a neural network's architectural symmetries duplicate every posterior mode for every permutation and sign flip of its hidden units (Exercise 7).
For large networks, the most widely used answer to the question that opened this section is simpler than any of the four methods. We train the same network several times from different random initializations and average the predicted probabilities. Such a deep ensemble (Lakshminarayanan et al., 2017) is a crude Monte Carlo estimate of the posterior predictive (24.8.1), in which a handful of independently trained networks stand in for posterior draws. Each run settles in a different mode, so the average spans several modes, which a single Laplace or mean-field fit cannot do. Where the members disagree, typically far from the training data, the averaged prediction becomes less confident. The members are not posterior samples, however, and nothing guarantees that they should be weighted equally. Their errors are also correlated, so adding members helps only up to a point: with pairwise correlation , the variance of the average never falls below the fraction of a single member's variance (Exercise 2 in Section 24.2).
The core ideas of this section nevertheless reappear throughout deep learning wherever a distribution is known only up to a normalizing constant. The evidence lower bound trains variational autoencoders (Kingma and Welling, 2014) (Section 17.7), where an encoder network outputs , as well as discrete diffusion models (Section 17.9). Importance weights and effective sample size allow policy-gradient methods to reuse past trajectories (Section 15.2). And gradient-guided proposals, stripped of their accept–reject step, become the Langevin samplers powering score-based generative models (Section 17.1). Finally, every sampling method returns an empirical average over finitely many draws; the next section asks how tightly such finite-sample averages concentrate around their expectations when the draws are independent.
24.8.6 Summary#
Training a model to a single parameter vector treats that point estimate as if it were known with certainty. Far from the training data, plausible parameter vectors can disagree by orders of magnitude, and averaging over them in the posterior predictive can shift rare-event probabilities by a factor of several. Computing that average requires integrating against a posterior known only up to its normalizing constant. All four methods in this section sidestep the unknown constant by working only with ratios or differences where it cancels: local curvature at the mode (Laplace), density ratios (rejection and importance sampling), acceptance ratios (Metropolis–Hastings), and an optimization objective that differs from reverse KL divergence by a constant (variational inference). The samplers bring built-in diagnostics (weight ESS for importance sampling, and split , autocorrelation time , and MCSE for MCMC), while Gaussian approximations must be checked against samples. Although full Bayesian inference remains intractable for large neural networks, the evidence lower bound, importance weights, and Langevin dynamics return across the book whenever we work with unnormalized distributions.
24.8.7 Exercises#
-
Metropolis–Hastings acceptance. The acceptance probability (24.8.11) turns any proposal into a chain that targets the posterior.
- On a continuous state space the transition kernel has a density part and an atom at the current state of mass , the probability of a rejection. Show that the posterior is stationary, accounting for the atom. Hint: the atom contributes to the density at after one step.
- An independence sampler proposes regardless of the current state. Show that its acceptance probability is with the importance weight of (24.8.7). What does the chain do after it reaches a state whose weight is far larger than the weights of typical proposals?
- Barker's rule accepts a symmetric proposal with probability . Show that it satisfies detailed balance. Write its transition matrix for the two-state chain of the text, and show that the Metropolis chain moves more often from both states. For a two-state chain the autocorrelation of any function of the state is , where is the second eigenvalue of the transition matrix. Compute and for both rules. Which gives the smaller Monte Carlo error for the same number of steps? Hint: Barker gives the off-diagonal entries and , against Metropolis' and .
-
[code] Proposal scale. The function
run_chainsmultiplies the Cholesky factor oflaplace_covby a scale, in the text.- Sweep the scale over , keeping the
12,000 steps per chain and the warm-up. For each value, record the
acceptance rate, the split , and the smallest ESS of
chain_essdivided by the log-joint evaluations of the four chains. Plot the ESS per evaluation against the acceptance rate. Over which range of acceptance rates does the ESS per evaluation stay within a factor of two of its maximum? - For a -dimensional standard Gaussian target and the proposal , Roberts et al. (1997) show that as the efficiency is largest at , where the acceptance rate is about . The logistic posterior is close to its Laplace approximation, so the Cholesky factor makes it roughly standard. Which scale does this result suggest for ? How do the best scale of your sweep and its acceptance rate compare?
- Which of the diagnostics of the text flag the run with scale ? Is the acceptance rate one of them? How far is that run's posterior mean from the grid mean, in units of its own MCSE?
- Sweep the scale over , keeping the
12,000 steps per chain and the warm-up. For each value, record the
acceptance rate, the split , and the smallest ESS of
-
Laplace and parameterization. A coin shows 9 heads and 4 tails. Under a uniform prior, the posterior of its heads probability is , with mean , standard deviation , and central interval .
- The Laplace approximation (24.8.5) in the parameter has mean and standard deviation , as computed in the text. Give its central interval and the probability it places outside .
- In the log-odds the posterior density is proportional to , because the Jacobian adds one count to each side. Show that its mode is , compute the curvature of the log density there, and map the central interval of the Laplace approximation back to .
- Which of the two approximations is closer to the exact posterior? Why does the Laplace approximation depend on the parameterization, whereas the exact posterior probability of an event such as does not?
-
[code] Moderated predictions. ● Under the Laplace approximation (24.8.5), the logit at a test input with is Gaussian with mean and variance . The probit approximation with , where is the standard normal c.d.f., turns the predictive integral (24.8.1) into a closed form (MacKay, 1992).
- Show that for . Hint: write as for an independent standard normal . Conclude that the moderated prediction lies between and .
- Compute the moderated predictions at from
theta_mapandlaplace_cov, and compare them with the plug-in and posterior predictive values that your run prints. - Compute three quantities at the same inputs: the plug-in , the prediction at the posterior mean , and the posterior predictive . Which of the two steps, from mode to mean and from mean to average, moves the prediction away from , and which toward it? Why are both steps small at but not at or ? What does this imply for using the Laplace approximation to moderate overconfident predictions?
-
[code] Predicting the weight ESS. ● By the proposition of the text, approaches as the number of draws grows.
- Let the normalized target be and the proposal in one dimension, and let . Show that for
and that the ratio is infinite for . Which minimizes the ratio when ?
- Approximate the posterior by independent Gaussians with the grid means
and standard deviations, ignoring the correlation, so that the ratio
factorizes over the coordinates. Predict the ESS of the 20,000
prior-proposal draws and compare it with the printed value. Repeat for
the prior proposals with and : set
prior_varin the model cell, rerun the cells through the importance cell, and compare prediction and measurement. Which factor of the formula makes a narrow prior a poor proposal, and which makes a broad prior a poor one? - Under the same approximation, for which coordinates of your run does the proposal have infinite weight variance? Run it ten times with 5,000 draws and record the ESS, the largest normalized weight, and the estimated posterior mean. Why does a run whose estimate looks plausible not show that the proposal is adequate?
- Rejection sampling from the prior keeps a draw with probability , where is the likelihood and its value at the maximum-likelihood estimate (for separable data, its supremum 1). Measure the acceptance rate on your data and on data with ten times as many points. Explain the decay with from the volume of the posterior, and compare the rate with the ESS fraction of importance sampling from the same prior.
-
[code] Estimating the evidence. ● Let be a normalized proposal, let , and let for independent draws .
- Show that is an unbiased estimate of and that . Show that is the ELBO (24.8.15) of and that does not decrease with (Burda et al., 2016).
- The function
log_jointomits the normalizing constant of the two-dimensional prior. Add it, and compute in three ways: by summing the density over the grid and multiplying by the area of a grid cell, by with 5,000 Laplace-proposal draws, and by the Laplace evidence . The Laplace estimate of comes out a few percent low, about in . Which feature of the posterior, seen in the grid cell, explains the sign? - Estimate the ELBO of the Laplace approximation and the mean-field fit using draws from each and report the MCSE of each estimate. By (24.8.14), the gap between and the ELBO of is . Compare the two Gaussians by this divergence.
-
[code] A posterior with two modes. ● Fifty observations are drawn as with the true value , and has the prior . The likelihood depends on only through , just as the loss of a neural network does not change when the incoming weights, the bias, and the outgoing weights of a hidden unit flip sign together. The posterior is therefore symmetric under .
- Compute the posterior on a one-dimensional grid. Report , , and the ratio of the posterior density at to its value at a mode.
- Show that the Gaussian that minimizes the forward divergence matches the mean and the variance of . Where does this Gaussian put its mode for the present posterior, and how plausible is that point under ?
- Fit three local approximations: the Laplace approximation at the positive mode, a one-dimensional Gaussian fitted by the ELBO ascent of the variational cell started at , and four Metropolis chains with proposal standard deviation started at . Then rerun the chains from . Which methods report a single mode? For each run, which of its diagnostics (split and the ESS for the chains, the ELBO for the variational fit) reveal the problem?
- Which posterior expectations does a single-mode approximation still estimate correctly? A network with hidden units has the sign flip of this problem for every unit and, in addition, the permutations of its hidden units (Exercise 6). How many equivalent copies of a mode does its posterior have under an isotropic Gaussian prior? What does this suggest about approximating the posterior of a neural network by one of the methods of this section?
-
[code] Tails of the logistic posterior. ●● A central limit theorem for importance sampling needs a finite second moment of the weights. The Laplace proposal of the importance cell usually reaches a high ESS. Throughout,
prior_varis the prior variance in the posterior (24.8.2).- Fix a unit vector and let . Show that the log-likelihood in (24.8.2) equals as , where is the sum of over the observations with and or with and . For which datasets is for every ?
- Conclude that a Gaussian proposal has when some eigenvalue of is smaller than , and when every eigenvalue of exceeds . Which of the two proposals of the importance cell has weights with finite variance? Compare this answer with the one that the formula of Exercise 5a gives for the Laplace proposal when the posterior is approximated by a Gaussian.
- Along each eigenvector of
laplace_cov, in both directions, find the Mahalanobis distance from beyond which exceeds its value at . How likely is a single Laplace-proposal draw to land that far out? Reconcile your answer with the ESS that your run prints. - Geweke (1989) builds importance densities from multivariate
Student- approximations at the posterior mode. Use a Student-
proposal with degrees of freedom, location
, and scale matrix
laplace_cov, and show that its weights have finite variance. Compare it with the Laplace proposal over 20 runs on the ESS and on the estimate of the tail probability , where and are the grid mean and standard deviation of the slope; for a reference value, evaluate the posterior on a grid twice as wide. Also try the defensive mixture of the text, and explain why its weights are bounded.
-
[code] Langevin proposals. ●● The Metropolis-adjusted Langevin algorithm proposes with and a preconditioner ; take to be the Laplace covariance and its Cholesky factor.
- Write down the proposal density and the Hastings factor of the acceptance rule (24.8.11). Why is the proposal not symmetric?
- Implement the sampler with
grad_log_jointand run four chains for . Report the acceptance rate, the split , and the ESS per gradient evaluation, and compare with the random walk's ESS per log-joint evaluation. - Without the accept step the chain is the unadjusted Langevin algorithm. Run it at and compare its mean and standard deviations with the grid. Which of the two errors, the bias of the discretization or the Monte Carlo error, does the Metropolis step remove?