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. 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.
# 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 leverages information about the analytic form of likelihood and conjugate priors, so it can merge proposal and reject/accept steps.

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

# Hamiltonian Monte Carlo can not handle discrete parameter.
# Because it cannot glide through discrete parameters without slopes.

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

# N_effective aims to estimate the number of 'ideal' samples. Ideal samples are entirely uncorrelated. Due to way MCMC works each next sample is actually correlated with the previous one to some extent. 
# n_eff as calculted by Stan: an estimated of effective number of samples, for the purpose of estimating the posterior mean.
# The 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?

# Rhat should be close to 1. It reflects the fact that inner variance and outer variance between chains is roughly the same, so we could expect that inference is not broken (does't depend on the chain).

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?

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)
m9e6 <- 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(m9e6 , depth = 2)
##             mean          sd        5.5%      94.5%
## a[1]   0.8865614 0.015675672  0.86150866  0.9116142
## a[2]   1.0505740 0.009936592  1.03469342  1.0664546
## b[1]   0.1324659 0.074204394  0.01387294  0.2510589
## b[2]  -0.1425655 0.054749351 -0.23006558 -0.0550655
## sigma  0.1094940 0.005935282  0.10000826  0.1189797
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 ...

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

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). Use ulam to estimate the posterior. 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)
m2 <- 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(m2, depth=2)
##             mean          sd        5.5%       94.5%
## a[1]   0.8865696 0.015675357  0.86151740  0.91162189
## a[2]   1.0505709 0.009936381  1.03469067  1.06645118
## b[1]   0.1325168 0.074202842  0.01392631  0.25110725
## b[2]  -0.1425994 0.054748169 -0.23009751 -0.05510121
## sigma  0.1094916 0.005934960  0.10000640  0.11897683
pairs(m2)

m2_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(m2_unif , depth=2)
##             mean          sd        5.5%       94.5%
## a[1]   0.8865655 0.015680684  0.86150476  0.91162628
## a[2]   1.0505694 0.009939819  1.03468368  1.06645518
## b[1]   0.1325019 0.074227181  0.01387252  0.25113127
## b[2]  -0.1425731 0.054766691 -0.23010089 -0.05504539
## sigma  0.1095299 0.005940148  0.10003637  0.11902338
pairs(m2_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?

m3 <- 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( m3 , depth=2 )
##             mean          sd        5.5%       94.5%
## a[1]   0.8865658 0.015678543  0.86150847  0.91162315
## a[2]   1.0505694 0.009938439  1.03468581  1.06645290
## b[1]   0.1325025 0.074217415  0.01388876  0.25111629
## b[2]  -0.1425745 0.054759265 -0.23009040 -0.05505863
## sigma  0.1095145 0.005938065  0.10002434  0.11900469
pairs(m3)

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?

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( m3 , depth=2 )
##             mean          sd        5.5%       94.5%
## a[1]   0.8865658 0.015678543  0.86150847  0.91162315
## a[2]   1.0505694 0.009938439  1.03468581  1.06645290
## b[1]   0.1325025 0.074217415  0.01388876  0.25111629
## b[2]  -0.1425745 0.054759265 -0.23009040 -0.05505863
## sigma  0.1095145 0.005938065  0.10002434  0.11900469

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

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?