# 机器学习（八）：贝叶斯网络——福尔摩斯推理、草地喷水器推断

1. 掌握贝叶斯网络算法的原理及设计；

2. 掌握利用贝叶斯网络算法解决推理分析。

2.

1.计算草地是湿的情况下，下雨的概率？

2.草地是湿的情况下，自动喷水的概率？

1.搭建模型

from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination
model = BayesianNetwork([('B', 'A'), ('E', 'A'), ('A', 'W'), ('E', 'R')])
cpd_1 = TabularCPD(variable='B', variable_card=2, values=[[0.9], [0.1]])
cpd_2 = TabularCPD(variable='E', variable_card=2, values=[[0.99], [0.01]])
cpd_A = TabularCPD(variable='A', variable_card=2,
values=[[0.99, 0.1, 0.1, 0.01],
[0.01, 0.9, 0.9, 0.99]],
evidence=['E', 'B'],#父节点
evidence_card=[2, 2])#警铃
cpd_W = TabularCPD(variable='W', variable_card=2,
values=[[0.99, 0.35],
[0.01, 0.65]],
evidence=['A'],#父节点
evidence_card=[2])#华生致电福尔摩斯
cpd_R = TabularCPD(variable='R', variable_card=2,
values=[[0.999, 0.01],
[0.001, 0.99]],
evidence=['E'],#父节点
evidence_card=[2])#广播播报地震
infer = VariableElimination(model)
print(infer.query(variables=['B'],evidence={'A':1}))
print(infer.query(variables=['E'],evidence={'A':1,'R':1}))
print(infer.query(variables=['B'],evidence={'A':1,'R':1}))


2.计算概率

1.搭建模型

model = BayesianNetwork([('R', 'S'), ('R', 'G'), ('S', 'G')])
cpd_1 = TabularCPD(variable='R', variable_card=2, values=[[0.8], [0.2]])
cpd_S = TabularCPD(variable='S', variable_card=2,
values=[[0.6, 0.99],
[0.4, 0.01]],
evidence=['R'],#父节点
evidence_card=[2])
cpd_G = TabularCPD(variable='G', variable_card=2,
values=[[1.0, 0.2, 0.1, 0.01],
[0.0, 0.8, 0.9, 0.99]],
evidence=['S', 'R'],#父节点
evidence_card=[2, 2])#警铃

infer = VariableElimination(model)
print(infer.query(variables=['R'],evidence={'G':1}))

print(infer.query(variables=['S'],evidence={'G':1}))


2.计算概率

（1）警铃A响了，那么窃贼入室B的概率是84.12%

（2）之后再路上听广播说发生了地震，那么发生地震的概率是98.92%，是窃贼入室的概率是11.75%

（1）草地是湿的情况下，下雨的概率是35.77%

（2）草地是湿的情况下，自动喷水的概率64.67%

posted @ 2023-05-25 17:33  孤飞  阅读(181)  评论(3编辑  收藏  举报