Petr Keil
March 2017, iDiv
Pandivirilia eximia (Meigen 1820), family Therevidae
Our data are counts of larvae sampled from underneath logs in a temperate primeval forest.
y <- c(23,17,25,28,38,18,32,51,
32,41,51,33,21,52,11,19)
N <- length(y)
my.data <- list(y=y, N=N)
my.data
$y
[1] 23 17 25 28 38 18 32 51 32 41 51 33 21 52 11 19
$N
[1] 16
\[ p(\theta|y) = \frac {p(\theta) \times p(y|\theta)}{p(y)} \]
where \( \theta \) are model parameters, and \( y \) are the data
\( p(y|\theta) \) … likelihood
\( p(\theta) \) … prior
\( p(\theta|y) \) … posterior
\( p(y) \) … the horrible thing
This is the model that we will fit: \( y_i \sim Poisson(\lambda) \)
model
{
# p(lambda)
# p(y|lambda)
}
This is the model that we will fit: \( y_i \sim Poisson(\lambda) \)
model
{
# p(lambda) ... prior
# p(y|lambda) ... likelihood
}
This is the model that we will fit: \( y_i \sim Poisson(\lambda) \)
model
{
# prior
lambda ~ dunif(0, 100)
# likelihood
for(i in 1:N)
{
y[i] ~ dpois(lambda)
}
}
We will dump the model to a file using cat("", file="")
cat("
model
{
# prior
lambda ~ dunif(0, 100)
# likelihood
for(i in 1:N)
{
y[i] ~ dpois(lambda)
}
}
", file="my_model.txt")
library(R2jags)
fitted.model <- jags(data=my.data, model.file="my_model.txt", parameters.to.save="lambda", n.chains=3, n.iter=2000, n.burnin=1000)
Compiling model graph
Resolving undeclared variables
Allocating nodes
Graph information:
Observed stochastic nodes: 16
Unobserved stochastic nodes: 1
Total graph size: 20
Initializing model
plot(as.mcmc(fitted.model))
fitted.model
Inference for Bugs model at "my_model.txt", fit using jags,
3 chains, each with 2000 iterations (first 1000 discarded)
n.sims = 3000 iterations saved
mu.vect sd.vect 2.5% 25% 50% 75% 97.5% Rhat
lambda 30.772 1.347 28.265 29.822 30.734 31.679 33.451 1.001
deviance 165.818 1.301 164.877 164.969 165.327 166.172 169.363 1.012
n.eff
lambda 3000
deviance 650
For each parameter, n.eff is a crude measure of effective sample size,
and Rhat is the potential scale reduction factor (at convergence, Rhat=1).
DIC info (using the rule, pD = var(deviance)/2)
pD = 0.8 and DIC = 166.7
DIC is an estimate of expected predictive error (lower deviance is better).
plot(fitted.model)