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 <- numeric(n)
accepted = 0
while (accepted < n){
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"))
}
}
}
out
}
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)
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. Adaptive extensions of the algorithm exist which can improve on these properties somewhat. In addition, the samples generated by the algorithm are not correlated; a distinct advantage over the technique we’ll cover next.
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.
Also note that the ratio in 2 will cause the normalizing constants to cancel; we need not concern ourselves with anything which is constant as a function of \(x\), allowing us to use the kernel of the posterior distribution, rather than a fully specified probability distribution. This can often greatly simplify computation. Finally, note that the comparison in 3 and the fractions in 2 can be computed on either the density or log-density scale. Frequently for moderately sized problems, we are obliged to work with log densities for reasons of numerical stability.
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:
# 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(1000)
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")
hist(sampleMH, main = "The Marginal Distribution Looks OK")
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
}