Gibbs Sampling and Metropolis within Gibbs

In the previous lab and lecture, we explored several different implementations of Metropolis-Hastings sampling. For your reference, this work is catalogued in the JAMHS package on the Uiowa GitHub site. We will be using this library in this lab.

Recap

While the Metropolis-Hastings algorithm is an indispensible tool for sampling from arbitrary distributions, a number of you have already observed the difficulty of sampling from higher dimensional distributions.

In two dimensions, the mixture problem works out well:

library(Rcpp)
## Warning: package 'Rcpp' was built under R version 3.4.2
library(RcppXPtrUtils)
## Warning: package 'RcppXPtrUtils' was built under R version 3.4.2
library(JAMHS)

f.cpp.ptr <- cppXPtr("
                     double f(Rcpp::NumericVector x){
                        double out = 0.0;
                        for (int i = 0; i < x.size(); i++){
                          out += std::log(0.25*R::dnorm(x[i], 3.0, 0.5, 0) + 0.75*R::dnorm(x[i], -3.0, 3.0, 0));
                        }
                        return(out);
                     }
                     ")

g.cpp.ptr <- cppXPtr("
                     double g(Rcpp::NumericVector from, 
                              Rcpp::NumericVector to){
                              double out = 0.0;
                              int i;
                              for (i = 0; i < from.size(); i++){
                                out += R::dnorm(to[i], from[i], 1.0, 1);
                              }
                            return(out);
                          }
                     ")

g.s.cpp.ptr <- cppXPtr("
                       Rcpp::NumericVector g_sample(Rcpp::NumericVector x0){
                          Rcpp::NumericVector out = Rcpp::NumericVector(x0.size());
                          int i;
                          for (i = 0; i < x0.size(); i++){
                            out[i] = x0[i] +  R::rnorm(0.0, 1.0);
                          }
                          return(out);
                       }
                       ")



## Example using C++ functions
RC_obj_cpp_ptr <- create_CppClassMH(param = c(0,0), 
                                    f = f.cpp.ptr, 
                                    g=g.cpp.ptr, 
                                    g.sample=g.s.cpp.ptr,
                                    log=TRUE,
                                    verbose=FALSE)



system.time({result <- RC_obj_cpp_ptr$sample(10000, 
                                         trace = FALSE)})
## Warning, thinning not implemented
##    user  system elapsed 
##    0.02    0.00    0.02
system.time({result <- RC_obj_cpp_ptr$sample(100000, 
                                         trace = TRUE)})
##    user  system elapsed 
##    0.14    0.00    0.14
plot(density(result[,1], bw = 0.75), xlim = c(-17,15))
lines(density(result[,2], bw = 0.75), col = "red")
legend(x=6,y=0.1, legend = c("Dim 1", "Dim 2"), lty = c(1,1), col = c(1,2))

rm(RC_obj_cpp_ptr)

As the number of dimensions increases, however, things start to break down:

## Example using C++ functions
RC_obj_cpp_ptr <- create_CppClassMH(param = rep(0,100), 
                                    f = f.cpp.ptr, 
                                    g=g.cpp.ptr, 
                                    g.sample=g.s.cpp.ptr,
                                    log=TRUE,
                                    verbose=TRUE)
## MH Sampler of dimension 100, log=1
system.time({result <- RC_obj_cpp_ptr$sample(10000, 
                                         trace = FALSE)})
## Warning, thinning not implemented...1000
## ...2000
## ...3000
## ...4000
## ...5000
## ...6000
## ...7000
## ...8000
## ...9000
## ...10000
##    user  system elapsed 
##    0.56    0.00    0.57
system.time({result <- RC_obj_cpp_ptr$sample(100000, 
                                         trace = FALSE)})
## Warning, thinning not implemented...11000
## ...12000
## ...13000
## ...14000
## ...15000
## ...16000
## ...17000
## ...18000
## ...19000
## ...20000
## ...21000
## ...22000
## ...23000
## ...24000
## ...25000
## ...26000
## ...27000
## ...28000
## ...29000
## ...30000
## ...31000
## ...32000
## ...33000
## ...34000
## ...35000
## ...36000
## ...37000
## ...38000
## ...39000
## ...40000
## ...41000
## ...42000
## ...43000
## ...44000
## ...45000
## ...46000
## ...47000
## ...48000
## ...49000
## ...50000
## ...51000
## ...52000
## ...53000
## ...54000
## ...55000
## ...56000
## ...57000
## ...58000
## ...59000
## ...60000
## ...61000
## ...62000
## ...63000
## ...64000
## ...65000
## ...66000
## ...67000
## ...68000
## ...69000
## ...70000
## ...71000
## ...72000
## ...73000
## ...74000
## ...75000
## ...76000
## ...77000
## ...78000
## ...79000
## ...80000
## ...81000
## ...82000
## ...83000
## ...84000
## ...85000
## ...86000
## ...87000
## ...88000
## ...89000
## ...90000
## ...91000
## ...92000
## ...93000
## ...94000
## ...95000
## ...96000
## ...97000
## ...98000
## ...99000
## ...100000
## ...101000
## ...102000
## ...103000
## ...104000
## ...105000
## ...106000
## ...107000
## ...108000
## ...109000
## ...110000
##    user  system elapsed 
##    5.35    0.00    5.35
plot(density(result[,1], bw = 0.75), xlim = c(-17,15))
lines(density(result[,20], bw = 0.75), col = "red")
legend(x=6,y=0.1, legend = c("Dim 1", "Dim 2"), lty = c(1,1), col = c(1,2))

rm(RC_obj_cpp_ptr)

If we take enough samples, the result should eventually converge (assuming the conditions we discussed previously), but it may be impractical to do so. A number of strategies exist for improving upon a simple application of Metropolis Hastings. Today, we’ll focus on Gibbs Sampling

Gibbs Sampling

Reading Material:

Consider for a moment the following likelihood, defined for independent \({bf{Y}}_i\):

\({\bf{Y}}_i \sim \mathcal{N}\left(\begin{bmatrix}\mu_1\\ \mu_2 \end{bmatrix}, \begin{bmatrix}\sigma_1, \sigma_{12}\\ \sigma_{12}, \sigma_2 \end{bmatrix} \right), i=1,...,n\)

For this problem, we specify the following prior distributions:

  • \(\mu_1 \sim N(0,1)\)
  • \(\mu_2 \sim N(0,1)\)
  • \(\sigma_1 \sim \mbox{gamma}(1,0.2)\)
  • \(\sigma_12 \sim \mbox{gamma}(1,1)\)
  • \(\sigma_2 \sim \mbox{gamma}(1,0.2)\)

Using Bayes’ Rule, and independence among these prior distributions we see that:

\(P(\mu_1, \mu_2, \sigma_1, \sigma_{12}, \sigma{2} | {\bf Y}) \propto P({\bf{Y}}|\mu_1, \mu_2, \sigma_1, \sigma_{12}, \sigma{2})P(\mu_1)P(\mu_2)P(\sigma_1)P(\sigma_{12})P(\sigma{2})\)

Based on our work last time, we can straightforwardly use MH to sample from this posterior. Let’s simulate some test data to try it out:

library(mvtnorm)
true_mu_1 <- -5
true_mu_2 <- 5
true_sigma_1 <- 2
true_sigma_12 <- 0.5
true_sigma_2 <- 3

Sigma <- matrix(c(true_sigma_1, true_sigma_12, true_sigma_12, true_sigma_2), nrow = 2)

Y <- rmvnorm(n = 1000, mean = c(true_mu_1, true_mu_2), sigma = Sigma)

# Positively correlated bivariate normal
plot(Y[,1], Y[,2])

We next need to define f, the kernel of our posterior distribution, along with g and the function to propose new parameter values g_sample. We’ll use the reference class version of the MH sampler, since our C++ code in JAMHS is currently designed for self contained \(f\) and \(g\) functions. When we need to access large data structures to evaluate distributions, we need to think carefully about how that memory is managed.

f <- function(par){
  mu <- par[1:2]
  Sigma <- matrix(par[c(3,4,4,5)], nrow = 2)
  # References global Y:
  lik <- sum(dmvnorm(Y, mean = mu, sigma = Sigma, log = TRUE))
  prior <- sum(dnorm(mu, mean = rep(0, length(mu)), 
              sd = rep(1, length(mu)), log = TRUE)) + 
           sum(dgamma(Sigma[c(1,3)], shape = 1, rate = 0.2, log = TRUE)) +  
           dgamma(Sigma[2], shape = 1, rate = 1, log = TRUE)
  lik+prior
}

# Proposal function
g.s <- function(from, sd_prop = 0.5){
  
  rnorm(rep(1, length(from)), mean = from, sd = rep(sd_prop, length(from)))
}
g <- function(from, to, sd_prop = 0.5){
  sum(dnorm(to, from, rep(sd_prop, length(from)), log = TRUE))
}


## Example using R functions
RC_obj <- create_RefClassMH(param = c(0,0,1,0,1), 
                  f = f, 
                  g=g, 
                  g.sample=g.s,
                  log=TRUE,
                  verbose=TRUE)

system.time({result <- RC_obj$sample(200, 
             trace = TRUE)})
##    user  system elapsed 
##    0.12    0.00    0.12
plot(result$samples[,1], main = "mu 1")

plot(result$samples[,2], main = "mu 2")

plot(result$samples[,3], main = "sigma 1")

plot(result$samples[,4], main = "sigma 12")

plot(result$samples[,5], main = "sigma 2")

This clearly works, but we’re already seeing a pretty low acceptance rate (and the R version is certainly slow).

We might naturally think that the mean parameters are naturally behaved in similar ways, and the covariance parameters are similarly related. Fortunately, Gibbs Sampling provides an intuitive way to tackle these parameters separately. Such sampling allows us to avoid the problem that as the dimension increases, we become less likely to produce a multivariate proposal which falls into a region of high posterior probability.

Consider that we can decompose \(P(\mu_1, \mu_2, \sigma_1, \sigma_{12}, \sigma{2} | {\bf Y})\) into \(P(\mu_1, \mu_2 | \sigma_1,\sigma_{12}, \sigma{2}, {\bf Y})P(\sigma_1, \sigma_{12}, \sigma{2}|{\bf Y})\). This first component is known as the ‘full-conditional’ distribution of \(\boldsymbol{\mu}\), since it’s the distribution of \(\boldsymbol{\mu}\) conditional on all other terms in the model. Intuitively, if we have sample values of \(\sigma_1, \sigma_{12}, \mbox{ and } \sigma_2\) from the posterior distribution, and we generate a sample based on them from this full conditional, the whole joint sample can be considered to have been drawn from the posterior distribution. The same would be true in reverse, when considering the full conditional distribution of some or all of the covariance parameters and a posterior sample of the rest of the parameters.

This property can be used to show that iteratively sampling from the full conditional distributions, updated at each step to reflect the new parameter values, will asymptotically provide a sample from the joint posterior distribution of all model parameters. While there are innumerable variants (and we’ve already combined standard Gibbs Sampling with ‘Blocked Gibbs Sampling’ by considering bivariate full conditionals), at its core Gibbs Sampling is one of the most commonly applied tools in modern Bayesian inference.

Algorithm For the Above Problem

  1. Choose initial values: \(\boldsymbol{\mu}^{(0)} = (\mu_1^{(0)}, \mu_2^{(0)}), \boldsymbol{\sigma}^{(0)} = (\sigma_1^{(0)}, \sigma_{12}^{(0)}, \sigma_2^{(0)})\)
  2. For \(i\) in \(1,...,N\) do:
  3. Generate \(\boldsymbol{\mu}^{(i)} \sim P(\boldsymbol{\mu} | \boldsymbol{\sigma}^{(i-1)}, {\bf Y})\)
  4. Generate \(\boldsymbol{\sigma}^{(i)} \sim P(\boldsymbol{\sigma} | \boldsymbol{\mu}^{(i)}, {\bf Y})\)
  5. end

In steps 2 and 3 from the above algorithm, we can accomplish the sampling using a Metropolis Hastings step, starting at \(\boldsymbol{\mu}^{(i-1)}\) and \(\boldsymbol{\sigma}^{(i-1)}\), respectively, and proposing new values \(\boldsymbol{\mu}^{(i)}\) and \(\boldsymbol{\sigma}^{(i)}\).

Assignment

  1. Implement a Gibbs Sampler for this multivariate normal problem, and demonstrate that it converges to the same distribution as the single-block Metropolis Hastings previously explored.
  2. (Extra Credit): Implement the Metropolis Hastings approach to this problem using C++.