Chapter 9 - Markov Chain Monte Carlo

This chapter has been an informal introduction to Markov chain Monte Carlo (MCMC) estimation. The goal has been to introduce the purpose and approach MCMC algorithms. The major algorithms introduced were the Metropolis, Gibbs sampling, and Hamiltonian Monte Carlo algorithms. Each has its advantages and disadvantages. The ulam function in the rethinking package was introduced. It uses the Stan (mc-stan.org) Hamiltonian Monte Carlo engine to fit models as they are defined in this book. General advice about diagnosing poor MCMC fits was introduced by the use of a couple of pathological examples.

Place each answer inside the code chunk (grey box). The code chunks should contain a text response or a code that completes/answers the question or activity requested. Make sure to include plots if the question requests them. Problems are labeled Easy (E), Medium (M), and Hard(H).

Finally, upon completion, name your final output .html file as: YourName_ANLY505-Year-Semester.html and publish the assignment to your R Pubs account and submit the link to Canvas. Each question is worth 5 points.

Questions

9E1. Which of the following is a requirement of the simple Metropolis algorithm?

  1. The parameters must be discrete.
  2. The likelihood function must be Gaussian.
  3. The proposal distribution must be symmetric.
# Answer is 3. The proposal distribution must be symmetric

9E2. Gibbs sampling is more efficient than the Metropolis algorithm. How does it achieve this extra efficiency? Are there any limitations to the Gibbs sampling strategy?

# Gibbs sampling uses conjugate priors. It can make smarter proposals which results it being more efficient.  The limitation is that it this approach may not be good from a scientific perspective. COmplex models are also challenging.

9E3. Which sort of parameters can Hamiltonian Monte Carlo not handle? Can you explain why?

# HMC cannot handle discrete parameters by construction. HMC is derived by adding momentum. It requires the Hessian to be non-negative. This requires a continuous smooth function. 

9E4. Explain the difference between the effective number of samples, n_eff as calculated by Stan, and the actual number of samples.

#Effective number of samples: gives an estimate of the number of samples that are independent
# n_eff as calculated by Stan: estimates effective number of samplesto estimate the posterior mean
# Actual number of samples: samples we use for accurate inference.

9E5. Which value should Rhat approach, when a chain is sampling the posterior distribution correctly?

# R-hat should be close to 1. It means the inner variance and outer variance between chains is roughly the same. We can expect inference to not be broken.

9E6. Sketch a good trace plot for a Markov chain, one that is effectively sampling from the posterior distribution. What is good about its shape? Then sketch a trace plot for a malfunctioning Markov chain. What about its shape indicates malfunction?

library(rethinking)
data(rugged)
d <- rugged
d$log_gdp <- log(d$rgdppc_2000)
dd <- d[ complete.cases(d$rgdppc_2000) , ]
dd$log_gdp_std <- dd$log_gdp / mean(dd$log_gdp)
dd$rugged_std <- dd$rugged / max(dd$rugged)
dd$cid <- ifelse( dd$cont_africa == 1 , 1 , 2)

datalist <- list(
                log_gdp_std = dd$log_gdp_std,
                rugged_std = dd$rugged_std,
                cid = as.integer( dd$cid ))


m9e6a <- ulam(
  alist(
    logGDP_std ~ dnorm(mu,sigma),
    mu<-a[cid] + b[cid]*(rugged_std-0.215),
    a[cid]~dnorm(1,0.1),
    b[cid]~dnorm(0,0.3),
    sigma~dunif(0,1)
  ), data=datalist, chains=4, cores=4
)
## Warning: There were 1005 transitions after warmup that exceeded the maximum treedepth. Increase max_treedepth above 10. See
## http://mc-stan.org/misc/warnings.html#maximum-treedepth-exceeded
## Warning: There were 3 chains where the estimated Bayesian Fraction of Missing Information was low. See
## http://mc-stan.org/misc/warnings.html#bfmi-low
## Warning: Examine the pairs() plot to diagnose sampling problems
## Warning: The largest R-hat is 3.85, indicating chains have not mixed.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#r-hat
## Warning: Bulk Effective Samples Size (ESS) is too low, indicating posterior means and medians may be unreliable.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#bulk-ess
## Warning: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#tail-ess
precis(m9e6a , depth = 2)
##                    mean           sd          5.5%        94.5%       n_eff
## logGDP_std 9.894370e-01 1.190991e-01  8.663437e-01 1.148627e+00    2.002007
## a[1]       9.894370e-01 1.190991e-01  8.663433e-01 1.148627e+00    2.002007
## a[2]       9.894370e-01 1.190991e-01  8.663434e-01 1.148627e+00    2.002007
## b[1]       7.510162e-09 1.079948e-06 -1.694289e-06 1.684559e-06 1446.810860
## b[2]       3.392034e-09 7.991555e-07 -1.266592e-06 1.279012e-06 1896.864201
## sigma      1.475825e-06 4.493748e-07  9.682848e-07 2.261350e-06    2.414541
##                  Rhat4
## logGDP_std 1012.275632
## a[1]       1012.235978
## a[2]       1012.245975
## b[1]          1.003436
## b[2]          1.001077
## sigma         4.912275
traceplot(m9e6a)
## [1] 1000
## [1] 1
## [1] 1000

