---
title: "The Metropolis Engine: Mechanics & Calibration"
subtitle: "Deconstructing the Random Walk, the Metropolis Acceptance Ratio, and the Step-Size Dilemma"
---
```{r setup, echo = TRUE, message = FALSE, warning = FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = FALSE)
library(dplyr)
library(ggplot2)
library(scales)
source("R/metropolis_sampler.R")
source("R/plots.R")
# Target: Correlated bivariate normal
target_toy <- function(theta) {
mu <- c(0, 0)
sigma <- matrix(c(1.0, 0.75, 0.75, 1.0), nrow = 2)
-0.5 * t(theta - mu) %*% solve(sigma) %*% (theta - mu)
}
# Run 3 chains with varying step sizes to demonstrate tuning
chain_timid <- run_metropolis(target_toy, initial_theta = c(0, 0), iterations = 2000, proposal_sd = 0.03, seed = 101)
chain_wild <- run_metropolis(target_toy, initial_theta = c(0, 0), iterations = 2000, proposal_sd = 3.20, seed = 101)
chain_tuned <- run_metropolis(target_toy, initial_theta = c(0, 0), iterations = 2000, proposal_sd = 1.20, seed = 101)
```
#### The Four Steps of Metropolis-Hastings
Rather than solving high-dimensional integrals analytically, the Metropolis-Hastings algorithm generates samples from an unnormalized target density via four iterative steps: <br/>
1. **Propose a Candidate Move:**
Given the current state $\theta^{(t)}$, sample candidate coordinates $\theta^*$ from a symmetric proposal distribution:
$$\theta^* \sim \mathcal{N}\left(\theta^{(t)}, \sigma_{\epsilon}^2 \mathbf{I}\right)$$
2. **Evaluate the Metropolis Acceptance Ratio ($\alpha$):** Compare target density at the candidate position to the current state:
$$\alpha = \min\left(1, \frac{p(\theta^*)}{p(\theta^{(t)})}\right)$$
In practice, this is evaluated in log-space to prevent numerical floating-point underflow:
$$\log \alpha = \min\left(0, \log p(\theta^*) - \log p(\theta^{(t)})\right)$$
3. **The Acceptance Decision:**
Draw a uniform scalar $u \sim \text{Uniform}(0, 1)$ . If $\log u < \log \alpha$, the candidate is accepted:
$$\theta^{(t+1)} = \theta^*$$
Otherwise, the candidate is rejected, and the chain remains in place:
$$\theta^{(t+1)} = \theta^{(t)}$$
::: {.callout-note icon=false}
While occasionally accepting lower-density moves enables traversal across non-convex surfaces, standard Random-Walk Metropolis remains vulnerable to getting trapped between separated modes on complex, multimodal target surfaces.
:::
4. **Iterate:**
Repeating this transition rule generates an empirical chain whose visited states converge asymptotically to the target posterior distribution $p(\theta \mid \mathcal{D})$.
---
### The Complete Engine in R
Below is the complete sampling engine implemented from first principles in base R:
```{r show-engine, echo = TRUE, eval = FALSE}
library(tibble)
library(dplyr)
run_metropolis <- function(target_log_posterior,
initial_theta,
iterations = 5000,
proposal_sd = 0.05,
seed = NULL) {
if (!is.null(seed)) set.seed(seed)
d <- length(initial_theta)
theta_current <- initial_theta
log_p_current <- target_log_posterior(theta_current)
draws_mat <- matrix(NA_real_, nrow = iterations, ncol = d)
accepted <- logical(iterations)
log_probs <- numeric(iterations)
for (t in 1:iterations) {
if (is.matrix(proposal_sd)) {
theta_candidate <- MASS::mvrnorm(1, mu = theta_current, Sigma = proposal_sd)
} else {
theta_candidate <- rnorm(d, mean = theta_current, sd = proposal_sd)
}
log_p_candidate <- target_log_posterior(theta_candidate)
log_alpha <- log_p_candidate - log_p_current
if (!is.na(log_alpha) && log(runif(1)) < log_alpha) {
theta_current <- theta_candidate
log_p_current <- log_p_candidate
accepted[t] <- TRUE
} else {
accepted[t] <- FALSE
}
draws_mat[t, ] <- theta_current
log_probs[t] <- log_p_current
}
param_names <- if (!is.null(names(initial_theta))) {
names(initial_theta)
} else {
paste0("theta_", seq_len(d))
}
draws_df <- as_tibble(draws_mat, .name_repair = "minimal")
colnames(draws_df) <- param_names
draws_df <- draws_df %>% mutate(iteration = seq_len(iterations))
diagnostics_df <- tibble(
iteration = seq_len(iterations),
accepted = accepted,
log_posterior = log_probs
)
list(
draws = draws_df,
acceptance_rate = mean(accepted),
diagnostics = diagnostics_df,
dimensions = d,
proposal_sd = proposal_sd
)
}
```
---
### The Step-Size Dilemma: Tuning Proposal Variance
The primary operational lever in Random-Walk Metropolis is the proposal standard deviation ($\sigma_{\epsilon}$). Tuning this parameter governs the trade-off between spatial displacement per jump and proposal rejection frequency:
```{r step-size-plot, fig.cap = "Figure 1: Trace plots illustrating the impact of proposal step size on chain mixing and acceptance"}
#| fig-width: 10
#| fig-height: 10
plot_step_size_comparison(chain_timid, chain_wild, chain_tuned)
```
**Understanding the Trace Plots**
The trace panels illustrate the trajectory of parameter $\theta_1$ over 2,000 steps under three distinct proposal step sizes ($\sigma_\epsilon$), showing how proposal variance governs chain exploration:
1. **Too Timid ($\sigma_{\epsilon} = 0.03$ — Bottom Panel):** Almost every proposal is accepted (98.5% acceptance), but displacement per step is small. The chain wanders sluggishly through diffusion rather than stationary mixing, exhibiting strong positive autocorrelation and requiring extensive iterations to traverse the distribution.
2. **Too Aggressive ($\sigma_{\epsilon} = 3.20$ — Middle Panel):** Large proposal jumps land frequently in low-probability density tails, leading to a rejection rate exceeding 90% (9.9% acceptance). The trace exhibits horizontal flatlines where the state remains frozen across multiple consecutive iterations.
3. **Calibrated ($\sigma_{\epsilon} = 1.20$ — Top Panel):** Jump radius is balanced against target density gradients, achieving an empirical acceptance rate of approximately 34.2% (aligning with theoretical targets of 25% to 40% for low dimensions). The trajectory rapidly oscillates across the distribution center. However, while a calibrated acceptance rate is necessary, it does not alone guarantee rapid autocorrelation decay when applied to high-dimensional, correlated parameters.