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.

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

9-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. Visualize the posteriors for both models. Does the different prior have any detectible influence on the posterior distribution of sigma? Why or why not?

library(tidybayes)

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)

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 ...
## Exponential prior for sigma
m8.3 <- ulam(
  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=dat_slim , chains=4 , cores=4)

precis(m8.3 , depth=2)
##             mean          sd       5.5%       94.5%    n_eff     Rhat4
## a[1]   0.8861515 0.015435511  0.8619230  0.91072848 3451.869 0.9982645
## a[2]   1.0506345 0.010311379  1.0346660  1.06702301 3367.157 0.9994278
## b[1]   0.1307376 0.074652115  0.0114436  0.24955191 3065.927 0.9984599
## b[2]  -0.1431357 0.054990057 -0.2284834 -0.05621833 2648.326 0.9990563
## sigma  0.1116057 0.006122552  0.1021414  0.12187065 2639.895 0.9997524
pairs(m8.3)

## Uniform prior for sigma
m9.1 <- ulam(
  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=dat_slim , chains=4 , cores=4)

precis(m9.1 , depth=2)
##             mean          sd        5.5%      94.5%    n_eff     Rhat4
## a[1]   0.8862011 0.015990392  0.86053292  0.9115044 2981.192 0.9993020
## a[2]   1.0506426 0.009720241  1.03525498  1.0666664 3738.067 0.9998099
## b[1]   0.1328565 0.076131369  0.01121257  0.2583158 2791.995 0.9986555
## b[2]  -0.1409603 0.058388020 -0.23468383 -0.0494029 2323.854 1.0012248
## sigma  0.1115542 0.006099111  0.10216818  0.1214367 2398.923 0.9988090
pairs(m9.1)

# In comparison, parameter estimations are very similar. Except for sigma, which has a higher n_eff in the uniform-prior model, the individual model outputs are also quite close, with all parameter estimates in the model with the exponential-prior model on sigma being significantly higher. As a result, we discover that while different priors impact n_eff, posterior distributions are unaffected.

Plot_df <- data.frame(
  Posteriors = c(
    extract.samples(m8.3, n = 1e4)$sigma,
    extract.samples(m9.1, n = 1e4)$sigma
  ),
  Name = rep(c("Exp", "Uni"), each = 1e4),
  Model = rep(c("m8.3", "m9.1"), each = 1e4)
)

ggplot(Plot_df, aes(y = Model, x = Posteriors)) +
  stat_halfeye() +
  labs(x = "Parameter Estimate", y = "Model") +
  theme_bw()

# In the posterior, there are almost no distinctions. There seemed to have been so much data that the previous was simply overloaded. The uniform prior, on the other hand, produces a broader and less peaky posterior, indicating more uncertainty.

9-2. 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.2 <- ulam(
  alist(
    log_gdp_std ~ dnorm( mu , sigma ) ,
    mu <- a[cid] + b[cid]* (rugged_std-0.215) ,
    a[cid] ~ dnorm(1,0.1),
    b[cid] ~ dexp(0.3),
    sigma ~ dexp(1)
  ) , 
  data=dat_slim , chains=4 , cores=4)

precis(m9.2 , depth=2)
##             mean          sd        5.5%      94.5%    n_eff     Rhat4
## a[1]  0.88714899 0.016272447 0.861114945 0.91299934 1573.955 1.0007477
## a[2]  1.04791074 0.010406040 1.031171766 1.06417370 1789.536 1.0006745
## b[1]  0.15112668 0.074062200 0.037380100 0.27430162 1485.525 0.9992817
## b[2]  0.01857779 0.017640228 0.001218088 0.05168614 1564.229 1.0036460
## sigma 0.11421694 0.006450127 0.104124473 0.12497579 1570.908 1.0005918
pairs(m9.2)

# We can see that there isn't much of a difference; nevertheless, the most significant difference is in the b parameter, which appears to have fewer samples and no longer accepts negative values.

9-3. 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?

# use fixed start values for comparability of runs
start <- list(a = c(1, 1), b = c(0, 0), sigma = 1)

