Reputation: 125
I am trying run rjags in R (via Rstudio) to estimate parameters alpha&beta and hyperparameter tau.nu
of the model following:
y_i|x_i~pois(eta_i),
eta_i=exp(alpha + beta*x_i + nu_i),
nu_i~N(0,tau.nu)
there is my code:
#generating data
N = 1000
x = rnorm(N, mean=3,sd=1)
nu = rnorm(N,0,0.01)
eta = exp(1 + 2*x + nu)
y = rpois(N,eta)
data=data.frame(y=y,x=x)
###MCMC
library(rjags)
library(coda)
mod_string= "model {
for(i in 1:1000) {
y[i]~dpois(eta[i])
eta[i]=exp(alpha+beta*x[i]+nu[i])
nu[i]~dnorm(0,tau.nu)
}
alpha ~ dnorm(0,0.001)
beta ~ dnorm(0,0.001)
tau.nu ~ dgamma(0.01,0.01)
}"
params = c("alpha","beta","tau.nu")
inits = function() {
inits = list("alpha"=rnorm(1,0,100),"beta"=rnorm(1,0,80),"tau.nu"=rgamma(1,1,1))
}
mod = jags.model(textConnection(mod_string), data=data, inits=inits, n.chains =3)
update(mod,5000)
mod_sim = coda.samples(model=mod,
variable.names=params,
n.iter=2e4)
mod_csim = as.mcmc(do.call(rbind, mod_sim))
plot(mod_csim)
the I get weird output,I don't konw where I get wrong.Does MCMC not work in this model?Or I just do something wrong in coding?
Upvotes: 9
Views: 297
Reputation: 25854
This model doesn't converge using the standard samplers. It does if you use the the samplers in the glm
module. (but this may not always be the case [1])
Without the glm
module loaded
library(rjags)
mod_sim1 <- jagsFUN(dat)
plot(mod_sim1)
load.module("glm")
mod_sim2 <- jagsFUN(dat)
plot(mod_sim2)
# function and data
# generate data
set.seed(1)
N = 50 # reduced so could run example quickly
x = rnorm(N, mean=3,sd=1)
nu = rnorm(N,0,0.01)
eta = exp(1 + 2*x + nu)
y = rpois(N,eta)
dat = data.frame(y=y,x=x)
# jags model
jagsFUN <- function(data) {
mod_string= "model {
for(i in 1:N) {
y[i] ~ dpois(eta[i])
log(eta[i]) = alpha + beta* x[i] + nu[i]
}
# moved prior outside the likelihood
for(i in 1:N){
nu[i] ~ dnorm(0,tau.nu)
}
alpha ~ dnorm(0,0.001)
beta ~ dnorm(0,0.001)
tau.nu ~ dgamma(0.001,0.001)
# return on variance scale
sig2 = 1 / tau.nu
}"
mod = jags.model(textConnection(mod_string),
data=c(as.list(data),list(N=nrow(data))),
n.chains = 3)
update(mod,1000)
mod_sim = coda.samples(model=mod,
variable.names=c("alpha","beta","sig2"),
n.iter=1e4)
return(mod_sim)
}
Upvotes: 6