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 YY and the age xx 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:

Y∣𝐱∼Poisson⁡(θx),log⁡θx=𝜷T𝐱,𝐱=(1,x,x2)T. Y \mid \mathbf{x} \sim \operatorname{Poisson}(\theta_x), \qquad \log\theta_x = \boldsymbol{\beta}^T\mathbf{x}, \qquad \mathbf{x} = (1, x, x^2)^T. (10.1)

A generalized linear model connects a linear predictor 𝜷T𝐱\boldsymbol{\beta}^T\mathbf{x} to E[Y∣𝐱]E[Y \mid \mathbf{x}] through a link function: the log link for counts, and for binary data the logit link log⁡θx1−θx=𝜷T𝐱\log\frac{\theta_x}{1 - \theta_x} = \boldsymbol{\beta}^T\mathbf{x}, that is, logistic regression. With a prior 𝜷∼𝒩p(𝜷0,Σ0)\boldsymbol{\beta} \sim \mathcal{N}_p(\boldsymbol{\beta}_0, \Sigma_0), the log-posterior for (10.1) is

log⁡p(𝜷∣𝐗,𝐲)=∑i=1n(yi 𝜷T𝐱i−e𝜷T𝐱i)−12(𝜷−𝜷0)TΣ0−1(𝜷−𝜷0)+const. \log p(\boldsymbol{\beta} \mid \mathbf{X}, \mathbf{y}) = \sum_{i=1}^n \bigl(y_i\,\boldsymbol{\beta}^T\mathbf{x}_i - e^{\boldsymbol{\beta}^T\mathbf{x}_i}\bigr) - \frac{1}{2}(\boldsymbol{\beta} - \boldsymbol{\beta}_0)^T\Sigma_0^{-1}(\boldsymbol{\beta} - \boldsymbol{\beta}_0) + \text{const}. (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 Σ0≻0\Sigma_0 \succ 0, the Poisson (log-link) and logistic (logit-link) posteriors are strictly log-concave in 𝜷\boldsymbol{\beta}, hence unimodal.

Proof. Differentiating twice, the Hessian of the log-posterior is −∑iwi𝐱i𝐱iT−Σ0−1-\sum_i w_i\mathbf{x}_i\mathbf{x}_i^T - \Sigma_0^{-1}, with wi=θxiw_i = \theta_{x_i} for Poisson and wi=θxi(1−θxi)w_i = \theta_{x_i}(1 - \theta_{x_i}) 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 10610^6 evaluations and five need 101010^{10}. Moreover, because β2\beta_2 and β3\beta_3 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 θa,θb\theta_a, \theta_b we have #{θa}/#{θb}≈p(θa∣y)/p(θb∣y)\#\{\theta_a\}/\#\{\theta_b\} \approx p(\theta_a \mid y)/p(\theta_b \mid y). Standing at θ(s)\theta^{(s)}, consider adding a nearby candidate θ∗\theta^*. The comparison we need,

r=p(θ∗∣y)p(θ(s)∣y)=p(y∣θ∗) p(θ∗)p(y∣θ(s)) p(θ(s)), r = \frac{p(\theta^* \mid y)}{p(\theta^{(s)} \mid y)} = \frac{p(y \mid \theta^*)\,p(\theta^*)}{p(y \mid \theta^{(s)})\,p(\theta^{(s)})}, (10.3)

does not involve the intractable constant p(y)p(y). If r≥1r \ge 1, the candidate deserves at least as many copies as the current value: accept it. If r<1r < 1, it deserves only a fraction rr of a copy: accept it with probability rr, 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 J(θ∗∣θ)J(\theta^* \mid \theta) be a symmetric proposal, J(θb∣θa)=J(θa∣θb)J(\theta_b \mid \theta_a) = J(\theta_a \mid \theta_b), for example normal⁡(θ,δ2)\operatorname{normal}(\theta, \delta^2) or uniform⁡(θ−δ,θ+δ)\operatorname{uniform}(\theta - \delta, \theta + \delta). Given θ(s)\theta^{(s)}:

  1. Sample θ∗∼J(θ∣θ(s))\theta^* \sim J(\theta \mid \theta^{(s)}).

  2. Compute

    log⁡r=log⁡p(y∣θ∗)+log⁡p(θ∗)−log⁡p(y∣θ(s))−log⁡p(θ(s)). \log r = \log p(y \mid \theta^*) + \log p(\theta^*) - \log p(y \mid \theta^{(s)}) - \log p(\theta^{(s)}).
  3. Sample u∼uniform⁡(0,1)u \sim \operatorname{uniform}(0, 1). Set θ(s+1)=θ∗\theta^{(s+1)} = \theta^* if log⁡u<log⁡r\log u < \log r, and θ(s+1)=θ(s)\theta^{(s+1)} = \theta^{(s)} otherwise.

Working on the log scale in step 2 is not a nicety: products of hundreds of densities underflow to zero, and the ratio 0/00/0 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: n=5n = 5 observations y=(9.37,10.18,9.16,11.60,10.33)y = (9.37, 10.18, 9.16, 11.60, 10.33) with σ2=1\sigma^2 = 1 and prior normal⁡(5,10)\operatorname{normal}(5, 10), so that θ∣y∼normal⁡(10.03,0.20)\theta \mid y \sim \operatorname{normal}(10.03, 0.20). Starting deliberately far away at θ(0)=0\theta^{(0)} = 0, he runs normal proposals with various δ2\delta^2 and reports lag-1 autocorrelations 0.98,0.77,0.69,0.84,0.860.98, 0.77, 0.69, 0.84, 0.86 for δ2=132,12,2,32,64\delta^2 = \frac{1}{32}, \frac{1}{2}, 2, 32, 64. The best is in the middle. Small steps are nearly always accepted but go nowhere; large steps are nearly always rejected (Figure 10.1).

Three Metropolis trace plots of 600 iterations started at zero with a shaded band around the posterior mean 10.03: proposal variance 1/32 drifts upward slowly and accepts 79 percent; proposal variance 2 reaches the band within a few steps and accepts 36 percent; proposal variance 64 shows long flat plateaus and accepts 9 percent
Figure 10.1: Metropolis chains of length 600 for Hoff’s five-observation normal model, all started at θ(0)=0\theta^{(0)} = 0; the dashed line and band mark the exact posterior mean and ±2\pm 2 posterior standard deviations. Left: δ2=1/32\delta^2 = 1/32 accepts most proposals but takes tiny steps. Center: δ2=2\delta^2 = 2 mixes well. Right: δ2=64\delta^2 = 64 is mostly rejected and gets stuck on plateaus. The acceptance rates in the titles (79%79\%, 36%36\%, 9%9\%) are for these short runs and include the burn-in from zero.

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 normal⁡(μ,τ2)\operatorname{normal}(\mu, \tau^2) and the proposal is normal⁡(θ,δ2)\operatorname{normal}(\theta, \delta^2), the acceptance rate at stationarity is 2πarctan⁡(2τ/δ)\frac{2}{\pi}\arctan(2\tau/\delta).

Proof. Standardize so that μ=0\mu = 0, τ=1\tau = 1, ℓ=δ/τ\ell = \delta/\tau, and write the proposed jump as u=ℓwu = \ell w with w∼normal⁡(0,1)w \sim \operatorname{normal}(0,1). Averaging the acceptance probability over the stationary position,

∫ϕ(x)min⁡{1,ϕ(x+u)/ϕ(x)} dx=∫min⁡{ϕ(x),ϕ(x+u)} dx=2Φ(−∣u∣/2), \int \phi(x)\min\{1, \phi(x+u)/\phi(x)\}\,dx = \int \min\{\phi(x), \phi(x + u)\}\,dx = 2\Phi(-\lvert u \rvert/2),

the overlap of two unit normals a distance ∣u∣\lvert u \rvert apart. With an independent v∼normal⁡(0,1)v \sim \operatorname{normal}(0,1), averaging over ww gives 2Pr⁡(v>ℓ∣w∣/2)2\Pr(v > \ell\lvert w \rvert/2). By rotational symmetry the wedge {v>ℓ∣w∣/2}\{v > \ell\lvert w \rvert/2\} has probability 1π(π2−arctan⁡ℓ2)=1πarctan⁡2ℓ\frac{1}{\pi}\bigl(\frac{\pi}{2} - \arctan\frac{\ell}{2}\bigr) = \frac{1}{\pi}\arctan\frac{2}{\ell}. □

With τ2=1/5.1\tau^2 = 1/5.1 this gives 87.5%87.5\%, 35.6%35.6\%, and 7.0%7.0\% for δ2=132,2,64\delta^2 = \frac{1}{32}, 2, 64, in line with the 87%87\% and 35%35\% Hoff observes for the first two (his finite-run estimate for the third is 5%5\%). The usual advice is to run short pilot chains until the acceptance rate lies between 20%20\% and 50%50\%. Theory supports it. For idealized targets with dd 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 d→∞d \to \infty the efficient proposal has scale about 2.38/d2.38/\sqrt{d} times the target’s, with limiting acceptance rate 0.2340.234; in one dimension the corresponding optimum is near 0.440.44 (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 𝜷(s)\boldsymbol{\beta}^{(s)} with covariance resembling the posterior’s. Borrowing from normal regression, Hoff uses σ^2(𝐗T𝐗)−1\hat{\sigma}^2(\mathbf{X}^T\mathbf{X})^{-1}, where σ^2\hat{\sigma}^2 is the sample variance of log⁡(yi+12)\log(y_i + \frac{1}{2}); the half avoids log⁡0\log 0. With priors βj∼normal⁡(0,100)\beta_j \sim \operatorname{normal}(0, 100) the acceptance ratio is

r=∏i=1ndpois⁡(yi, exp⁡(𝐱iT𝜷∗))∏i=1ndpois⁡(yi, exp⁡(𝐱iT𝜷(s)))×∏j=13dnorm⁡(βj∗,0,10)∏j=13dnorm⁡(βj(s),0,10), r = \frac{\prod_{i=1}^n \operatorname{dpois}\bigl(y_i,\, \exp(\mathbf{x}_i^T\boldsymbol{\beta}^*)\bigr)}{\prod_{i=1}^n \operatorname{dpois}\bigl(y_i,\, \exp(\mathbf{x}_i^T\boldsymbol{\beta}^{(s)})\bigr)} \times \frac{\prod_{j=1}^3 \operatorname{dnorm}(\beta_j^*, 0, 10)}{\prod_{j=1}^3 \operatorname{dnorm}(\beta_j^{(s)}, 0, 10)}, (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 dpois⁡(yi,𝐱iT𝜷∗)\operatorname{dpois}(y_i, \mathbf{x}_i^T\boldsymbol{\beta}^*); the R code on the same page correctly uses exp(X%*%beta.p). See Appendix C. Ten thousand iterations accept about 43%43\% of proposals and yield effective sample sizes of 818818, 778778, and 726726 for β1,β2,β3\beta_1, \beta_2, \beta_3; 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 p0(x)p_0(x), known up to a constant. Given x(s)x^{(s)}:

  1. Sample x∗∼Js(x∗∣x(s))x^* \sim J_s(x^* \mid x^{(s)}).

  2. Compute the acceptance ratio

    r=p0(x∗)p0(x(s))×Js(x(s)∣x∗)Js(x∗∣x(s)). r = \frac{p_0(x^*)}{p_0(x^{(s)})} \times \frac{J_s(x^{(s)} \mid x^*)}{J_s(x^* \mid x^{(s)})}. (10.5)
  3. Set x(s+1)=x∗x^{(s+1)} = x^* with probability min⁡(1,r)\min(1, r), and x(s+1)=x(s)x^{(s+1)} = x^{(s)} otherwise.

The proposal may depend on the current state and on the iteration index ss, but on no earlier state.

The correction Js(x(s)∣x∗)/Js(x∗∣x(s))J_s(x^{(s)} \mid x^*)/J_s(x^* \mid x^{(s)}) 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 JsJ_s depend on ss allows different blocks of xx to be updated in turn.

Proposition 10.5 (Metropolis and Gibbs Are Special Cases). (i) If JsJ_s is symmetric, (10.5) reduces to the Metropolis ratio p0(x∗)/p0(x(s))p_0(x^*)/p_0(x^{(s)}). (ii) If x=(u,v)x = (u, v) and the proposal replaces uu by a draw from its full conditional p0(u∣v)p_0(u \mid v), then r≡1r \equiv 1.

Proof. Part (i) is immediate. For (ii), J(u∗∣u,v)=p0(u∗∣v)J(u^* \mid u, v) = p_0(u^* \mid v) and the reverse move has density p0(u∣v)p_0(u \mid v), so

r=p0(u∗,v)p0(u,v)⋅p0(u∣v)p0(u∗∣v)=p0(u∗∣v) p0(v)p0(u∣v) p0(v)⋅p0(u∣v)p0(u∗∣v)=1. r = \frac{p_0(u^*, v)}{p_0(u, v)} \cdot \frac{p_0(u \mid v)}{p_0(u^* \mid v)} = \frac{p_0(u^* \mid v)\,p_0(v)}{p_0(u \mid v)\,p_0(v)} \cdot \frac{p_0(u \mid v)}{p_0(u^* \mid v)} = 1 .

□

10.3.1Why It Works

Two separate facts are needed: that the chain converges to something, and that the something is p0p_0.

A chain is irreducible if it can eventually reach every region of positive target probability from anywhere. (Proposing x±2x \pm 2 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 {x(1),x(2),… }\{x^{(1)}, x^{(2)}, \dots\} be an irreducible, aperiodic, and (positive) recurrent Markov chain. Then there is a unique distribution π\pi such that, as s,S→∞s, S \to \infty,

Pr⁡(x(s)∈A)→π(A)for every set A,1S∑s=1Sg(x(s))→∫g(x) π(x) dx \Pr(x^{(s)} \in A) \to \pi(A) \quad\text{for every set } A, \qquad \frac{1}{S}\sum_{s=1}^S g(x^{(s)}) \to \int g(x)\,\pi(x)\,dx (10.6)

almost surely, for every gg with ∫∣g(x)∣ π(x) dx<∞\int \lvert g(x) \rvert\,\pi(x)\,dx < \infty. Moreover π\pi is stationary: if x(s)∼πx^{(s)} \sim \pi then x(s+1)∼πx^{(s+1)} \sim \pi.

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 π\pi. Write α(x,x′)=min⁡{1,r}\alpha(x, x') = \min\{1, r\} 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:

T(x,A)=∫AJ(x′∣x) α(x,x′) dx′+ρ(x) 𝟏(x∈A),ρ(x)=1−∫J(x′∣x) α(x,x′) dx′. T(x, A) = \int_A J(x' \mid x)\,\alpha(x, x')\,dx' + \rho(x)\,\mathbf{1}(x \in A), \qquad \rho(x) = 1 - \int J(x' \mid x)\,\alpha(x, x')\,dx'. (10.7)

Theorem 10.7 (Detailed Balance for Metropolis–Hastings). The kernel (10.7) satisfies detailed balance with respect to p0p_0: for all sets AA and BB,

∫Ap0(x) T(x,B) dx=∫Bp0(x) T(x,A) dx. \int_A p_0(x)\,T(x, B)\,dx = \int_B p_0(x)\,T(x, A)\,dx . (10.8)

Consequently p0p_0 is stationary for TT.

Proof. Accepted moves (x≠x′x \neq x'). Multiplying the acceptance probability through,

p0(x) J(x′∣x) α(x,x′)=p0(x) J(x′∣x) min⁡{1, p0(x′) J(x∣x′)p0(x) J(x′∣x)}=min⁡{p0(x) J(x′∣x),  p0(x′) J(x∣x′)}, p_0(x)\,J(x' \mid x)\,\alpha(x, x') = p_0(x)\,J(x' \mid x)\,\min\left\{1,\, \frac{p_0(x')\,J(x \mid x')}{p_0(x)\,J(x' \mid x)}\right\} = \min\bigl\{p_0(x)\,J(x' \mid x),\; p_0(x')\,J(x \mid x')\bigr\},

which is symmetric in (x,x′)(x, x'). (Where p0(x)J(x′∣x)=0p_0(x)J(x' \mid x) = 0 such a move has probability zero, and both sides vanish.) Integrating over x∈Ax \in A, x′∈Bx' \in B therefore equals integrating over x∈Bx \in B, x′∈Ax' \in A.

Rejections (x=x′x = x'). The atom contributes ∫Ap0(x) ρ(x) 𝟏(x∈B) dx=∫A∩Bp0(x) ρ(x) dx\int_A p_0(x)\,\rho(x)\,\mathbf{1}(x \in B)\,dx = \int_{A \cap B} p_0(x)\,\rho(x)\,dx, which is symmetric in AA and BB whatever ρ\rho is.

Adding the two parts proves (10.8). Taking AA to be the whole space and using T(x,whole space)=1T(x, \text{whole space}) = 1 gives ∫p0(x) T(x,B) dx=∫Bp0(x) dx\int p_0(x)\,T(x, B)\,dx = \int_B p_0(x)\,dx, which is stationarity. □

The discrete sketch in most textbooks checks only x≠x′x \neq x' 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 p0p_0, 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 CO2_2 concentration at 200 time points from Antarctic ice cores. Ordinary least squares gives slope 0.080.08 with nominal standard error 0.00380.0038, but the residuals have lag-1 autocorrelation 0.520.52, so that standard error cannot be believed. A first-order autoregressive error model replaces σ2I\sigma^2 I by

𝐲∼𝒩n(𝐗𝜷, σ2Cρ),(Cρ)s,t=ρ∣s−t∣. \mathbf{y} \sim \mathcal{N}_n(\mathbf{X}\boldsymbol{\beta},\, \sigma^2 C_\rho), \qquad (C_\rho)_{s,t} = \rho^{\lvert s - t \rvert}. (10.9)

Given ρ\rho this is regression with a known correlation matrix, and the updates are those of Chapter 9 with Cρ−1C_\rho^{-1} inserted:

𝜷∣⋅∼𝒩p(𝜷n,Σn),Σn=(𝐗TCρ−1𝐗/σ2+Σ0−1)−1,𝜷n=Σn(𝐗TCρ−1𝐲/σ2+Σ0−1𝜷0),1/σ2∣⋅∼gamma⁡ ⁣(ν0+n2, ν0σ02+SSR⁡ρ2),SSR⁡ρ=(𝐲−𝐗𝜷)TCρ−1(𝐲−𝐗𝜷). \begin{aligned} \boldsymbol{\beta} \mid \cdot &\sim \mathcal{N}_p(\boldsymbol{\beta}_n, \Sigma_n), \qquad \Sigma_n = \bigl(\mathbf{X}^TC_\rho^{-1}\mathbf{X}/\sigma^2 + \Sigma_0^{-1}\bigr)^{-1}, \quad \boldsymbol{\beta}_n = \Sigma_n\bigl(\mathbf{X}^TC_\rho^{-1}\mathbf{y}/\sigma^2 + \Sigma_0^{-1}\boldsymbol{\beta}_0\bigr), \\ 1/\sigma^2 \mid \cdot &\sim \operatorname{gamma}\!\left(\frac{\nu_0 + n}{2},\, \frac{\nu_0\sigma_0^2 + \operatorname{SSR}_\rho}{2}\right), \qquad \operatorname{SSR}_\rho = (\mathbf{y} - \mathbf{X}\boldsymbol{\beta})^TC_\rho^{-1}(\mathbf{y} - \mathbf{X}\boldsymbol{\beta}). \end{aligned} (10.10)

With a vague prior 𝜷n\boldsymbol{\beta}_n is close to the generalized least squares estimate, hence Bayesian GLS. Naively, each new ρ\rho would cost an O(n3)O(n^3) inversion. The Markov structure of the errors removes it.

Proposition 10.8 (Closed Form for the AR(1) Precision Matrix). For ∣ρ∣<1\lvert \rho \rvert < 1, ∣Cρ∣=(1−ρ2)n−1\lvert C_\rho \rvert = (1 - \rho^2)^{n-1}, and Cρ−1C_\rho^{-1} is tridiagonal:

Cρ−1=11−ρ2(1−ρ−ρ1+ρ2−ρ⋱⋱⋱−ρ1+ρ2−ρ−ρ1). C_\rho^{-1} = \frac{1}{1 - \rho^2} \begin{pmatrix} 1 & -\rho & & & \\ -\rho & 1 + \rho^2 & -\rho & & \\ & \ddots & \ddots & \ddots & \\ & & -\rho & 1 + \rho^2 & -\rho \\ & & & -\rho & 1 \end{pmatrix}. (10.11)

Hence

𝐞TCρ−1𝐞=e12+11−ρ2∑t=2n(et−ρet−1)2, \mathbf{e}^TC_\rho^{-1}\mathbf{e} = e_1^2 + \frac{1}{1 - \rho^2}\sum_{t=2}^n (e_t - \rho e_{t-1})^2,

computable in O(n)O(n) operations.

Proof. A unit-variance AR(1) vector satisfies e1=η1e_1 = \eta_1 and et=ρet−1+1−ρ2 ηte_t = \rho e_{t-1} + \sqrt{1 - \rho^2}\,\eta_t with independent standard normal ηt\eta_t, and direct computation gives Cov⁡(es,et)=ρ∣s−t∣\operatorname{Cov}(e_s, e_t) = \rho^{\lvert s - t \rvert}. So 𝜼=M𝐞\boldsymbol{\eta} = M\mathbf{e} with MM lower bidiagonal: first row (1,0,…,0)(1, 0, \dots, 0), and row tt equal to (1−ρ2)−1/2(…,−ρ,1,… )(1-\rho^2)^{-1/2}(\dots, -\rho, 1, \dots). Since I=MCρMTI = MC_\rho M^T, we get Cρ−1=MTMC_\rho^{-1} = M^TM, which multiplies out to (10.11), and ∣Cρ∣=∣M∣−2=(1−ρ2)n−1\lvert C_\rho \rvert = \lvert M \rvert^{-2} = (1 - \rho^2)^{n-1}. The quadratic form is ∥M𝐞∥2\lVert M\mathbf{e} \rVert^2. □

The conditional of ρ\rho is not standard, so we propose it with a reflecting random walk: draw ρ∗∼uniform⁡(ρ−δ,ρ+δ)\rho^* \sim \operatorname{uniform}(\rho - \delta, \rho + \delta); if ρ∗<0\rho^* < 0 replace it by ∣ρ∗∣\lvert \rho^* \rvert, and if ρ∗>1\rho^* > 1 replace it by 2−ρ∗2 - \rho^*. This is symmetric on (0,1)(0, 1) (Exercise 10.11), so no Hastings correction is required.

Algorithm 10.9 (Metropolis-within-Gibbs for AR(1) Regression). Given (𝜷(s),σ2(s),ρ(s))(\boldsymbol{\beta}^{(s)}, \sigma^{2(s)}, \rho^{(s)}), one scan consists of:

  1. Gibbs: draw 𝜷(s+1)\boldsymbol{\beta}^{(s+1)} from (10.10) using σ2(s),ρ(s)\sigma^{2(s)}, \rho^{(s)}.

  2. Gibbs: draw σ2(s+1)\sigma^{2(s+1)} from (10.10) using 𝜷(s+1),ρ(s)\boldsymbol{\beta}^{(s+1)}, \rho^{(s)}.

  3. Metropolis: propose ρ∗\rho^* by reflection and accept it with probability min⁡(1,r)\min(1, r), where

    log⁡r=−n−12log⁡1−ρ∗21−ρ(s)2−SSR⁡ρ∗−SSR⁡ρ(s)2σ2(s+1)+log⁡p(ρ∗)p(ρ(s)). \log r = -\frac{n-1}{2}\log\frac{1 - \rho^{*2}}{1 - \rho^{(s)2}} - \frac{\operatorname{SSR}_{\rho^*} - \operatorname{SSR}_{\rho^{(s)}}}{2\sigma^{2(s+1)}} + \log\frac{p(\rho^*)}{p(\rho^{(s)})}. (10.12)

With diffuse priors and ρ∼uniform⁡(0,1)\rho \sim \operatorname{uniform}(0,1), the first 1,0001{,}000 scans accept 32%32\% of the ρ\rho 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 25,00025{,}000 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 R̂\widehat{R} over several chains,Aki Vehtari, Andrew Gelman, Daniel Simpson, Bob Carpenter, and Paul-Christian Bürkner. Rank-Normalization, Folding, and Localization: An Improved R̂\widehat{R} 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 0.0280.028 with 95% interval (0.01,0.05)(0.01, 0.05): 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 ∑i(yi−e𝜷T𝐱i)𝐱i−Σ0−1(𝜷−𝜷0)\sum_i (y_i - e^{\boldsymbol{\beta}^T\mathbf{x}_i})\mathbf{x}_i - \Sigma_0^{-1}(\boldsymbol{\beta} - \boldsymbol{\beta}_0); 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 ℓ(θ)=log⁡p(θ∣y)\ell(\theta) = \log p(\theta \mid y), add a momentum 𝐮∼𝒩d(𝟎,M)\mathbf{u} \sim \mathcal{N}_d(\mathbf{0}, M), and iterate leapfrog steps of size ϵ\epsilon:

𝐮1/2=𝐮+ϵ2∇ℓ(θ),θ′=θ+ϵM−1𝐮1/2,𝐮′=𝐮1/2+ϵ2∇ℓ(θ′),α=min⁡{1, eH(θ,𝐮)−H(θ∗,𝐮∗)},H(θ,𝐮)=−ℓ(θ)+12𝐮TM−1𝐮, \begin{aligned} \mathbf{u}_{1/2} &= \mathbf{u} + \frac{\epsilon}{2}\nabla\ell(\theta), \qquad \theta' = \theta + \epsilon M^{-1}\mathbf{u}_{1/2}, \qquad \mathbf{u}' = \mathbf{u}_{1/2} + \frac{\epsilon}{2}\nabla\ell(\theta'), \\ \alpha &= \min\bigl\{1,\, e^{H(\theta, \mathbf{u}) - H(\theta^*, \mathbf{u}^*)}\bigr\}, \qquad H(\theta, \mathbf{u}) = -\ell(\theta) + \frac{1}{2}\mathbf{u}^TM^{-1}\mathbf{u}, \end{aligned} (10.13)

where (θ∗,𝐮∗)(\theta^*, \mathbf{u}^*) is the end of the trajectory.

Why it holds. Each of the three updates is a shear, with Jacobian 11, 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 11 and only the change in HH remains. For product targets in dd dimensions the stable step size scales as d−1/4d^{-1/4}, so a trajectory of fixed length costs O(d1/4)O(d^{1/4}) gradients, against O(d)O(d) steps for the random walk, and the optimal acceptance rate rises from 0.2340.234 to 0.6510.651.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 (θ+−θ−)T𝐮±<0(\theta^+ - \theta^-)^T\mathbf{u}^\pm < 0 at either end, selects a point in a way that preserves the target, and tunes ϵ\epsilon 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 p(y)p(y) but still requires p(y∣θ)p(y \mid \theta), 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 p^≥0\hat{p} \ge 0 be a random estimate of p(y∣θ)p(y \mid \theta) with density m(p^∣θ)m(\hat{p} \mid \theta) and E[p^∣θ]=p(y∣θ)E[\hat{p} \mid \theta] = p(y \mid \theta). Use

r^=p^∗ p(θ∗)p^(s) p(θ(s))×J(θ(s)∣θ∗)J(θ∗∣θ(s)),p~(θ,p^∣y)∝p(θ) p^ m(p^∣θ). \hat{r} = \frac{\hat{p}^*\,p(\theta^*)}{\hat{p}^{(s)}\,p(\theta^{(s)})} \times \frac{J(\theta^{(s)} \mid \theta^*)}{J(\theta^* \mid \theta^{(s)})}, \qquad \tilde{p}(\theta, \hat{p} \mid y) \propto p(\theta)\,\hat{p}\,m(\hat{p} \mid \theta). (10.14)

Why it holds. Run Metropolis–Hastings on the extended target p~\tilde{p}, proposing θ∗∼J\theta^* \sim J and then p^∗∼m(⋅∣θ∗)\hat{p}^* \sim m(\cdot \mid \theta^*). The factors mm cancel, leaving exactly r^\hat{r}, so Theorem 10.7 applies. Integrating p^\hat{p} out of p~\tilde{p} gives p(θ) p(y∣θ)p(\theta)\,p(y \mid \theta) 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 p^(s)\hat{p}^{(s)} 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 log⁡p^\log\hat{p} near 1.21.2 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 p(y∣θ)p(y \mid \theta) 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 {0,1}p\{0,1\}^p, so the sampler for the inclusion vector 𝐳\mathbf{z} 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 KK be a symmetric kernel, such as “flip a uniformly chosen coordinate,” and let h>0h > 0 satisfy h(t)=t h(1/t)h(t) = t\,h(1/t), for example h(t)=th(t) = \sqrt{t} or h(t)=t/(1+t)h(t) = t/(1+t). 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

J(𝐳∗∣𝐳)=1Z(𝐳) h ⁣(p0(𝐳∗)p0(𝐳))K(𝐳,𝐳∗),Z(𝐳)=∑𝐳′h ⁣(p0(𝐳′)p0(𝐳))K(𝐳,𝐳′),α(𝐳,𝐳∗)=min⁡{1,  Z(𝐳)Z(𝐳∗)}. \begin{aligned} J(\mathbf{z}^* \mid \mathbf{z}) &= \frac{1}{Z(\mathbf{z})}\,h\!\left(\frac{p_0(\mathbf{z}^*)}{p_0(\mathbf{z})}\right)K(\mathbf{z}, \mathbf{z}^*), \qquad Z(\mathbf{z}) = \sum_{\mathbf{z}'} h\!\left(\frac{p_0(\mathbf{z}')}{p_0(\mathbf{z})}\right)K(\mathbf{z}, \mathbf{z}'), \\ \alpha(\mathbf{z}, \mathbf{z}^*) &= \min\left\{1,\; \frac{Z(\mathbf{z})}{Z(\mathbf{z}^*)}\right\}. \end{aligned} (10.15)

Why it holds. Put t=p0(𝐳∗)/p0(𝐳)t = p_0(\mathbf{z}^*)/p_0(\mathbf{z}) in (10.5). Symmetry cancels KK, and the ratio becomes t h(1/t) Z(𝐳)/{h(t) Z(𝐳∗)}=Z(𝐳)/Z(𝐳∗)t\,h(1/t)\,Z(\mathbf{z})/\{h(t)\,Z(\mathbf{z}^*)\} = Z(\mathbf{z})/Z(\mathbf{z}^*). When one flip barely alters the surroundings, Z(𝐳)≈Z(𝐳∗)Z(\mathbf{z}) \approx Z(\mathbf{z}^*) and nearly every informed move is accepted. The greedy choice h(t)=th(t) = t violates the condition and loses this property. For variable selection, flipping zjz_j has t=ojt = o_j if zj=0z_j = 0 and t=1/ojt = 1/o_j if zj=1z_j = 1, with the odds ojo_j of (9.10). With h(t)=t/(1+t)h(t) = t/(1+t) the weight hh is exactly the probability that Hoff’s Gibbs update would change zjz_j, so effort goes to the coordinates that want to move.

When to use it. One move needs all pp marginal likelihoods, so it pays when pp is large, few coordinates are ambiguous, and the evaluations parallelize. For small pp, Algorithm 9.6 is hard to beat; and since both make single flips, neither crosses a valley between swapped correlated regressors unless KK includes swaps.

10.5.4Computational & Symbolic Check

The script runs the leapfrog map of (10.13) on a one-dimensional standard normal, U(q)=−ℓ(q)=q2/2U(q) = -\ell(q) = q^2/2 with M=1M = 1, and tests volume, reversibility, the HMC draws, and the Barker weight h(t)=t/(1+t)h(t) = t/(1+t).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))
Compose one leapfrog step (M=1M = 1) for an arbitrary potential UU: half-step in pp, full step in qq, half-step in pp.
// 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]}]]`
(q′,p′)={q+ϵ(p−12ϵ U′(q)),p−12ϵ U′(q)−12ϵ U′ ⁣(q+ϵ(p−12ϵ U′(q)))} \begin{aligned} (q', p') = \Bigl\{&q+\epsilon \left(p-\tfrac{1}{2} \epsilon\, U'(q)\right), \\ &p-\tfrac{1}{2} \epsilon\, U'(q)-\tfrac{1}{2} \epsilon\, U'\!\left(q+\epsilon \left(p-\tfrac{1}{2} \epsilon\, U'(q)\right)\right)\Bigr\} \end{aligned} Differentiate the step with respect to (q,p)(q, p): both U′′U'' terms cancel, so the determinant is 11 for every ϵ\epsilon.
await show`Simplify[Det[D[${leap}, {{q, p}}]]]`
det⁡Jleapfrog=det⁡∂(q′,p′)∂(q,p)=1 \det J_{\text{leapfrog}} = \det\frac{\partial(q', p')}{\partial(q, p)} = 1 Test h(t)−t h(1/t)h(t) - t\,h(1/t) for the Barker weight, the square root, and the greedy h(t)=th(t) = t, which fails the balance condition.
// 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}}]]]`
(h(t)−t h(1/t))h ∈ {t1+t, t, t}={0,0,−1+t} \bigl(h(t) - t\,h(1/t)\bigr)_{h \,\in\, \left\{\frac{t}{1+t},\, \sqrt{t},\, t\right\}} = \{0,0,-1+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 (n,σ2,τ02,δ)(n, \sigma^2, \tau_0^2, \delta), verifies the closed-form AR(1) determinant and tridiagonal precision matrix for n=5n = 5, and instantiates the symbolic acceptance formula on Hoff’s 5-point normal target.

Integrate the Metropolis acceptance probability against a standard normal target to derive α(ℓ)=(2/π)arccot⁡(ℓ/2)\alpha(\ell) = (2/\pi)\operatorname{arccot}(\ell/2).
// 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}]]]`
α(ℓ)=∫−∞∞erfc⁡ ⁣(∣ℓw∣22)ϕ(w) dw=2cot⁡−1(ℓ2)π \begin{aligned} &\alpha(\ell) = \int_{-\infty}^\infty \operatorname{erfc}\!\left(\frac{|\ell w|}{2\sqrt{2}}\right)\phi(w)\,dw \\ &= \frac{2 \cot^{-1}\left(\frac{\ell}{2}\right)}{\pi} \end{aligned} Substitute the scaled proposal step ℓ=dn/σ2+τ0−2\ell = d\sqrt{n/\sigma^2 + \tau_0^{-2}} for a general normal posterior.
// 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]]]`
α ⁣(dn/σ2+τ0−2)=2cot⁡−1(12dnσ2+1τ02)π \begin{aligned} &\alpha\!\left(d\sqrt{n/\sigma^2 + \tau_0^{-2}}\right) \\ &= \frac{2 \cot^{-1}\left(\frac{1}{2} d \sqrt{\frac{n}{\sigma^2}+\frac{1}{\tau_0^2}}\right)}{\pi} \end{aligned} Compute the symbolic determinant (1−ρ2)4(1 - \rho^2)^4 of the 5×55 \times 5 AR(1) correlation matrix.
// 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}]]]`
det⁡ ⁣(ρ∣i−j∣)1≤i,j≤5=(−1+ρ)4(1+ρ)4 \det\!\bigl(\rho^{|i-j|}\bigr)_{1\le i,j\le 5} = (-1+\rho)^4 (1+\rho)^4 Invert the 5×55 \times 5 AR(1) correlation matrix to confirm its sparse tridiagonal precision structure.
await show`Simplify[(1 - rho^2) * Inverse[Table[rho^Abs[i - j], {i, 5}, {j, 5}]]]`
(1−ρ2)(ρ∣i−j∣)1≤i,j≤5−1=(1−ρ000−ρ1+ρ2−ρ000−ρ1+ρ2−ρ000−ρ1+ρ2−ρ000−ρ1) \begin{aligned} &(1-\rho^2)\bigl(\rho^{|i-j|}\bigr)_{1\le i,j\le 5}^{-1} \\ &= \left( \begin{array}{ccccc} 1 & -\rho & 0 & 0 & 0 \\ -\rho & 1+\rho^2 & -\rho & 0 & 0 \\ 0 & -\rho & 1+\rho^2 & -\rho & 0 \\ 0 & 0 & -\rho & 1+\rho^2 & -\rho \\ 0 & 0 & 0 & -\rho & 1 \\ \end{array} \right) \end{aligned} Instantiate the exact acceptance rate on Hoff’s 5-point normal target for δ2∈{1/32,2,64}\delta^2 \in \{1/32, 2, 64\}.
// 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}}]]`
(α(δ))δ2∈{1/32, 2, 64}={0.874573,0.356176,0.0701892} \bigl(\alpha(\delta)\bigr)_{\delta^2 \in \{1/32,\, 2,\, 64\}} = \{0.874573,0.356176,0.0701892\}

10.7Exercises

Exercise 10.10. Extend the proof of Proposition 10.3 to the expected squared jump. With ℓ=δ/τ\ell = \delta/\tau and ω=arctan⁡(ℓ/2)\omega = \arctan(\ell/2), show by polar coordinates that

E[(θ(s+1)−θ(s))2]=2δ2π[π2−ω−12sin⁡2ω] E[(\theta^{(s+1)} - \theta^{(s)})^2] = \frac{2\delta^2}{\pi}\bigl[\frac{\pi}{2} - \omega - \frac{1}{2}\sin 2\omega\bigr]

at stationarity, and that the lag-1 autocorrelation is 11 minus this quantity divided by 2τ22\tau^2. Maximize numerically over ℓ\ell and confirm that the optimum is near ℓ=2.4\ell = 2.4 with acceptance rate near 0.440.44. Why do finite-run autocorrelations started at θ(0)=0\theta^{(0)} = 0 differ from these stationary values?

Symbolic Solution & InstantiationSimplify the 1-D Metropolis expected squared jump distance ESJD⁡(ℓ)\operatorname{ESJD}(\ell) 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)]`
ESJD⁡(ℓ)=ℓ2(−4ℓ4+ℓ2+π−2tan⁡−1(ℓ2))π \begin{aligned} &\operatorname{ESJD}(\ell) \\ &= \frac{\ell^2 \left(-\frac{4 \ell}{4+\ell^2}+\pi -2 \tan^{-1}\left(\frac{\ell}{2}\right)\right)}{\pi} \end{aligned} Express the lag-1 autocorrelation ρ1(ℓ)=1−1/2ESJD⁡(ℓ)\rho_1(\ell) = 1 - 1/2\operatorname{ESJD}(\ell) in closed form.
const acf1 = await show`FullSimplify[1 - ${esjd}/2]`
ρ1(ℓ)=1−12ESJD⁡(ℓ)=1−ℓ2(−4ℓ4+ℓ2+π−2tan⁡−1(ℓ2))2π \begin{aligned} &\rho_1(\ell) = 1 - \frac{1}{2}\operatorname{ESJD}(\ell) \\ &= 1-\frac{\ell^2 \left(-\frac{4 \ell}{4+\ell^2}+\pi -2 \tan^{-1}\left(\frac{\ell}{2}\right)\right)}{2 \pi} \end{aligned} Write the stationary acceptance rate α(ℓ)\alpha(\ell) of the 1-D Gaussian random-walk Metropolis at scale ℓ\ell.
const accRate = await show`(2/Pi)*ArcCot[ell/2]`
α(ℓ)=2cot⁡−1(ℓ2)π \alpha(\ell) = \frac{2 \cot^{-1}\left(\frac{\ell}{2}\right)}{\pi} Maximize ESJD⁡(ℓ)\operatorname{ESJD}(\ell) numerically by solving ESJD⁡′(ℓ)=0\operatorname{ESJD}'(\ell) = 0 near ℓ=2.4\ell = 2.4.
const ellStar = await show`ell /. FindRoot[D[${esjd}, ell] == 0, {ell, 2.4}]`
ℓ∗=arg⁡max⁡ℓ ESJD⁡(ℓ)=2.4264 \ell^* = \arg\max_{\ell}\, \operatorname{ESJD}(\ell) = 2.4264 Instantiate α(ℓ)\alpha(\ell) and ρ1(ℓ)\rho_1(\ell) at ℓ∗\ell^* to obtain the 1-D optimum (ℓ∗,α(ℓ∗),ρ1(ℓ∗))(\ell^*, \alpha(\ell^*), \rho_1(\ell^*)).
await show`N[{${ellStar}, ${accRate} /. ell -> ${ellStar}, ${acf1} /. ell -> ${ellStar}}]`
(ℓ∗,  α(ℓ∗),  ρ1(ℓ∗))τ=1={2.4264,0.438862,0.627898} \bigl(\ell^*,\; \alpha(\ell^*),\; \rho_1(\ell^*)\bigr)_{\tau=1} = \{2.4264,0.438862,0.627898\}

Exercise 10.11. Show that for 0<δ≤10 < \delta \le 1 the reflecting random walk has density

J(b∣a)=12δ[𝟏(∣b−a∣<δ)+𝟏(a+b<δ)+𝟏(2−a−b<δ)] J(b \mid a) = \frac{1}{2\delta}\bigl[\mathbf{1}(\lvert b - a \rvert < \delta) + \mathbf{1}(a + b < \delta) + \mathbf{1}(2 - a - b < \delta)\bigr]

on (0,1)(0,1), and conclude that it is symmetric. What goes wrong if out-of-range proposals are instead redrawn until they fall inside (0,1)(0, 1), with no Hastings correction?

Symbolic Solution & InstantiationVerify that the reflecting random-walk kernel integrates to 11 near the boundary (0<a<d≤1/20 < a < d \le 1/2).
// 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}]]]`
∫01Jrefl(b∣a) db=1 \int_0^1 J_{\text{refl}}(b \mid a)\,db = 1 Compute the stationary density distortion factor Z(a)/(2d)Z(a)/(2d) induced by naive boundary redrawing.
const statFactor = await show`(Min[1, a + d] - Max[0, a - d]) / (2*d)`
πredraw(a)π(a)∝Z(a)2d=−max⁡(0,a−d)+min⁡(1,a+d)2d \begin{aligned} &\frac{\pi_{\text{redraw}}(a)}{\pi(a)} \propto \frac{Z(a)}{2d} \\ &= \frac{-\max (0,a-d)+\min (1,a+d)}{2 d} \end{aligned} Evaluate the boundary distortion at a=0.001,d=0.2a = 0.001, d = 0.2, confirming the stationary boundary density is halved.
await show`N[${statFactor} /. {a -> 1/1000, d -> 1/5}]`
Z(a)2d∣a=0.001,  d=0.2=0.5025 \left.\frac{Z(a)}{2d}\right|_{a=0.001,\; d=0.2} = 0.5025

Exercise 10.12. To sample a positive parameter θ\theta, propose θ∗=θeϵ\theta^* = \theta e^{\epsilon} with ϵ∼normal⁡(0,δ2)\epsilon \sim \operatorname{normal}(0, \delta^2). Compute the Hastings correction J(θ∣θ∗)/J(θ∗∣θ)J(\theta \mid \theta^*)/J(\theta^* \mid \theta) and show that it equals θ∗/θ\theta^*/\theta. Verify that the same algorithm arises by running a symmetric Metropolis walk on log⁡θ\log\theta with the Jacobian included in the target, and demonstrate by simulation what distribution is sampled when the correction is omitted.

Symbolic Solution & InstantiationWrite the forward log-normal proposal density of θ∗=θeϵ\theta^* = \theta e^{\epsilon}, ϵ∼normal⁡(0,δ2)\epsilon \sim \operatorname{normal}(0, \delta^2).
// 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])`
J(θ∗∣θ)=e−log⁡2(θ∗/θ)2δ22π δ θ∗ J(\theta^* \mid \theta) = \frac{e^{-\frac{\log^2(\theta^*/\theta)}{2 \delta^2}}}{\sqrt{2 \pi}\, \delta\, \theta^*} Write the reverse proposal density, swapping the roles of θ\theta and θ∗\theta^*.
const jRev = await show`Exp[-(Log[th/thP])^2/(2*d^2)] / (th*d*Sqrt[2*Pi])`
J(θ∣θ∗)=e−log⁡2(θ/θ∗)2δ22π δ θ J(\theta \mid \theta^*) = \frac{e^{-\frac{\log^2(\theta/\theta^*)}{2 \delta^2}}}{\sqrt{2 \pi}\, \delta\, \theta} Take the ratio of reverse to forward log-normal proposal densities to derive the Hastings factor θ∗/θ\theta^*/\theta.
const hRatio = await show`Assuming[th > 0 && thP > 0 && d > 0, FullSimplify[${jRev} / ${jFwd}]]`
J(θ∣θ∗)J(θ∗∣θ)=θ∗θ \frac{J(\theta \mid \theta^*)}{J(\theta^* \mid \theta)} = \frac{\theta^*}{\theta} Evaluate the Hastings Jacobian correction at a doubling move θ=1→θ∗=2\theta = 1 \to \theta^* = 2.
await show`${hRatio} /. {th -> 1, thP -> 2}`
J(θ∣θ∗)J(θ∗∣θ)∣θ=1,  θ∗=2=2 \left.\frac{J(\theta \mid \theta^*)}{J(\theta^* \mid \theta)}\right|_{\theta=1,\; \theta^*=2} = 2

Exercise 10.13. In Algorithm 10.9 the update of ρ\rho conditions on 𝜷\boldsymbol{\beta}. Integrate 𝜷\boldsymbol{\beta} out of (10.9) analytically to obtain p(𝐲∣𝐗,σ2,ρ)p(\mathbf{y} \mid \mathbf{X}, \sigma^2, \rho), and implement the alternative scan that first updates ρ\rho given σ2\sigma^2 and then draws 𝜷\boldsymbol{\beta} given (ρ,σ2)(\rho, \sigma^2). Explain why the pair of steps is a valid update of (ρ,𝜷)(\rho, \boldsymbol{\beta}) jointly, and compare effective sample sizes per second.

Symbolic Solution & InstantiationWrite the collapsed marginal covariance Cov⁡(y∣X,σ2,ρ)\operatorname{Cov}(y \mid X, \sigma^2, \rho) after integrating out β∼𝒩(b0,Σ0)\beta \sim \mathcal{N}(b_0, \Sigma_0).
// 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]`
Cov⁡(y∣X,σ2,ρ)=σ2C(ρ)+X.Σ0.XT \operatorname{Cov}(y \mid X, \sigma^2, \rho) = \sigma^2 C (\rho)+X .\Sigma_0 .X^T Instantiate the collapsed 2×22 \times 2 marginal covariance at σ2=1,ρ=0.5,X=(1,2)T,Σ0=4\sigma^2 = 1, \rho = 0.5, X = (1, 2)^T, \Sigma_0 = 4.
await show`N[{{1, 1/2}, {1/2, 1}} + {{1}, {2}}.{{4}}.{{1, 2}}]`
Cov⁡(y∣X,σ2=1,ρ=0.5)=(5.8.58.517.) \begin{aligned} &\operatorname{Cov}(y \mid X, \sigma^2=1, \rho=0.5) \\ &= \left( \begin{array}{cc} 5. & 8.5 \\ 8.5 & 17. \\ \end{array} \right) \end{aligned}