全部版块 我的主页
论坛 数据科学与人工智能 数据分析与数据科学 R语言论坛
457 0
2023-10-04
用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)
            
        
        
   

二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

相关推荐
栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群