PyAgrum的一个例子

文章目录

  • 1 下载PyAgrum
  • 2 构建贝叶斯网络
    • 2.1 创建网络和名字
    • 2.2 添加节点
    • 2.3 添加边
      • 2.4 快捷添加边
  • 3 构建条件概率表
    • 3.1 父节点
    • 3.2 子节点
  • 4 Input/Output
  • 5 在贝叶斯网络中的推断
    • 5.1 精确推断
    • 5.2 没有新数据的推断
    • 5.3 有新数据的推断
    • 5.4 展示所有节点的推断
      • 5.4.1 有证据的推断
      • 5.4.2 nference with soft and hard evidence
      • 5.4.3 inference with partial targets
  • 6 测试节点独立性
    • 6.1 条件独立性
      • 6.1.1 有向性
      • 6.1.2 Markov Blanket
      • 6.1.3 最小条件集
      • 6.1.4 证据影响的概率预测
  • 7 完整的创建第一个贝叶斯网络的代码

1 下载PyAgrum

pip install pyagrum

如果出现超时问题,搜索anaconda如何更改下载源,改为清华下载源。

2 构建贝叶斯网络

引入相关包

from pylab import *
import matplotlib.pyplot as plt
import os
import pyAgrum as gum

2.1 创建网络和名字

#给这个贝叶斯网络命名
bn=gum.BayesNet('WaterSprinkler')

2.2 添加节点

#添加单个节点
c=bn.add(gum.LabelizedVariable('c','cloudy ?',2))
#print(c)
#添加多个节点
s, r, w = [ bn.add(name, 2) for name in "srw" ] #bn.add(name, 2) === bn.add(gum.LabelizedVariable(name, name, 2))

L a b e l i z e d v a r i a b l e Labelized variable Labelizedvariable是标识变量,指变量的数值是有限的。2说明 c c c的值只有两种,是 b o o l e a n boolean boolean变量。

2.3 添加边

#添加单个边,前面父节点,后面子节点
bn.addArc(c,s)
#添加多个边
for link in [(c,r),(s,w),(r,w)]:
    bn.addArc(*link)
#print(bn)

2.4 快捷添加边

bn=gum.fastBN("c->r->w<-s<-c")
bn

3 构建条件概率表

3.1 父节点

#创建CPT
bn.cpt(c).fillWith([0.4,0.6])
bn.cpt("c").fillWith([0.5,0.5])

3.2 子节点

#创建第二层的CPT
bn.cpt("s").var_names#展示s里的变量名,有c和s两类
bn.cpt("s")[:]=[ [0.5,0.5],[0.9,0.1]]
print(bn.cpt("s")[1])
bn.cpt("s")[0,:]=0.5 # equivalent to [0.5,0.5]
bn.cpt("s")[1,:]=[0.9,0.1]
bn.cpt("r")[{'c':0}]=[0.8,0.2]
bn.cpt("r")[{'c':1}]=[0.2,0.8]
print(bn.cpt("w").var_names)
bn.cpt("w")
bn.cpt("w")[0,0,:] = [1, 0] # r=0,s=0时的概率分布
bn.cpt("w")[0,1,:] = [0.1, 0.9] # r=0,s=1
bn.cpt("w")[1,0,:] = [0.1, 0.9] # r=1,s=0
bn.cpt("w")[1,1,:] = [0.01, 0.99] # r=1,s=1
#用字典进行赋值
bn.cpt("w")[{'r': 0, 's': 0}] = [1, 0]
bn.cpt("w")[{'r': 0, 's': 1}] = [0.1, 0.9]
bn.cpt("w")[{'r': 1, 's': 0}] = [0.1, 0.9]
bn.cpt("w")[{'r': 1, 's': 1}] = [0.01, 0.99]
bn.cpt("w")

4 Input/Output

#Input
print(gum.availableBNExts())
#Output
gum.saveBN(bn,"D:\\Bayesian network\\pyArum\\out\\tutorial1\\WaterSprinkler.bif")
with open("D:\\Bayesian network\\pyArum\\out\\tutorial1\\WaterSprinkler.bif","r") as out:
    print(out.read())
bn2=gum.loadBN("D:\\Bayesian network\\pyArum\\out\\tutorial1\\WaterSprinkler.bif.bif")

gum.saveBN(bn,"D:\\Bayesian network\\pyArum\\out\\tutorial1\\WaterSprinkler.bif.net")
with open("D:\\Bayesian network\\pyArum\\out\\tutorial1\\WaterSprinkler.bif.net","r") as out:
    print(out.read())