9E7. Repeat the problem above, but now for a trace rank plot.

# malfunctioning chain
m9e6b<-ulam(
  alist(
    y ~ dnorm(mu,sigma),
    mu<-alpha,
    alpha ~ dnorm(0,1000),
    sigma~dexp(0.0001)
  ),data=list(y=c(-1,1)),chains=4,cores=4
)
## Warning: There were 315 divergent transitions after warmup. See
## http://mc-stan.org/misc/warnings.html#divergent-transitions-after-warmup
## to find out why this is a problem and how to eliminate them.
## Warning: Examine the pairs() plot to diagnose sampling problems
## Warning: The largest R-hat is 1.25, indicating chains have not mixed.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#r-hat
## Warning: Bulk Effective Samples Size (ESS) is too low, indicating posterior means and medians may be unreliable.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#bulk-ess
## Warning: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#tail-ess
traceplot(m9e6b)
## [1] 1000
## [1] 1
## [1] 1000

9M1. Re-estimate the terrain ruggedness model from the chapter, but now using a uniform prior for the standard deviation, sigma. The uniform prior should be dunif(0,1). Visualize the priors. Use ulam to estimate the posterior. Visualize the posteriors for both models. Does the different prior have any detectible influence on the posterior distribution of sigma? Why or why not?

data(rugged)
d <- rugged
d$log_gdp <- log(d$rgdppc_2000)
dd <- d[ complete.cases(d$rgdppc_2000) , ]

dd$log_gdp_std <- dd$log_gdp/ mean(dd$log_gdp)
dd$rugged_std<- dd$rugged/max(dd$rugged)

dd$cid<-ifelse(dd$cont_africa==1,1,2)

m9.1 <- quap(
  alist(
    log_gdp_std ~ dnorm( mu , sigma ) ,
    mu <- a[cid] + b[cid]* (rugged_std-0.215) ,
    a[cid] ~ dnorm(1,0.1),
    b[cid] ~ dnorm(0,0.3),
    sigma ~ dexp(1)
  ) , 
  data=dd)

precis(m9.1 , depth=2)
##             mean          sd        5.5%       94.5%
## a[1]   0.8865636 0.015675718  0.86151077  0.91161642
## a[2]   1.0505679 0.009936623  1.03468724  1.06644853
## b[1]   0.1325056 0.074204550  0.01391242  0.25109882
## b[2]  -0.1425757 0.054749485 -0.23007596 -0.05507546
## sigma  0.1094943 0.005935322  0.10000849  0.11898008
pairs(m9.1)

m9.1_unif <- quap(
  alist(
    log_gdp_std ~ dnorm( mu , sigma ) ,
    mu <- a[cid] + b[cid]* (rugged_std-0.215) ,
    a[cid] ~ dnorm(1,0.1),
    b[cid] ~ dnorm(0,0.3),
    sigma ~ dunif(0,1)
  ) , 
  data=dd)

precis(m9.1 , depth=2)
##             mean          sd        5.5%       94.5%
## a[1]   0.8865636 0.015675718  0.86151077  0.91161642
## a[2]   1.0505679 0.009936623  1.03468724  1.06644853
## b[1]   0.1325056 0.074204550  0.01391242  0.25109882
## b[2]  -0.1425757 0.054749485 -0.23007596 -0.05507546
## sigma  0.1094943 0.005935322  0.10000849  0.11898008
pairs(m9.1_unif)

