我正在努力使用rjags
定义条件线性高斯贝叶斯网络。
(clg BN由连续子节点(结果)定义,具有连续正常和离散父(预测变量))
对于下面的网,A是离散的,D和E是连续的:
对于rjags
模型,我假设我想要的是在值节点E
上定义的节点A
的参数:伪代码
model {
A ~ dcat(c(0.0948, 0.9052 ))
D ~ dnorm(11.87054, 1/1.503111^2)
if A==a then E ~ dnorm(6.558366 + 1.180965*D, 1/2.960002^2)
if A==b then E ~ dnorm(3.370021 + 1.532289*D, 1/6.554402^2)
}
我可以通过使用下面的代码获得一些工作,但是它会更快地与更多的预测器和分类级别混淆。
library(rjags)
model <- textConnection("model {
A ~ dcat(c(0.0948, 0.9052 ))
D ~ dnorm(11.87054, 1/1.503111^2)
int = 6.558366 - (A==2)*(6.558366 - 3.370021)
slope = 1.180965 - (A==2)*(1.180965 - 1.532289)
sig = 2.960002 - (A==2)*(2.960002 - 6.554402)
E ~ dnorm(int + slope*D, 1/sig^2)
}")
jg <- jags.model(model, n.adapt = 1000
我的问题:我如何简洁地定义这个模型?
数据来自
library(bnlearn)
net = model2network("[A][D][E|A:D]")
ft = bn.fit(net, clgaussian.test[c("A", "D", "E")])
coef(ft)
structure(list(A = structure(c(0.0948, 0.9052), class = "table", .Dim = 2L, .Dimnames = list(
c("a", "b"))), D = structure(11.8705363469396, .Names = "(Intercept)"),
E = structure(c(6.55836552742708, 1.18096500477159, 3.37002124328838,
1.53228891423418), .Dim = c(2L, 2L), .Dimnames = list(c("(Intercept)",
"D"), c("0", "1")))), .Names = c("A", "D", "E"))
sigma(ft)
structure(list(A = NA, D = 1.50311121682603, E = structure(c(2.96000206596326,
6.55440224877698), .Names = c("0", "1"))), .Names = c("A", "D",
"E"))
答案 0 :(得分:2)
您只需使用变量A作为索引参数:
library('rjags')
model <- "
model {
A ~ dcat(c(0.0948, 0.9052 ))
D ~ dnorm(11.87054, 1/1.503111^2)
ints <- c(6.558366, 3.370021)
int <- ints[A]
slopes <- c(1.180965, 1.532289)
slope <- slopes[A]
sigs <- c(2.960002, 6.554402)
sig <- sigs[A]
E ~ dnorm(int + slope*D, 1/sig^2)
}
"
jg <- jags.model(textConnection(model), n.adapt = 1000)
顺便说一下,由于模型中有很多固定数量,在R中定义这些数据然后将它们作为数据传递给JAGS可能更有意义。这样,您可以调整向量的值和长度(只要catprobs,int,slope和sig的长度匹配),而无需修改JAGS代码。例如(为了方便起见使用runjags,尽管也可以使用jags):
library("runjags")
model <- "
model {
A ~ dcat(catprobs)
D ~ dnorm(Dmu, Dprec)
int <- ints[A]
slope <- slopes[A]
sig <- sigs[A]
E ~ dnorm(int + slope*D, 1/sig^2)
#data# catprobs, Dmu, Dprec, ints, slopes, sigs
#monitor# A, D, E
}
"
catprobs <- c(0.0948, 0.9052)
Dmu <- 11.87054
Dprec <- 1/1.503111^2
ints <- c(6.558366, 3.370021)
slopes <- c(1.180965, 1.532289)
sigs <- c(2.960002, 6.554402)
results <- run.jags(model)
results
马特