2

我对 JAGS 和贝叶斯统计非常陌生,并且一直在尝试遵循 Crawley 第 2 版 R 书中关于贝叶斯统计的第 22 章。我完全按照书中简单线性模型的代码复制代码:growth = a + b *tannin,其中有 9 行两个连续变量:增长和单宁。数据和包是这样的:

install.packages("R2jags")
library(R2jags)

growth <- c(12,10,8,11,6,7,2,3,3)
tannin <- c(0,1,2,3,4,5,6,7,8)
N <- c(1,2,3,4,5,6,7,8,9)
bay.df <- data.frame(growth,tannin,N)

ASCII 文件如下所示:

model{
  for(i in 1:N) {
    growth[i] ~ dnorm(mu[i],tau)
    mu[i] <- a+b*tannin[i]
  }
  a ~ dnorm(0.0, 1.0E-4)
  b ~ dnorm(0.0, 1.0E-4)
  sigma <- 1.0/sqrt(tau)
  tau ~ dgamma(1.0E-3, 1.0E-3)
}

但是,当我使用这段代码时:

> practicemodel <- jags(data=data.jags,parameters.to.save = c("a","b","tau"),
+                   n.iter=100000, model.file="regression.bugs.txt", n.chains=3)

我收到一条错误消息,上面写着:

module glm loaded
Compiling model graph
 Resolving undeclared variables
Deleting model

Error in jags.model(model.file, data = data, inits = init.values, n.chains = n.chains,  : 
  RUNTIME ERROR:
Non-conforming parameters in function :
4

1 回答 1

1

问题已经解决了!

基本上变化是 from N <- (1,2...)to N <- 9,但还有另一种解决方案,在N开始时没有指定。您可以在函数N内部指定data.jags数据框中的行数;data.jags = list(growth=bay.df$growth, tannin=bay.df$tannin, N=nrow(bay.df)).

这是新代码:

# Make the data frame
growth <- c(12,10,8,11,6,7,2,3,3)
tannin <- c(0,1,2,3,4,5,6,7,8)
# CHANGED : This is for the JAGS code to know there are 9 rows of data
N <- 9 code
bay.df <- data.frame(growth,tannin)

library(R2jags)

# Now, write the Bugs model and save it in a text file
sink("regression.bugs.txt") #tell R to put the following into this file
cat("
model{
  for(i in 1:N) {
    growth[i] ~ dnorm(mu[i],tau)
    mu[i] <- a+b*tannin[i]
  }
  a ~ dnorm(0.0, 1.0E-4)
  b ~ dnorm(0.0, 1.0E-4)
  sigma <- 1.0/sqrt(tau)
  tau ~ dgamma(1.0E-3, 1.0E-3)
}
", fill=TRUE)
sink() #tells R to stop putting things into this file.

#tell jags the names of the variables containing the data
data.jags <- list("growth","tannin","N")

# run the JAGS function to produce the function:
practicemodel <- jags(data=data.jags,parameters.to.save = c("a","b","tau"),
                  n.iter=100000, model.file="regression.bugs.txt", n.chains=3)

# inspect the model output. Important to note that the output will
# be different every time because there's a stochastic element to the model
practicemodel 

# plots the information nicely, can visualize the error 
# margin for each parameter and deviance
plot(practicemodel) 


谢谢您的帮助!我希望这对其他人有帮助。

于 2019-11-22T18:39:03.450 回答