使用 JAGS 生成预测

Generate predictions using JAGS

我有一个参数化的线性高斯贝叶斯网络,我正在尝试使用 rjags 对模型进行预测。我可以对一次观察执行此操作,但不知道如何通过多次观察。这是一个例子

library(rjags)
library(coda)

初始模型

mod <- textConnection("model {
  mpg.hat <- (34.96055404 - 3.35082533* wt - 0.01772474* disp)
  wt      ~ dnorm(3.21725, 1/0.9784574^2)
  disp    ~ dnorm(230.7219, 1/123.9387^2)
  mpg     ~ dnorm(mpg.hat, 1/2.916555^2)
}")

# Evaluate and get prediction when wt=1 and disp is hidden
m <- jags.model(mod, n.chains = 1, n.adapt = 1000, data=list(wt=1, disp=NA))
update(m, 10000)
cs <- coda.samples(m,  c("mpg", "wt", "disp"),  1e5)
summary(cs)

这按预期工作,但是,我有多行数据要生成预测。如果我尝试扩展 data=list( 参数以包含更多行,则会引发错误。因此,在重新运行模型文本和以下命令后,我得到了错误

m <- jags.model(mod, n.chains = 1, n.adapt = 1000, data=list(wt=1:2, disp=1:2))

Error in jags.model(mod, n.chains = 1, n.adapt = 1000, data = list(wt = 1:2, :
Error in node dnorm(230.722,(a1/(a123.939^2)))
Length mismatch in Node::setValue

如何将其扩展到更多观察结果?

您需要遍历行:

mod <- textConnection("model {
  for (n in 1:N) {
    mpg.hat[n] <- (34.96055404 - 3.35082533* wt[n] - 0.01772474* disp[n])
    mpg[n]     ~ dnorm(mpg.hat[n], 1/2.916555^2)
    wt[n]      ~ dnorm(3.21725, 1/0.9784574^2)
    disp[n]    ~ dnorm(230.7219, 1/123.9387^2)
  }
}")

请注意,您还需要将 N 添加到您的数据列表中:

data = list(N = 1, wt = 1, disp = NA)
data = list(N = 2, wt = 1:2, disp = 1:2)