9M2. Modify the terrain ruggedness model again. This time, change the prior for b[cid] to dexp(0.3). What does this do to the posterior distribution? Can you explain it?

m9.3_exp <- quap(
  alist(
    log_gdp_std ~ dnorm(mu , sigma) ,
    mu <- a[cid] + b[cid]* (rugged_std-0.215) ,
    a[cid] ~ dnorm(1,0.1),
    b[cid] ~ dnorm(0,0.3),
    sigma ~ dexp(0.3)
  ) , 
  data=dd)

precis(m9.3_exp , depth=2)
##             mean          sd        5.5%       94.5%
## a[1]   0.8865686 0.015677865  0.86151232  0.91162484
## a[2]   1.0505683 0.009938000  1.03468550  1.06645119
## b[1]   0.1325036 0.074214300  0.01389482  0.25111239
## b[2]  -0.1425740 0.054756898 -0.23008608 -0.05506188
## sigma  0.1095096 0.005937401  0.10002050  0.11899873
pairs(m9.3_exp)

9M3. Re-estimate one of the Stan models from the chapter, but at different numbers of warmup iterations. Be sure to use the same number of sampling iterations in each case. Compare the n_eff values. How much warmup is enough?

dat_slim <- list(
                log_gdp_std = dd$log_gdp_std,
                rugged_std = dd$rugged_std,
                cid = as.integer( dd$cid ))
str(dat_slim)
## List of 3
##  $ log_gdp_std: num [1:170] 0.88 0.965 1.166 1.104 0.915 ...
##  $ rugged_std : num [1:170] 0.138 0.553 0.124 0.125 0.433 ...
##  $ cid        : int [1:170] 1 2 2 2 2 2 2 2 2 1 ...

9H1. Run the model below and then inspect the posterior distribution and explain what it is accomplishing.

mp <- ulam(
 alist(
   a ~ dnorm(0,1),
   b ~ dcauchy(0,1)
 ), data=list(y=1) , chains=1 )
## 
## SAMPLING FOR MODEL 'bcf56ee89f6cf2a4224a4139ff01c7d4' NOW (CHAIN 1).
## Chain 1: 
## Chain 1: Gradient evaluation took 0.001 seconds
## Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 10 seconds.
## Chain 1: Adjust your expectations accordingly!
## Chain 1: 
## Chain 1: 
## Chain 1: Iteration:   1 / 1000 [  0%]  (Warmup)
## Chain 1: Iteration: 100 / 1000 [ 10%]  (Warmup)
## Chain 1: Iteration: 200 / 1000 [ 20%]  (Warmup)
## Chain 1: Iteration: 300 / 1000 [ 30%]  (Warmup)
## Chain 1: Iteration: 400 / 1000 [ 40%]  (Warmup)
## Chain 1: Iteration: 500 / 1000 [ 50%]  (Warmup)
## Chain 1: Iteration: 501 / 1000 [ 50%]  (Sampling)
## Chain 1: Iteration: 600 / 1000 [ 60%]  (Sampling)
## Chain 1: Iteration: 700 / 1000 [ 70%]  (Sampling)
## Chain 1: Iteration: 800 / 1000 [ 80%]  (Sampling)
## Chain 1: Iteration: 900 / 1000 [ 90%]  (Sampling)
## Chain 1: Iteration: 1000 / 1000 [100%]  (Sampling)
## Chain 1: 
## Chain 1:  Elapsed Time: 0.06 seconds (Warm-up)
## Chain 1:                0.019 seconds (Sampling)
## Chain 1:                0.079 seconds (Total)
## Chain 1:
## Warning: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable.
## Running the chains for more iterations may help. See
## http://mc-stan.org/misc/warnings.html#tail-ess
traceplot(mp)
## [1] 1000
## [1] 1
## [1] 1000
#We find traceplot for A paramter to be normally distribured prior 0 and between +2 and -2

Compare the samples for the parameters a and b. Can you explain the different trace plots? If you are unfamiliar with the Cauchy distribution, you should look it up. The key feature to attend to is that it has no expected value. Can you connect this fact to the trace plot?