m9.3 <- ulam(
  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 = dat_slim,
  start = start,
  chains = 4, 
  cores = 4,
  iter = 100
)

# define warmup values to run through
warm_list <- c(5, 10, 100, 500, 1000) 

# first make matrix to hold n_eff results
n_eff <- matrix(NA, nrow = length(warm_list), ncol = 5) 

for (i in 1:length(warm_list)) { # loop over warm_list and collect n_eff
  w <- warm_list[i]
  m_temp <- ulam(m9.3, chains = 4, cores = 4, iter = 1000 + w, warmup = w, start = start)
  n_eff[i, ] <- precis(m_temp, 2)$n_eff
}

colnames(n_eff) <- rownames(precis(m_temp, 2))
rownames(n_eff) <- warm_list
n_eff # columns show parameters, rows show n_eff
##             a[1]      a[2]        b[1]        b[2]       sigma
## 5       5.546765   38.0989    2.420818    2.611865    2.703547
## 10   1878.211774 2682.3100  213.900252  430.195486  332.103828
## 100  4431.869666 4647.0430 1786.434843 2754.477638 2420.691226
## 500  5363.896053 5826.7068 4735.284496 4754.550872 4953.017635
## 1000 5227.052981 6360.7375 4850.814742 5331.567853 5330.839680
# As can be seen, n_eff does not vary significantly after 10 warmup samples. In this situation, a warmup of 10 would suffice.

9-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 'bcf56ee89f6cf2a4224a4139ff01c7d4' NOW (CHAIN 1).
## Chain 1: 
## Chain 1: Gradient evaluation took 0 seconds
## Chain 1: 1000 transitions using 10 leapfrog steps per transition would take 0 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.035 seconds (Warm-up)
## Chain 1:                0.036 seconds (Sampling)
## Chain 1:                0.071 seconds (Total)
## Chain 1:
precis(mp , depth=2)
##         mean        sd      5.5%    94.5%    n_eff    Rhat4
## a 0.14066036 0.9968023 -1.459209 1.700533 246.0602 1.003622
## b 0.09169595 3.7715724 -4.132354 3.750886 213.7985 1.000287
pairs(mp)

traceplot(mp)
## [1] 1000
## [1] 1
## [1] 1000
# The prior is about 0 and the spread is between 2 and -2, thus plot 'a' should be a normal distribution. Plot 'b' depicts a Cauchy distribution with several extreme values ranging from 30 to -40.

post <- extract.samples(mp)
par(mfrow = c(1, 2))

dens(post$a)
curve(dnorm(x, 0, 1), from = -4, to = 4, add = T, lty = 2)
legend("topright", lty = c(1, 2), legend = c("Sample", "Exact density"), bty = "n")
mtext("Normal")
dens(post$b, col = "red", xlim = c(-10, 10))
curve(dcauchy(x, 0, 1),
  from = -10, to = 10, add = T, lty = 2,
  col = "red"
)
mtext("Cauchy")

# The normal distribution, as can be seen, has been reconstructed well but the cauchy distribution hasn't.

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?

9-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.

# load data and copy
data(WaffleDivorce)
d <- WaffleDivorce

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

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

m5.1 <- 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 # this is needed to get the terms for calculating PSIS or WAIC instead log_log
)

m5.2 <- 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 # this is needed to get the terms for calculating PSIS or WAIC instead log_log
)

m5.3 <- 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 # this is needed to get the terms for calculating PSIS or WAIC instead log_log
)

set.seed(77)
compare( m5.1 , m5.2 , m5.3 , func=WAIC )
##          WAIC        SE    dWAIC       dSE    pWAIC       weight
## m5.1 125.6718 12.552074  0.00000        NA 3.578269 0.6860406902
## m5.3 127.2399 12.586524  1.56812 0.7958371 4.574666 0.3132109152
## m5.2 139.3133  9.824634 13.64152 9.1051690 2.948397 0.0007483946
# Model m5.1 with only median age at marriage as a predictor performs best, but is not really distinguishable from model m5.3. However, the model with marriage rate only, m5.2 clearly performs worse than both.