In this lab, we’ll explore one of the most commonly used tools in Bayesian computing and MCMC numerical integration: the Metropolis-Hastings Algorithm. Before we introduce this technique, we’ll start by discussing rejection sampling.
As in the previous lab, focused on ABC, we’re interested in estimating the posterior distribution, \(f(\theta | y) = \frac{f(y|\theta)f(\theta)}{f(y)} \propto f(y|\theta)f(\theta)\), where \(\theta\) is a vector of parameters and \(y\) is our observed vector of data. Also following the previous lab, we want to learn about this distribution by drawing samples from it. By sampling from the posterior distribution, we can make formal Bayesian inference about the parameters of interest, or functions of them. If we have a function of our parameters, \(a(\theta)\), we can approximate its expectation over \(n\) samples \(\theta^{(i)}\) as: \(E(a(\theta)) = \int_{Y}a(\theta)f(Y,\theta)dy = \int_{Y}a(\theta)f(\theta|Y)f(Y)dy \approx \frac{1}{n}\sum_{i=1}^na(\theta^{(i)})\)
There are lots of algorithms for drawing samples from an unnormalized probability density function, each with benefits and drawbacks. As we saw last time, Approximate Bayesian Computation might be beneficial in settings where the likelihood/data generating distribution is unavailable or intractable. Most of the models we encounter in statistical practice, however, have tractable likelihoods and, as a result, tractable posteriors (unless we do silly things like use improper prior distributions).
Suppose we’re interested in sampling from the following function:
f <- function(x){
0.25*dnorm(x, mean = 3, sd =0.5) + 0.75*dnorm(x, mean = -3, sd = 3)
}
curve(f, xlim = c(-10,10))
The rejection algorithm requires that we find a proposal/envelope distribution \(g\) from which we can sample, and a constant \(M\) such that \(f(x) \le Mg(x) \forall x\). This can be challenging in practice, especially for high dimensions.
Nevertheless, for our toy example, we can construct such a \(g\) and \(M\) quite easily:
g <- function(x){
dnorm(x, mean = 0, sd = 10)
}
M <- 6
g.m <- function(x){M*g(x)}
curve(f, xlim = c(-20, 20), ylim = c(0,0.3))
curve(g.m, add = TRUE, col = "red")
The rejection sampling algorithm proceeds as follows:
The algorithm terminates when a prespecified number of accepted samples are obtained. This is easily implemented:
reject_algo <- function(n, f, g, g.sample, M, verbose = TRUE){
out <- matrix(NA, nrow = n, ncol = length(g.sample()))
accepted <- 0
trys <- 0
while (accepted < n){
trys <- trys+1
x <- g.sample()
ratio <- f(x)/(M*g(x))
if (runif(1,0,1) < ratio){
accepted <- accepted + 1
out[accepted,] <- x
if (verbose && accepted %% 100 == 0){
cat(paste0(accepted, "/", n, "\n"))
}
}
}
list(sample = out, acc_rate = accepted/trys)
}
sample <- reject_algo(1000, f, g, function(){rnorm(1,0,10)}, 6)
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
hist(sample$sample, breaks = 20)
sample$acc_rate
## [1] 0.174642
This algorithm is useful in the one dimensional case, but the requirements on \(g\) can be burdensome, and the acceptance rates can suffer in higher dimensions. On the other hand, the samples generated by the algorithm are not correlated; a distinct advantage over some other methods.
Consider what happens if we generalize this example to more dimensions:
f.nd <- function(x){
prod(0.25*dnorm(x, mean = 3, sd =0.5) + 0.75*dnorm(x, mean = -3, sd = 3))
}
g.nd <- function(x){
# iid normal
prod(dnorm(x, mean = 0, sd = 10))
}
M <- 6
dimensional_problems <- Reduce("rbind", lapply(1:10, function(d){
cat("Dimension: ", d, "\n")
tm <- system.time({rslt <- reject_algo(1000, f.nd, g.nd,
g.sample = function(){rnorm(d,0,10)},
M = 6)$acc_rate})
data.frame(rate = rslt, time = tm[3])
}))
## Dimension: 1
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 2
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 3
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 4
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 5
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 6
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 7
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 8
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 9
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
## Dimension: 10
## 100/1000
## 200/1000
## 300/1000
## 400/1000
## 500/1000
## 600/1000
## 700/1000
## 800/1000
## 900/1000
## 1000/1000
plot(1:10, dimensional_problems$rate, type = "b", xlab = "dimension", ylab = "Acceptance Rate")
plot(1:10, dimensional_problems$time, type = "b", xlab = "Dimension", ylab = "Time")
In fact, the problem is actually worse - we have less coverage of the domain, since the domain increases rapidly, while the number of samples was kept constant here.
Consider this effect with simple uniform distributions:
## 1D Example
Npts <- 20
X <- runif(Npts, 0,1)
plot(X, rep(0,Npts), xlim = c(0,1), xlab = "Value", ylab = "",
main = "One Dimension")
abline(h=0)
abline(v=c(0,1))
summary(dist(X))
## 2D Example
Y <- runif(Npts, 0,1)
plot(X, Y, xlim = c(0,1), ylim = c(0,1),
xlab = "Dimension 1", ylab = "Dimension 2",
main = "Two Dimensions")
summary(dist(cbind(X,Y)))
library(rgl)
Z <- runif(Npts, 0,1)
points3d(x = X,
y = Y,
z = Z)
summary(dist(cbind(X,Y,Z)))
Adaptive extensions of the algorithm exist which can improve on these properties somewhat. The basic Adaptive Rejection Sampling algorithm will actually not work on the example function given here, because it requires that the density function we’re studying is log-concave, which is not the case here:
xvals <- seq(-10,10,length = 1000)
plot(xvals, log(f(xvals)), type = "l")
plot(xvals, f(xvals), type = "l")
The basic idea is to make our envelope function adaptive, so that it improves over time. Generally, we’ll make it out of piece-wise linear densities. Consider the following toy example:
f <- function(x){
dbeta(x, 5,5)
}
l.f <- function(x){
dbeta(x, 5,5, log = TRUE)
}
g <- function(x){
rep(f(0.5), length(x))
}
set.seed(123126)
M <- 3
xpts <- seq(0,1,length = 1000)
plot(xpts, f(xpts), ylim = c(0,3), type = "l", xlab = "value")
lines(xpts, g(xpts), col = "red")
points(x=c(0,1), y = g(c(0,1)), col = "red")
# Draw Proposal
x1 <- runif(1,0,1)
abline(v = x1)
# Evaluate uniform along the line
u <- runif(1,0,1)
points(x1, u, col = "blue")
# We fail to accept, so we want to update our proposal
# Check out log scale:
plot(xpts, log(f(xpts)), type = "l", xlab = "value")
lines(xpts, log(g(xpts)), col = "red")
points(x1, log(u), col = "blue")
# Upper bound at this point:
points(x1,l.f(x1))
# Compute slope of tangent line at x1
deriv <- function(f, x){
(f(x1 + 2*.Machine$double.eps) - f(x1 - 2*.Machine$double.eps))/
(4*.Machine$double.eps)
}
slope <- deriv(l.f, x1)
intercept <- l.f(x1) - slope*x1
# Plot tangent line
abline(intercept,slope, col = "blue")
# Construct our new overall envelope:
# Intersection of two lines:
intersection <- (intercept - log(g(x1)))/(0-slope)
points(intersection, log(g(intersection)))
This process is iterated, refining the envelope function each time a sample is not accepted. Sampling from the piecewise envelope function can be done by inversion. Additional reading:
Unlike the rejection sampler (or its adaptive cousins), the Metropolis Hastings (MH) algorithm generates correlated samples from the distribution of interest. MH is an example of a Markov-Chain Monte Carlo technique; the ‘Markov’ indicates that each iteration of the algorithm depends on the previous state, forming a Markov-Chain. Both the rejection algorithm and MH are Monte-Carlo techniques in that they use random samples to obtain a result. Instead of generating samples from a single proposal distribution and accepting or rejecting them, the MH algorithm begins at an initial point, \(x_0\), and proposes a new state using a distribution which depends on \(x_0\). This updated state is then either accepted, in which case the chain moves to new state \(x_1\), or rejected, in which case it remains at \(x_0\).
The step-by-step instructions for the algorithm in the scalar case can be written as follows (a slightly different summary is given on Wikipedia):
Step 3 often confuses students, but it’s as simple as generating a random uniform variable and comparing it to \(a\): \(P(u < a) = a\). Also, we can omit the special check to see if \(a\) is greater than 1. This is required mathematically, because it makes no sense to accept a value with probability greater than one. Algorithmically, \(u\) will always be less than one, so \(u < a\) will cause us to accept \(x_1\) when \(a > 1\) automatically.
Stuff to note:
Unlike adaptive rejection sampling, we don’t require that the density of interest is log-concave. We also don’t need to find an appropriate envelope function, such as in rejection sampling. Instead, we draw on the theory of stochastic processes to construct an algorithm with the appropriate [stationary distribution] (specifically, a Markov process ), and then draw many samples using it.
Defining a Markov process is trivial - we’ve already done so with the random-walk examples. All we need to define the process is an update rule: \(P(x_{t+1}| x_t)\) (written here in terms of a discrete time index). Specially constructed Markov processes, however, will converge to particular distributions. Consider the following example of Gaussian autocorrelation:
# Stationary Gaussian Time Series:
N <- 10000
rho <- 0.25
X <- numeric(N)
X[1] <- 0
for (i in 2:N){
X[i] = rho*X[i-1] + rnorm(1,0,1)
}
plot(X)
hist(X)
qqnorm(X)
qqline(X)
This section is summarized from here.
Detailed Balance: The probability \(P(X'|X)P(X) = P(X|X')P(X')\) for all pairs of states, \((X,X')\)
Ergodicity: Characteristic of states, which requires that the process moving forward is aperiodic and positive recurrent.
Aperiodic: Does not return to the same state deterministically (fixed intervals)
Positive Recurrent: Expected number of steps for returning to the same state is finite.
These properties are defined for discrete-space Markov processes, but can be easily generalized to continuous space processes via \(\epsilon\)-discritization. Additional Reading 1, Additional Reading 2. We’re interested in these because a Markov process has a stationary distribution \(f(x)\) if:
Exercise: look at the Wikipedia derivation of the MH algorithm. What is an example of \(g\) which will not produce a stationary chain?
A simple version of this algorithm is implemented in the scalar case in the code below:
mh_scalar <- function(x0, f, g, g.sample, log = TRUE){
x1 <- g.sample(x0)
if (log){
a <- (f(x1) - f(x0)) + g(x1, x0) - g(x0, x1)
u <- log(runif(1,0,1))
} else{
a <- (f(x1)/f(x0))*(g(x1, x0)/g(x0, x1))
u <- runif(1,0,1)
}
if (u < a){
return(x1)
}
return(x0)
}
In our example, we can apply this function as follows:
f <- function(x){
0.25*dnorm(x, mean = 3, sd =0.5) +
0.75*dnorm(x, mean = -3, sd = 3)
}
# Initial value
x0 <- 0
# Proposal function
g.s <- function(from, sd_prop = 1){
rnorm(1, mean = from, sd = sd_prop)
}
g <- function(from, to, sd_prop = 1){
dnorm(to, from, sd_prop)
}
sampleMH <- numeric(5000)
sampleMH[1] <- x0
for (i in 2:length(sampleMH)){
sampleMH[i] <- mh_scalar(sampleMH[i-1], f, g, g.s,
log = FALSE)
}
plot(sampleMH, type = "l", main = "Samples are clearly correlated",
xlab = "Iteration", ylab = "x value", xlim = c(0,100))
hist(sampleMH, main = "The Marginal Distribution Looks OK", breaks = 20)
Exercise: Add a MH implementation to the ObjectExamples package
Your task is to implement the MH algorithm for the multivariate case. Complete the following function definitions, and demonstrate their use with a custom 5 dimensional function of your choosing. Please provide your output in addition to your code.
# Single Metropolis Hastings Update
MH_update <- function(x0, f, g, g.s, log = FALSE){
# Multivariate version of the MH code given previously.
}
# Metropolis Hastings Algorithm
MH <- function(n_iterations, x0, f, g, g.s, log = FALSE){
# Should return an n*p matrix, where p is the length of x0
}