用R里的bnlearn做bayesian network inference结果不对,求解答。
模型是有两个node的network,parent node是v~N(0,0.1),child node是v_hat~N(v,2)。我的input是v_hat在-20到20的grid,每一个v_hat都取200个随机值。最后算的是posterior expectation。
代码在这里:
library(bnlearn)
library(rbmn)
vtilde = 0; sigmav2tilde = 0.1; sigmav2 = 2
dag.bnlearn <- model2network("[v][v_hat|v]")
v.dist <- list(coef = c("(Intercept)" = vtilde), sd = sqrt(sigmav2tilde))
v_hat.dist <- list(coef = c("(Intercept)" = 0, v = 1), sd = sqrt(sigmav2))
dist.list = list(v = v.dist, v_hat = v_hat.dist)
gbn.bnlearn <- custom.fit(dag.bnlearn, dist = dist.list)
v_hat_grid = seq(-20, 20, length = 50)
v_post_approx <- c()
for (v_hat_input in v_hat_grid) {
sims <- cpdist(gbn.bnlearn,
nodes = "v",
evidence = list(v_hat = v_hat_input),
method = "lw",
n = 200)
weights <- attributes(sims)$weights
vals <- sims * weights
cols <- colnames(vals)
posts <- vals %>% summarise(across(all_of(cols), ~ mean(.x, na.rm = TRUE), .names = "post_{.col}"))
v_post_approx <- c(v_post_approx, posts[1,1])
}
plot(y = v_post_approx, x = v_hat_grid)


雷达卡



京公网安备 11010802022788号







