Chapter 10
Nonconjugate Priors and Metropolis–Hastings
The Gibbs sampler needs every full conditional to be a distribution we can sample. Change the sampling model from normal to Poisson, or let a correlation parameter enter a covariance matrix, and that requirement fails. The Metropolis–Hastings algorithm asks for far less: the ability to evaluate the posterior density up to a constant.Nicholas Metropolis, Arianna W. Rosenbluth, Marshall N. Rosenbluth, Augusta H. Teller, and Edward Teller. Equation of State Calculations by Fast Computing Machines. Journal of Chemical Physics, 21(6):1087–1092, 1953; and W. Keith Hastings. Monte Carlo Sampling Methods Using Markov Chains and Their Applications. Biometrika, 57:97–109, 1970 This chapter derives it from a counting argument, proves that it works, and shows that the Gibbs sampler of Chapter 6 was a special case all along.
10.1Generalized Linear Models and the Loss of Conjugacy#
Hoff’s motivating data are the number of offspring and the age of 52 female song sparrows. Two-year-olds do best, and success declines afterwards, so we want a quadratic in age. But a quadratic for the mean itself may go negative. Modeling the logarithm of the mean avoids this and gives Poisson regression:
(10.1)A generalized linear model connects a linear predictor to through a link function: the log link for counts, and for binary data the logit link , that is, logistic regression. With a prior , the log-posterior for (10.1) is
(10.2)The exponential term is not quadratic, so no normal prior yields a normal posterior. The situation is nevertheless benign.
Proposition 10.1 (Log-Concavity of GLM Posteriors). Under a normal prior with , the Poisson (log-link) and logistic (logit-link) posteriors are strictly log-concave in , hence unimodal.
Proof. Differentiating twice, the Hessian of the log-posterior is , with for Poisson and for logistic regression. All weights are positive, so the first term is negative semidefinite and the second negative definite. □
A grid would succeed here, but barely: with 100 points per coordinate, three coefficients need evaluations and five need . Moreover, because and are strongly negatively correlated, nearly all of those points carry no probability.
10.2The Metropolis Algorithm#
Suppose we wish to build a collection of values whose relative frequencies match the posterior, so that for any two values we have . Standing at , consider adding a nearby candidate . The comparison we need,
(10.3)does not involve the intractable constant . If , the candidate deserves at least as many copies as the current value: accept it. If , it deserves only a fraction of a copy: accept it with probability , and otherwise record the current value again. The repeats are not waste. They are how the chain assigns weight.
Algorithm 10.2 (Metropolis Algorithm). Let be a symmetric proposal, , for example or . Given :
Sample .
Compute
Sample . Set if , and otherwise.
Working on the log scale in step 2 is not a nicety: products of hundreds of densities underflow to zero, and the ratio is meaningless. The output is a Markov chain, so the advice of Chapter 6 carries over. Discard an initial burn-in while the chain travels to the high-probability region, and measure the remainder by its effective sample size.
10.2.1Tuning the Proposal#
Unlike Gibbs, Metropolis has a knob. Hoff’s test case has a known answer: observations with and prior , so that . Starting deliberately far away at , he runs normal proposals with various and reports lag-1 autocorrelations for . The best is in the middle. Small steps are nearly always accepted but go nowhere; large steps are nearly always rejected (Figure 10.1).
For a normal target the acceptance rate can be computed exactly.
Proposition 10.3 (Random-Walk Acceptance Rate for a Normal Target). If the target is and the proposal is , the acceptance rate at stationarity is .
Proof. Standardize so that , , , and write the proposed jump as with . Averaging the acceptance probability over the stationary position,
the overlap of two unit normals a distance apart. With an independent , averaging over gives . By rotational symmetry the wedge has probability . □
With this gives , , and for , in line with the and Hoff observes for the first two (his finite-run estimate for the third is ). The usual advice is to run short pilot chains until the acceptance rate lies between and . Theory supports it. For idealized targets with independent components, Roberts, Gelman, and GilksGareth O. Roberts, Andrew Gelman, and Walter R. Gilks. Weak Convergence and Optimal Scaling of Random Walk Metropolis Algorithms. The Annals of Applied Probability, 7(1):110–120, 1997 showed that as the efficient proposal has scale about times the target’s, with limiting acceptance rate ; in one dimension the corresponding optimum is near (Exercise 10.10). These are guides, not certificates: a chain trapped in one mode may boast a perfect acceptance rate.
10.2.2Poisson Regression for the Sparrows#
For several coefficients, the proposal’s shape matters as much as its size. The natural choice is a multivariate normal centered at with covariance resembling the posterior’s. Borrowing from normal regression, Hoff uses , where is the sample variance of ; the half avoids . With priors the acceptance ratio is
(10.4)in which the Poisson mean is the exponential of the linear predictor.The displayed ratio on p. 180 of Hoff (2009) omits the exponential, writing ; the R code on the same page correctly uses exp(X%*%beta.p). See Appendix C. Ten thousand iterations accept about of proposals and yield effective sample sizes of , , and for ; the marginals are indistinguishable from the million-point grid.
10.3Metropolis–Hastings: One Algorithm to Contain Them All#
Metropolis proposals are symmetric; Gibbs proposals are not, yet are always accepted. Hastings’ generalization allows any proposal, at the price of one correction factor.
Algorithm 10.4 (Metropolis–Hastings). Target , known up to a constant. Given :
Sample .
Compute the acceptance ratio
(10.5)Set with probability , and otherwise.
The proposal may depend on the current state and on the iteration index , but on no earlier state.
The correction is easily remembered: reverse over forward. If a value is proposed far more often than its reverse move, its acceptance must be discounted or it would be over-represented. Letting depend on allows different blocks of to be updated in turn.
Proposition 10.5 (Metropolis and Gibbs Are Special Cases). (i) If is symmetric, (10.5) reduces to the Metropolis ratio . (ii) If and the proposal replaces by a draw from its full conditional , then .
Proof. Part (i) is immediate. For (ii), and the reverse move has density , so
□
10.3.1Why It Works#
Two separate facts are needed: that the chain converges to something, and that the something is .
A chain is irreducible if it can eventually reach every region of positive target probability from anywhere. (Proposing on the integers is reducible: even and odd numbers never meet.) It is aperiodic if it does not cycle through a fixed sequence of regions, and recurrent if it is certain to return to any region of positive probability.
Theorem 10.6 (Ergodic Theorem). Let be an irreducible, aperiodic, and (positive) recurrent Markov chain. Then there is a unique distribution such that, as ,
(10.6)almost surely, for every with . Moreover is stationary: if then .
Hoff states the theorem with “recurrent” alone; the word positive matters, because a symmetric random walk on the integers is irreducible and recurrent but has no stationary distribution.In general state spaces the theorem holds from almost every starting point, and from every one under Harris recurrence. An irreducible chain that possesses a proper invariant distribution is automatically positive recurrent, so Theorem 10.7 supplies the missing ingredient. Aperiodicity is needed for the first limit but not for the second. It remains to identify . Write for the acceptance probability. The transition kernel of Algorithm 10.4 has two parts, a density for accepted moves and an atom at the current point for rejections:
(10.7)Theorem 10.7 (Detailed Balance for Metropolis–Hastings). The kernel (10.7) satisfies detailed balance with respect to : for all sets and ,
(10.8)Consequently is stationary for .
Proof. Accepted moves (). Multiplying the acceptance probability through,
which is symmetric in . (Where such a move has probability zero, and both sides vanish.) Integrating over , therefore equals integrating over , .
Rejections (). The atom contributes , which is symmetric in and whatever is.
Adding the two parts proves (10.8). Taking to be the whole space and using gives , which is stationarity. □
The discrete sketch in most textbooks checks only and leaves the diagonal implicit; with densities, the diagonal is the rejection atom, and stationarity fails if it is forgotten. A scan that applies several block kernels in turn still preserves , since each factor does, although the composed kernel need not satisfy detailed balance.
10.4Metropolis within Gibbs: Regression with Correlated Errors#
Detailed balance holds kernel by kernel, so we may mix freely: Gibbs updates where full conditionals are available, Metropolis where they are not. This hybrid is Metropolis within Gibbs. Hoff’s example regresses temperature on CO concentration at 200 time points from Antarctic ice cores. Ordinary least squares gives slope with nominal standard error , but the residuals have lag-1 autocorrelation , so that standard error cannot be believed. A first-order autoregressive error model replaces by
(10.9)Given this is regression with a known correlation matrix, and the updates are those of Chapter 9 with inserted:
(10.10)With a vague prior is close to the generalized least squares estimate, hence Bayesian GLS. Naively, each new would cost an inversion. The Markov structure of the errors removes it.
Proposition 10.8 (Closed Form for the AR(1) Precision Matrix). For , , and is tridiagonal:
(10.11)Hence
computable in operations.
Proof. A unit-variance AR(1) vector satisfies and with independent standard normal , and direct computation gives . So with lower bidiagonal: first row , and row equal to . Since , we get , which multiplies out to (10.11), and . The quadratic form is . □
The conditional of is not standard, so we propose it with a reflecting random walk: draw ; if replace it by , and if replace it by . This is symmetric on (Exercise 10.11), so no Hastings correction is required.
Algorithm 10.9 (Metropolis-within-Gibbs for AR(1) Regression). Given , one scan consists of:
With diffuse priors and , the first scans accept of the proposals, yet their effective sample size is only 23. The acceptance rate looks healthy and the mixing is dreadful; only the latter matters. Hoff runs scans and keeps every 25th. Be clear about what thinning achieves: the retained draws are less correlated, but discarding the rest never adds information. For estimating a mean from a given run, using all the draws is in general at least as accurate, as Geyer argued;Charles J. Geyer. Practical Markov Chain Monte Carlo. Statistical Science, 7:473–483, 1992 thinning saves memory and downstream computation. Report the effective sample size, and modern rank-normalized over several chains,Aki Vehtari, Andrew Gelman, Daniel Simpson, Bob Carpenter, and Paul-Christian Bürkner. Rank-Normalization, Folding, and Localization: An Improved for Assessing Convergence of MCMC. Bayesian Analysis, 16(2):667–718, 2021 rather than the thinning interval.
The scientific answer changes by more than the standard error. The posterior mean slope is with 95% interval : still positive, but roughly a third of the OLS estimate. Runs of extreme temperatures are highly correlated with one another, and the GLS model counts them as few observations rather than many.
import numpy as np
rng = np.random.default_rng(10)
def metropolis(logp, x0, L, S):
"""Random-walk Metropolis; L is a Cholesky factor of the proposal covariance."""
x, lp, acc = np.array(x0, dtype=float), logp(x0), 0
out = np.empty((S, x.size))
for s in range(S):
prop = x + L @ rng.normal(size=x.size)
lpp = logp(prop)
if np.log(rng.uniform()) < lpp - lp: # log scale throughout
x, lp, acc = prop, lpp, acc + 1
out[s] = x # a rejection repeats the old value
return out, acc / S
def ess(x):
"""Effective sample size by Geyer's initial positive sequence."""
x = x - x.mean()
acf = np.correlate(x, x, "full")[x.size - 1:] / (x @ x)
tau = -1.0
for k in range(0, x.size - 1, 2):
pair = acf[k] + acf[k + 1]
if pair <= 0:
break
tau += 2 * pair
return x.size / max(tau, 1.0)
# 1. Hoff's normal example: observed acceptance vs (2/pi) arctan(2 tau / delta)
yn = np.array([9.37, 10.18, 9.16, 11.60, 10.33])
lp_norm = lambda t: -0.5 * np.sum((yn - t) ** 2) - 0.5 * np.sum((t - 5.0) ** 2) / 10.0
for d2 in (1 / 32, 2.0, 64.0):
ch, acc = metropolis(lp_norm, np.array([0.0]), np.array([[np.sqrt(d2)]]), 10_000)
print(f"delta^2={d2:7.3f} accept={acc:.3f} "
f"theory={2 / np.pi * np.arctan(2 * np.sqrt(1 / 5.1 / d2)):.3f} ESS={ess(ch[500:, 0]):.0f}")
# 2. Poisson regression on synthetic sparrow-like data
age = rng.integers(1, 7, size=52).astype(float)
X = np.column_stack([np.ones(52), age, age ** 2])
y = rng.poisson(np.exp(X @ np.array([0.2, 0.6, -0.13])))
def lp_pois(b):
eta = X @ b
return y @ eta - np.exp(eta).sum() - b @ b / 200.0 # normal(0, 100) priors
V = np.var(np.log(y + 0.5), ddof=1) * np.linalg.inv(X.T @ X)
B, acc = metropolis(lp_pois, np.zeros(3), np.linalg.cholesky(V), 10_000)
print(f"Poisson: accept={acc:.2f}, mean={B[1000:].mean(0).round(2)}, "
f"ESS={[round(ess(B[1000:, j])) for j in range(3)]}")
# 3. Metropolis within Gibbs for AR(1) regression (synthetic ice-core-like series)
def ar1(n, rho):
e = rng.normal(size=n)
for t in range(1, n):
e[t] = rho * e[t - 1] + np.sqrt(1 - rho ** 2) * e[t]
return e
def whiten(M, rho): # W'W = M' C_rho^{-1} M in O(n)
W = M.copy()
W[1:] = (M[1:] - rho * M[:-1]) / np.sqrt(1 - rho ** 2)
return W
n = 200
Xt = np.column_stack([np.ones(n), 230 + 25 * ar1(n, 0.8)])
yt = Xt @ np.array([-10.0, 0.03]) + 2.0 * ar1(n, 0.8)
nu0, s20, iS0, delta = 1.0, 1.0, np.eye(2) / 1000.0, 0.1
s2, rho, keep, acc = np.var(yt), 0.5, [], 0
for s in range(10_000):
W, w = whiten(Xt, rho), whiten(yt, rho)
Vn = np.linalg.inv(W.T @ W / s2 + iS0)
beta = Vn @ (W.T @ w) / s2 + np.linalg.cholesky(Vn) @ rng.normal(size=2)
e = yt - Xt @ beta
ssr = lambda r: np.sum(whiten(e, r) ** 2)
s2 = 1.0 / rng.gamma((nu0 + n) / 2, 2.0 / (nu0 * s20 + ssr(rho))) # scale = 1/rate
rp = abs(rng.uniform(rho - delta, rho + delta))
rp = 2 - rp if rp > 1 else rp
lr = (-0.5 * (n - 1) * (np.log1p(-rp ** 2) - np.log1p(-rho ** 2))
- (ssr(rp) - ssr(rho)) / (2 * s2))
if np.log(rng.uniform()) < lr:
rho, acc = rp, acc + 1
keep.append((beta[1], s2, rho))
keep = np.array(keep)[1000:]
print(f"AR(1): accept={acc / 10_000:.2f}, slope 95% CI={np.quantile(keep[:, 0], [.025, .975]).round(3)}, "
f"ESS(slope, sigma^2, rho)={[round(ess(keep[:, j])) for j in range(3)]}")10.5Modern Developments: Gradients, Estimated Likelihoods, and Informed Proposals#
10.5.1Hamiltonian Monte Carlo and the No-U-Turn Sampler#
The random walk of Algorithm 10.2 ignores the gradient of the log-posterior, which for (10.2) is simply ; Hamiltonian Monte Carlo (HMC) uses it to make distant proposals that are still accepted.Beyond Hoff (2009). This material is not in Hoff’s book; HMC itself is older (physicists introduced it as hybrid Monte Carlo in the 1980s), but its optimal-scaling theory (Beskos et al., 2013) and the self-tuning No-U-Turn Sampler (Hoffman and Gelman, 2014) are later. Write , add a momentum , and iterate leapfrog steps of size :
(10.13)where is the end of the trajectory.
Why it holds. Each of the three updates is a shear, with Jacobian , and following the trajectory with a momentum flip gives a map that is its own inverse. The proposal is therefore deterministic, volume preserving, and reversible, so the reverse over forward factor of (10.5) is and only the change in remains. For product targets in dimensions the stable step size scales as , so a trajectory of fixed length costs gradients, against steps for the random walk, and the optimal acceptance rate rises from to .Alexandros Beskos, Natesh Pillai, Gareth Roberts, Jesus-Maria Sanz-Serna, and Andrew Stuart. Optimal tuning of the hybrid Monte Carlo algorithm. Bernoulli, 19(5A):1501–1534, 2013. doi: 10.3150/12-BEJ414 The No-U-Turn Sampler doubles the trajectory until at either end, selects a point in a way that preserves the target, and tunes during warmup.Matthew D. Hoffman and Andrew Gelman. The No-U-Turn Sampler: Adaptively Setting Path Lengths in Hamiltonian Monte Carlo. Journal of Machine Learning Research, 15(47):1593–1623, 2014
When to use it. Make NUTS the default for smooth, continuous posteriors with more than a few parameters. Hoff’s random walk remains fine in low dimension or without gradients; discrete parameters need a different tool, and separated modes defeat both.
10.5.2Pseudo-Marginal and Particle MCMC#
The ratio (10.3) cancels but still requires , which is itself an intractable integral when the AR(1) process of (10.9) is, say, the hidden log-rate of Poisson counts; the pseudo-marginal method replaces it with an estimate.Beyond Hoff (2009). This material is not in Hoff’s book; the theory of Andrieu and Roberts (2009) appeared in the same year as Hoff’s book and is not covered there, and particle MCMC (Andrieu, Doucet, and Holenstein, 2010) followed. Let be a random estimate of with density and . Use
(10.14)Why it holds. Run Metropolis–Hastings on the extended target , proposing and then . The factors cancel, leaving exactly , so Theorem 10.7 applies. Integrating out of gives by unbiasedness: the estimate is noisy, yet the target is exact.Christophe Andrieu and Gareth O. Roberts. The pseudo-marginal approach for efficient Monte Carlo computations. The Annals of Statistics, 37(2):697–725, 2009. doi: 10.1214/07-AOS574 The stored must be kept until the next acceptance; refreshing it changes the target. A particle filter supplies unbiased estimates for state-space models, and particle Gibbs updates the whole hidden path.Christophe Andrieu, Arnaud Doucet, and Roman Holenstein. Particle Markov Chain Monte Carlo Methods. Journal of the Royal Statistical Society Series B: Statistical Methodology, 72(3):269–342, 2010. doi: 10.1111/j.1467-9868.2009.00736.x More particles mean less noise but more work: under Gaussian log-noise of constant variance, a standard deviation of near is a good general choice, lower when the exact chain would mix well and higher when it would mix poorly.A. Doucet, M. K. Pitt, G. Deligiannidis, and R. Kohn. Efficient implementation of Markov chain Monte Carlo when using an unbiased likelihood estimator. Biometrika, 102(2):295–313, 2015. doi: 10.1093/biomet/asu075
When to use it. Use it when cannot be evaluated but has an unbiased, nonnegative estimator of manageable variance; being able to simulate data is not enough by itself. If the latent path can be updated in closed-form blocks, Hoff’s Algorithm 10.9 is simpler and cheaper.
10.5.3Locally Balanced Proposals for Discrete Spaces#
Gradients do not exist on , so the sampler for the inclusion vector in Chapter 9 visits coordinates blindly, most of which have nothing to do; a locally balanced proposal looks at all the neighbors first.Beyond Hoff (2009). This material is not in Hoff’s book; Zanella (2020) extends gradient-style informed proposals to discrete spaces, modernizing blind single-site updates. Let be a symmetric kernel, such as “flip a uniformly chosen coordinate,” and let satisfy , for example or . ThenGiacomo Zanella. Informed Proposals for Local MCMC in Discrete Spaces. Journal of the American Statistical Association, 115(530):852–865, 2020. doi: 10.1080/01621459.2019.1585255
(10.15)Why it holds. Put in (10.5). Symmetry cancels , and the ratio becomes . When one flip barely alters the surroundings, and nearly every informed move is accepted. The greedy choice violates the condition and loses this property. For variable selection, flipping has if and if , with the odds of (9.10). With the weight is exactly the probability that Hoff’s Gibbs update would change , so effort goes to the coordinates that want to move.
When to use it. One move needs all marginal likelihoods, so it pays when is large, few coordinates are ambiguous, and the evaluations parallelize. For small , Algorithm 9.6 is hard to beat; and since both make single flips, neither crosses a valley between swapped correlated regressors unless includes swaps.
10.5.4Computational & Symbolic Check#
The script runs the leapfrog map of (10.13) on a one-dimensional standard normal, with , and tests volume, reversibility, the HMC draws, and the Barker weight .Beyond Hoff (2009). This computational check and its Wolfram symbolic counterpart below verify the modern methods in this section and are not in Hoff’s book.
import numpy as np
def leapfrog(q, p, eps=0.5, L=3): # U(q) = q^2/2, so U'(q) = q
for _ in range(L):
p = p - 0.5 * eps * q
q = q + eps * p
p = p - 0.5 * eps * q
return q, p
rng = np.random.default_rng(101)
J = np.column_stack([leapfrog(1.0, 0.0), leapfrog(0.0, 1.0)]) # here the map is linear
q1, p1 = leapfrog(0.7, -1.2)
print("det J =", np.linalg.det(J).round(12), " reversed:", np.round(leapfrog(q1, -p1), 12))
q, acc = np.full(50_000, 3.0), 0.0 # 50,000 chains, all started at q = 3
for _ in range(20):
p = rng.normal(size=q.size)
qn, pn = leapfrog(q, p)
ok = np.log(rng.uniform(size=q.size)) < 0.5 * (q ** 2 + p ** 2 - qn ** 2 - pn ** 2)
q, acc = np.where(ok, qn, q), acc + ok.mean() / 20
print(f"HMC: accept={acc:.3f}, mean={q.mean():.3f}, var={q.var():.3f} (exact 0, 1)")
t, h = np.array([0.1, 1.0, 7.0]), lambda t: t / (1 + t)
print("balance h(t) - t h(1/t):", np.round(h(t) - t * h(1 / t), 12))// One leapfrog step (M = 1) for a general potential U, and its Jacobian determinant
const leap = await show`With[{ph = p - eps/2*U'[q]}, With[{qn = q + eps*ph}, {qn, ph - eps/2*U'[qn]}]]`await show`Simplify[Det[D[${leap}, {{q, p}}]]]`// Locally balanced condition h(t) = t h(1/t): Barker, square root, and the greedy choice
await show`Assuming[t > 0, Simplify[Table[f - t*(f /. t -> 1/t), {f, {t/(1 + t), Sqrt[t], t}}]]]`10.6Symbolic Check in Wolfram Language#
Evaluates the stationary normal random-walk acceptance integral symbolically in wolfram-ws-bridge JavaScript mode, abstracts the normal-target example to general , verifies the closed-form AR(1) determinant and tridiagonal precision matrix for , and instantiates the symbolic acceptance formula on Hoff’s 5-point normal target.
// Chapter 10: Symbolic Metropolis acceptance rate (general normal posterior) & AR(1) precision
const accRate = await show`Assuming[ell > 0,
FullSimplify[Integrate[Erfc[Abs[ell*w]/(2*Sqrt[2])]*Exp[-w^2/2]/Sqrt[2*Pi], {w, -Infinity, Infinity}]]]`// Abstract the normal-target example: ell = delta / tau_n with 1/tau_n^2 = n/s2 + 1/t0^2
const accNormal = await show`Assuming[d > 0 && n > 0 && s2 > 0 && t0 > 0,
FullSimplify[${accRate} /. ell -> d * Sqrt[n/s2 + 1/t0^2]]]`// Verify AR(1) determinant and tridiagonal precision matrix symbolically for n = 5
await show`Factor[Det[Table[rho^Abs[i - j], {i, 5}, {j, 5}]]]`await show`Simplify[(1 - rho^2) * Inverse[Table[rho^Abs[i - j], {i, 5}, {j, 5}]]]`// Instantiate symbolic accNormal on Hoff's 5-point normal target (n = 5, s2 = 1, t0^2 = 10; delta^2 in {1/32, 2, 64})
await show`N[Table[${accNormal} /. {n -> 5, s2 -> 1, t0 -> Sqrt[10], d -> Sqrt[d2]}, {d2, {1/32, 2, 64}}]]`10.7Exercises#
Exercise 10.10. Extend the proof of Proposition 10.3 to the expected squared jump. With and , show by polar coordinates that
at stationarity, and that the lag-1 autocorrelation is minus this quantity divided by . Maximize numerically over and confirm that the optimum is near with acceptance rate near . Why do finite-run autocorrelations started at differ from these stationary values?
Symbolic Solution & Instantiation
Simplify the 1-D Metropolis expected squared jump distance symbolically.// Ex 10.1: Symbolic expected squared jump & optimal 1D Metropolis scaling (tau = 1; 2.38 is d -> Inf limit)
const esjd = await show`FullSimplify[(2*ell^2/Pi) * (Pi/2 - ArcTan[ell/2] - Sin[2*ArcTan[ell/2]]/2)]`const acf1 = await show`FullSimplify[1 - ${esjd}/2]`const accRate = await show`(2/Pi)*ArcCot[ell/2]`const ellStar = await show`ell /. FindRoot[D[${esjd}, ell] == 0, {ell, 2.4}]`await show`N[{${ellStar}, ${accRate} /. ell -> ${ellStar}, ${acf1} /. ell -> ${ellStar}}]`Exercise 10.11. Show that for the reflecting random walk has density
on , and conclude that it is symmetric. What goes wrong if out-of-range proposals are instead redrawn until they fall inside , with no Hastings correction?
Symbolic Solution & Instantiation
Verify that the reflecting random-walk kernel integrates to near the boundary ().// Ex 10.2: Normalization & symmetry of reflecting random walk vs. naive-redraw boundary depletion
await show`Assuming[0 < d <= 1/2 && 0 < a < d,
FullSimplify[Integrate[1/(2*d), {b, 0, a + d}] + Integrate[1/(2*d), {b, 0, d - a}]]]`const statFactor = await show`(Min[1, a + d] - Max[0, a - d]) / (2*d)`await show`N[${statFactor} /. {a -> 1/1000, d -> 1/5}]`Exercise 10.12. To sample a positive parameter , propose with . Compute the Hastings correction and show that it equals . Verify that the same algorithm arises by running a symmetric Metropolis walk on with the Jacobian included in the target, and demonstrate by simulation what distribution is sampled when the correction is omitted.
Symbolic Solution & Instantiation
Write the forward log-normal proposal density of , .// Ex 10.3: Log-scale multiplicative proposal Hastings ratio J(th | th*) / J(th* | th) = th* / th
const jFwd = await show`Exp[-(Log[thP/th])^2/(2*d^2)] / (thP*d*Sqrt[2*Pi])`const jRev = await show`Exp[-(Log[th/thP])^2/(2*d^2)] / (th*d*Sqrt[2*Pi])`const hRatio = await show`Assuming[th > 0 && thP > 0 && d > 0, FullSimplify[${jRev} / ${jFwd}]]`await show`${hRatio} /. {th -> 1, thP -> 2}`Exercise 10.13. In Algorithm 10.9 the update of conditions on . Integrate out of (10.9) analytically to obtain , and implement the alternative scan that first updates given and then draws given . Explain why the pair of steps is a valid update of jointly, and compare effective sample sizes per second.
Symbolic Solution & Instantiation
Write the collapsed marginal covariance after integrating out .// Ex 10.4: Marginal covariance of y | X, sigma^2, rho after integrating out beta ~ N(b0, S0)
await show`s2 * cMat[rho] + xMat . s0Mat . Transpose[xMat]`await show`N[{{1, 1/2}, {1/2, 1}} + {{1}, {2}}.{{4}}.{{1, 2}}]`