JAGS分析简介

时间:2015-10-01 05:52:39

标签: r bayesian jags

我是一名学习贝叶斯统计学的学生,刚开始使用JAGS,使用我的讲师编写的介绍脚本,我们(学生)只需要输入数据和迭代次数。以下是添加了我的数据的脚本:

setwd("C:\\Users\\JohnSmith\\Downloads")

rawdata = read.table("bwt.txt",header=TRUE)
Birthweight = rawdata$Birthweight
Age = rawdata$Age

model = "model
{
  beta0 ~ dnorm(0, 1/1000^2)
  beta1 ~  dnorm(0, 1/1000^2)

  log_sigma ~ dunif(-10, 10)
  sigma <- exp(log_sigma)

 for(i in 1:N)
 {
   mu[i] <- beta0 + beta1 * Age[i]
   Birthweight[i] ~ dnorm(mu[i], 1/sigma^2) 
 } 
}
"

data = list(x=Birthweight, y=Age, N=24)

# Variables to monitor
variable_names = c('beta0','beta1')

# How many burn-in steps?
burn_in = 1000

# How many proper steps?
steps = 100000

# Thinning?
thin = 10

# Random number seed
seed = 2693795


    # NO NEED TO EDIT PAST HERE!!!
    # Just run it all and use the results list.

library('rjags')

# Write model out to file
fileConn=file("model.temp")
writeLines(model, fileConn)
close(fileConn)

if(all(is.na(data)))
{
    m = jags.model(file="model.temp", inits=list(.RNG.seed=seed,             .RNG.name="base::Mersenne-Twister"))
} else
{
m = jags.model(file="model.temp", data=data, inits=list(.RNG.seed=seed,     .RNG.name="base::Mersenne-Twister"))
}
update(m, burn_in)
draw = jags.samples(m, steps, thin=thin, variable.names = variable_names)
# Convert to a list
make_list <- function(draw)
{
    results = list()
    for(name in names(draw))
    {
        # Extract "chain 1"
        results[[name]] = as.array(draw[[name]][,,1])

        # Transpose 2D arrays
        if(length(dim(results[[name]])) == 2)
            results[[name]] = t(results[[name]])
    }
    return(results)
}
results = make_list(draw)

但是,当我运行以下代码时,我收到以下错误消息:

Error in jags.model(file = "model.temp", data = data, inits = list(.RNG.seed = seed,  : 
  RUNTIME ERROR:
Compilation error on line 11.
Unknown parameter Age

In addition: Warning messages:
1: In jags.model(file = "model.temp", data = data, inits = list(.RNG.seed =     seed,  :
  Unused variable "x" in data
2: In jags.model(file = "model.temp", data = data, inits = list(.RNG.seed = seed,  :
  Unused variable "y" in data

但据我所知,第11行是空白的,这让我对错误的来源感到难过。如果有人能给我一些解决这个问题的建议,我们将不胜感激。

1 个答案:

答案 0 :(得分:2)

数据列表(data)的元素名称应与模型中变量的名称相匹配。

你有:

data = list(x=Birthweight, y=Age, N=24)

所以JAGS正在模型中寻找名为xy的变量。但是,在您的模型中,您有:

mu[i] <- beta0 + beta1 * Age[i]
Birthweight[i] ~ dnorm(mu[i], 1/sigma^2) 

也就是说,您的变量称为AgeBirthweight

因此,要么将列表更改为:

data <- list(Birthweight=Birthweight, Age=Age, N=24)

或将您的模型更改为:

mu[i] <- beta0 + beta1 * y[i]
x[i] ~ dnorm(mu[i], 1/sigma^2)

如果您完成readLines('model.temp')(或在文本编辑器中打开了model.temp),您会看到该文件的第11行引用包含mu[i] <- beta0 + beta1 * Age[i]的行,这是第一个错误JAGS由于引用Age而遇到的,既未提供数据也未提供先验。