r - “函数中的不合格参数:”在使用 JAGS 的简单线性回归中
问题描述
我对 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 :
解决方案
问题已经解决了!
基本上变化是 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)
谢谢您的帮助!我希望这对其他人有帮助。
推荐阅读
- mongodb - 无法重新启动 mongod.service:未找到单元 mongod.service (Ubuntu 20.04)
- javascript - 有条件地比较数组的值并将其设置为变量
- c - 如何使用 Realloc 收缩字符串
- python - 如何使用 python Tkinter 创建一个智能输入字段字段来建议自动完成的单词
- javascript - 嵌套的 JSON 对象未保存到数据库 MongoDB
- python - 我不知道如何让我的 Plotly 图表只显示整数
- python - 如何将 swf 文件从内存加载到 QWebEngineView
- python - Python - 你好,我是 python 新手,我有一个变量没有在 while 循环中更新的问题,当我这样做时,它只会无限输出“你好”
- javascript - 将 DOM 事件附加到本地文件
- reactjs - 多个文件上传不起作用(Material UI Dropzone ^3.4.0,axios)