Chapter 9 - Markov Chain Monte Carlo

This week 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.

Finally, upon completion, name your final output .html file as: Xinyi Zhu_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

8-1. 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 distribution of sigma. Visualize the posterior distribution of sigma for both models. Do not use a ‘pairs’ plot. Does the different prior have any detectable influence on the posterior distribution of sigma? Why or why not?

library(usethis)
library(devtools)
library(bayesplot)
library(ggplot2)
library(tibble)
library(rethinking)
library(dplyr)
library(dagitty)
library(tidyr)
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 )

m1 <- 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( m1 , depth=2 )
##             mean          sd        5.5%       94.5%
## a[1]   0.8865623 0.015675420  0.86151000  0.91161470
## a[2]   1.0505706 0.009936431  1.03469028  1.06645095
## b[1]   0.1324785 0.074203226  0.01388741  0.25106958
## b[2]  -0.1425759 0.054748460 -0.23007452 -0.05507729
## sigma  0.1094922 0.005935035  0.10000683  0.11897750
m1_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(m1_unif , depth=2)
##             mean          sd        5.5%       94.5%
## a[1]   0.8864453 0.015678605  0.86138790  0.91150278
## a[2]   1.0505887 0.009938605  1.03470491  1.06647253
## b[1]   0.1323366 0.074218825  0.01372061  0.25095264
## b[2]  -0.1425163 0.054760286 -0.23003385 -0.05499882
## sigma  0.1095165 0.005938316  0.10002593  0.11900708
pairs(m1)

pairs(m1_unif)

8-2. Modify the terrain ruggedness model again. This time, change the prior for b[cid] to dexp(0.3). Plot the joint posterior. Do not use a ‘pairs’ plot. What does this do to the posterior distribution? Can you explain it?

m2_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(m2_exp , depth=2)
##             mean          sd        5.5%       94.5%
## a[1]   0.8865576 0.015677647  0.86150168  0.91161350
## a[2]   1.0505598 0.009937879  1.03467718  1.06644248
## b[1]   0.1325041 0.074213399  0.01389677  0.25111146
## b[2]  -0.1425696 0.054756218 -0.23008059 -0.05505856
## sigma  0.1095082 0.005937208  0.10001940  0.11899701
pairs(m2_exp)

8-3. Re-estimate one of the Stan models from the chapter, but at different numbers (at least 5) 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?

formula <- 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( m2_exp , depth=2 )
##             mean          sd        5.5%       94.5%
## a[1]   0.8865576 0.015677647  0.86150168  0.91161350
## a[2]   1.0505598 0.009937879  1.03467718  1.06644248
## b[1]   0.1325041 0.074213399  0.01389677  0.25111146
## b[2]  -0.1425696 0.054756218 -0.23008059 -0.05505856
## sigma  0.1095082 0.005937208  0.10001940  0.11899701

8-4. 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 'anon_model' NOW (CHAIN 1).
## Chain 1: 
## Chain 1: Gradient evaluation took 1e-05 seconds
## Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0.1 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.009 seconds (Warm-up)
## Chain 1:                0.015 seconds (Sampling)
## Chain 1:                0.024 seconds (Total)
## Chain 1:
p=precis(mp)

traceplot(mp)

Compare the samples for the parameters a and b. Plot the trace plots. 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?

8-5. Recall the divorce rate example from Chapter 5. Repeat that analysis, using ulam this time, fitting models m5.1, m5.2, and m5.3. Use compare to compare the models on the basis of WAIC or PSIS. To use WAIC or PSIS with ulam, you need add the argument log_log=TRUE. Explain the model comparison results.

data(WaffleDivorce)
df1 <- WaffleDivorce

# standardize variables
df1$D <- standardize( df1$Divorce )
df1$M <- standardize( df1$Marriage )
df1$A <- standardize( df1$MedianAgeMarriage )

d_trim <- list(D = df1$D, M = df1$M, A = df1$A)

m5a <- ulam(
  alist(
    D ~ dnorm(mu, sigma),
    mu <- a + bA * A,
    a ~ dnorm(0, 0.2),
    bA ~ dnorm(0, 0.5),
    sigma ~ dexp(1)
  ),
  data = d_trim,
  chains = 4, 
  cores = 4,
  log_lik = TRUE
)
m5b <- ulam(
  alist(
    D ~ dnorm(mu, sigma),
    mu <- a + bM * M,
    a ~ dnorm(0, 0.2),
    bM ~ dnorm(0, 0.5),
    sigma ~ dexp(1)
  ),
  data = d_trim,
  chains = 4, 
  cores = 4,
  log_lik = TRUE 
)
m5c <- ulam(
  alist(
    D ~ dnorm(mu, sigma),
    mu <- a + bA * A + bM * M,
    a ~ dnorm(0, 0.2),
    bA ~ dnorm(0, 0.5),
    bM ~ dnorm(0, 0.5),
    sigma ~ dexp(1)
  ),
  data = d_trim,
  chains = 4, 
  cores = 4,
  log_lik = TRUE 
)
set.seed(77)
compare( m5a , m5b , m5c , func=WAIC )
##         WAIC        SE     dWAIC       dSE    pWAIC       weight
## m5a 125.4690 12.503267  0.000000        NA 3.481577 0.7279086669
## m5c 127.4426 12.757910  1.973635 0.7050609 4.726972 0.2713360554
## m5b 139.2106  9.747585 13.741691 9.1314436 2.903530 0.0007552777