004 gtsam/examples/DiscreteBayesNetExample.cpp

DiscreteBayesNetExample.cpp

离散化的BayesNet
Discrete Bayes Net example with famous Asia Bayes Network

一、main函数

int main(int argc, char **argv) {
  DiscreteBayesNet asia;
  DiscreteKey Asia(0, 2), Smoking(4, 2), Tuberculosis(3, 2), LungCancer(6, 2),
      Bronchitis(7, 2), Either(5, 2), XRay(2, 2), Dyspnea(1, 2);
  asia.add(Asia % "99/1");
  asia.add(Smoking % "50/50");

  asia.add(Tuberculosis | Asia = "99/1 95/5");
  asia.add(LungCancer | Smoking = "99/1 90/10");
  asia.add(Bronchitis | Smoking = "70/30 40/60");

  asia.add((Either | Tuberculosis, LungCancer) = "F T T T");

  asia.add(XRay | Either = "95/5 2/98");
  asia.add((Dyspnea | Either, Bronchitis) = "9/1 2/8 3/7 1/9");

  // print
  vector<string> pretty = {"Asia",    "Dyspnea", "XRay",       "Tuberculosis",
                           "Smoking", "Either",  "LungCancer", "Bronchitis"};
  auto formatter = [pretty](Key key) { return pretty[key]; };
  asia.print("Asia", formatter);

  // Convert to factor graph
  DiscreteFactorGraph fg(asia);

  // Create solver and eliminate
  Ordering ordering;
  ordering += Key(0), Key(1), Key(2), Key(3), Key(4), Key(5), Key(6), Key(7);//按序添加变量
  DiscreteBayesNet::shared_ptr chordal = fg.eliminateSequential(ordering);

  // solve //优化
  DiscreteFactor::sharedValues mpe = chordal->optimize();
  GTSAM_PRINT(*mpe);

  // We can also build a Bayes tree (directed junction tree).
  // The elimination order above will do fine:
  // 可以构建一个有向的Bayes树
  auto bayesTree = fg.eliminateMultifrontal(ordering);
  bayesTree->print("bayesTree", formatter);

  // add evidence, we were in Asia and we have dyspnea
  fg.add(Asia, "0 1");
  fg.add(Dyspnea, "0 1");

  // solve again, now with evidence
  // 再次优化(带有置信度)
  DiscreteBayesNet::shared_ptr chordal2 = fg.eliminateSequential(ordering);//消除所有变量,生成bayes树
  DiscreteFactor::sharedValues mpe2 = chordal2->optimize();//优化
  GTSAM_PRINT(*mpe2);

  // We can also sample from it
  cout << "\n10 samples:" << endl;
  for (size_t i = 0; i < 10; i++) {
    DiscreteFactor::sharedValues sample = chordal2->sample();
    GTSAM_PRINT(*sample);
  }
  return 0;
}

DiscreteBayesNet asia;构造离散的BayesNet

// Convert to factor graph // 转化为因子图
DiscreteFactorGraph fg(asia);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值