我正在自学贝叶斯图形网络。我正在尝试使用 python 包pgmpy在 python 中生成网络。这似乎是一个很好的资源。
对于我的第一个测试,我生成了一个如下所示的简单网络(我设置了已知概率和条件概率来推断无条件概率):

现在,我将和的概率以及的概率输入到 pgmpy 中的贝叶斯图形模型结构中:
IN:
#These are based on the the Monte Hall example found at https://github.com/pgmpy/pgmpy/blob/dev/examples/Monte%20Hall%20Problem.ipynb
from pgmpy.models import BayesianModel
from pgmpy.factors import TabularCPD
# Defining the network structure
model = BayesianModel([('A', 'C'), ('B', 'C')])
# Defining the CPDs:
cpd_p = TabularCPD('A', 2, [[0.99, 0.01]])
cpd_a = TabularCPD('B', 2, [[0.9, 0.1]])
cpd_t = TabularCPD('C', 2, [[0.9, 0.5, 0.4, 0.1],
[0.1, 0.5, 0.6, 0.9]],
evidence=['A', 'B'], evidence_card=[2, 2])
# Associating the CPDs with the network structure.
model.add_cpds(cpd_p, cpd_a, cpd_t)
# Some other methods
model.get_cpds()
OUT:
[<TabularCPD representing P(A:2) at 0x10e24cfd0>,
<TabularCPD representing P(B:2) at 0x10e24cf10>,
<TabularCPD representing P(C:2 | A:2, B:2) at 0x10df9a750>]
但是,当我计算 pgmpy 中的概率时,我得到:
IN:
# Infering the posterior probability
from pgmpy.inference import VariableElimination
print 'P(B|A=1,C=1)'
infer = VariableElimination(model)
posterior_p = infer.query(['B'], evidence={'A': 1, 'C': 1})
print(posterior_p['B'])
print 'P(B|C=1)'
posterior_p = infer.query(['B'], evidence={'C': 1})
print(posterior_p['B'])
print 'probs'
posterior_p = infer.query(['B','C','A'])
for entry in posterior_p:
print posterior_p[entry]
OUT:
P(B|A=1,C=1)
+-----+----------+
| B | phi(B) |
|-----+----------|
| B_0 | 0.8333 |
| B_1 | 0.1667 |
+-----+----------+
P(B|C=1)
+-----+----------+
| B | phi(B) |
|-----+----------|
| B_0 | 0.6082 |
| B_1 | 0.3918 |
+-----+----------+
probs
+-----+----------+
| A | phi(A) |
|-----+----------|
| A_0 | 0.9900 |
| A_1 | 0.0100 |
+-----+----------+
+-----+----------+
| C | phi(C) |
|-----+----------|
| C_0 | 0.8461 |
| C_1 | 0.1539 |
+-----+----------+
+-----+----------+
| B | phi(B) |
|-----+----------|
| B_0 | 0.9000 |
| B_1 | 0.1000 |
+-----+----------+
但是,当我手动计算上面显示的条件概率(或变量的总概率)时(从无条件概率计算),我得到不同的答案:
显然这与 pgmpy 输出的概率不同。
有人知道我哪里出错了吗?使用我的“手动”计算或编码。
谢谢!!!