statistical-rethinking icon indicating copy to clipboard operation
statistical-rethinking copied to clipboard

statistical-rethinking/chapter-12/homework.R 12M4

Open monogenea opened this issue 6 years ago • 0 comments

Solution to 12M4

# Sun Feb 24 17:47:16 2019 ------------------------------
library(rethinking)
data("chimpanzees")
head(chimpanzees)
chimpanzees$recipient <- NULL
chimpanzees$block_id <- chimpanzees$block

# New cross-clasified model
mod1 <- map2stan(alist(
      pulled_left ~ dbinom(1, p),
      logit(p) <- a_actor[actor] + a_block[block_id] +
            (bP + bPC * condition)*prosoc_left,
      a_actor[actor] ~ dnorm(mu_actor, sigma_actor),
      a_block[block_id] ~ dnorm(mu_block, sigma_block),
      c(bP, bPC, mu_actor, mu_block) ~ dnorm(0, 10),
      c(sigma_actor, sigma_block) ~ dcauchy(0, 1)),
      data = chimpanzees, warmup = 1000, iter = 5000, chains = 4, cores = 3)

# Chapter's model for reference (incl. a and var intercept priors with mean == 0)
mod2 <- map2stan(alist(
      pulled_left ~ dbinom(1, p),
      logit(p) <- a + a_actor[actor] + a_block[block_id] +
            (bP + bPC * condition)*prosoc_left,
      a_actor[actor] ~ dnorm(0, sigma_actor),
      a_block[block_id] ~ dnorm(0, sigma_block),
      c(a, bP, bPC) ~ dnorm(0, 10),
      c(sigma_actor, sigma_block) ~ dcauchy(0, 1)),
      data = chimpanzees, warmup = 1000, iter = 5000, chains = 4, cores = 3)

compare(mod1, mod2)
precis(mod1)
precis(mod2)
# WAIC clearly favours the chapter model
# the posterior dists in the new model have much larger sds (~6),
# and this is reflected in n_eff from the HMC samples

monogenea avatar Feb 24 '19 20:02 monogenea