pip install pyagrum
如果出现超时问题,搜索anaconda如何更改下载源,改为清华下载源。
引入相关包
from pylab import *
import matplotlib.pyplot as plt
import os
import pyAgrum as gum
#给这个贝叶斯网络命名
bn=gum.BayesNet('WaterSprinkler')
#添加单个节点
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变量。
#添加单个边,前面父节点,后面子节点
bn.addArc(c,s)
#添加多个边
for link in [(c,r),(s,w),(r,w)]:
bn.addArc(*link)
#print(bn)
bn=gum.fastBN("c->r->w<-s<-c")
bn
#创建CPT
bn.cpt(c).fillWith([0.4,0.6])
bn.cpt("c").fillWith([0.5,0.5])
#创建第二层的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")
#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()里的路径要改成自己的保存路径,且不能有中文
ie=gum.LazyPropagation(bn)
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")[:]
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')
gnb.showInference(bn,evs={})
gnb.showInference(bn,evs={'s':1,'c':0})
gnb.showInference(bn,evs={'s':1,'c':[0.3,0.9]})
gnb.showInference(bn,evs={'c':[0.3,0.9]},targets={'c','w'})
# 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
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"])
print(gum.MarkovBlanket(bn,"C").toDot())
gum.MarkovBlanket(bn,"C")
gum.MarkovBlanket(bn,"J")
[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"])]
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
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)$'])