bn3=gum.loadBN("oD:\\Bayesian network\\pyArum\\out\\tutorial1\\WaterSprinkler.bif.net")

注意: s a v e B N ( ) saveBN() saveBN()里的路径要改成自己的保存路径,且不能有中文

5 在贝叶斯网络中的推断

5.1 精确推断

ie=gum.LazyPropagation(bn)

5.2 没有新数据的推断

ie.makeInference()
print (ie.posterior("w"))
from IPython.core.display import HTML
HTML(f"In our BN, $P(W)=${ie.posterior('w')[:]}")
ie.posterior("w")[:]

5.3 有新数据的推断

ie.setEvidence({'s':0, 'c': 0})
ie.makeInference()
ie.posterior("w")
ie.setEvidence({'s': [0.5, 1], 'c': [1, 0]})
ie.makeInference()
ie.posterior("w") # using gnb's feature
gnb.showProba(ie.posterior("w"))
gnb.showPosterior(bn,{'s':1,'c':0},'w')

5.4 展示所有节点的推断

gnb.showInference(bn,evs={})

5.4.1 有证据的推断

gnb.showInference(bn,evs={'s':1,'c':0})

5.4.2 nference with soft and hard evidence

gnb.showInference(bn,evs={'s':1,'c':[0.3,0.9]})

5.4.3 inference with partial targets

gnb.showInference(bn,evs={'c':[0.3,0.9]},targets={'c','w'})

6 测试节点独立性

# fast create a BN (random paramaters are chosen for the CPTs)
bn=gum.fastBN("A->B<-C->D->E<-F<-A;C->G<-H<-I->J")
bn

6.1 条件独立性

6.1.1 有向性

def testIndep(bn,x,y,knowing):
    res="" if bn.isIndependent(x,y,knowing) else " NOT"
    giv="." if len(knowing)==0 else f" given {knowing}."
    print(f"{x} and {y} are{res} independent{giv}")

testIndep(bn,"A","C",[])
testIndep(bn,"A","C",["E"])
print()
testIndep(bn,"E","C",[])
testIndep(bn,"E","C",["D"])
print()
testIndep(bn,"A","I",[])
testIndep(bn,"A","I",["E"])
testIndep(bn,"A","I",["G"])
testIndep(bn,"A","I",["E","G"])

6.1.2 Markov Blanket

print(gum.MarkovBlanket(bn,"C").toDot())
gum.MarkovBlanket(bn,"C")
gum.MarkovBlanket(bn,"J")

6.1.3 最小条件集

[bn.variable(i).name() for i in bn.minimalCondSet("B",["A","H","J"])]
[bn.variable(i).name() for i in bn.minimalCondSet("B",["A","G","H","J"])]

6.1.4 证据影响的概率预测

ie=gum.LazyPropagation(bn)
ie.evidenceImpact("B",["A","C","H","G"]) # H,G will be removed w.r.t the minimalCondSet above
ie.evidenceImpact("B",["A","G","H","J"]) # "J" is not necessary to compute the impact of the evidence

7 完整的创建第一个贝叶斯网络的代码

bn=gum.fastBN("Cloudy?->Sprinkler?->Wet Grass?<-Rain?<-Cloudy?")

bn.cpt("Cloudy?").fillWith([0.5,0.5])

bn.cpt("Sprinkler?")[:]=[[0.5,0.5],
                         [0.9,0.1]]

bn.cpt("Rain?")[{'Cloudy?':0}]=[0.8,0.2]
bn.cpt("Rain?")[{'Cloudy?':1}]=[0.2,0.8]

bn.cpt("Wet Grass?")[{'Rain?': 0, 'Sprinkler?': 0}] = [1, 0]
bn.cpt("Wet Grass?")[{'Rain?': 0, 'Sprinkler?': 1}] = [0.1, 0.9]
bn.cpt("Wet Grass?")[{'Rain?': 1, 'Sprinkler?': 0}] = [0.1, 0.9]
bn.cpt("Wet Grass?")[{'Rain?': 1, 'Sprinkler?': 1}] = [0.01, 0.99]

gum.config['notebook','potential_visible_digits']=2
gnb.sideBySide(bn.cpt("Cloudy?"),captions=['$P(Cloudy)$'])
gnb.sideBySide(bn.cpt("Sprinkler?"),gnb.getBN(bn,size="3!"),bn.cpt("Rain?"),
              captions=['$P(Sprinkler|Cloudy)$',"",'$P(WetGrass|Sprinkler,Rain)$'])
gnb.sideBySide(bn.cpt("Wet Grass?"),captions=['$P(WetGrass|Sprinkler,Rain)$'])

你可能感兴趣的:(python,人工智能)