实例分析
如下图所示,给出了贝叶斯网络的图和相应的条件概率
对上述信息建立贝叶斯网络,代码如下
- N=8;
- dag=zeros(N,N);
- A=1;S=2;T=3;L=4;B=5;E=6;X=7;D=8;
- dag(A,T)=1;
- dag(S,[L B])=1;
- dag([T L],E)=1;
- dag(B,D)=1;
- dag(E,[X D])=1;
- discrete_nodes=1:N;
- node_sizes=2*ones(1,N);
- bnet=mk_bnet(dag,node_sizes,'names',{'A','S','T','L','B','E','X','D'},'discrete',discrete_nodes);
- bnet.CPD{A}=tabular_CPD(bnet,A,[0.99,0.01]);
- bnet.CPD{S}=tabular_CPD(bnet,S,[0.5,0.5]);
- bnet.CPD{T}=tabular_CPD(bnet,T,[0.99,0.95,0.01,0.05]);
- bnet.CPD{L}=tabular_CPD(bnet,L,[0.99,0.9,0.01,0.1]);
- bnet.CPD{B}=tabular_CPD(bnet,B,[0.7,0.4,0.3,0.6]);
- bnet.CPD{E}=tabular_CPD(bnet,E,[1,0,0,0,0,1,1,1]);
- bnet.CPD{X}=tabular_CPD(bnet,X,[0.95,0.02,0.05,0.98]);
- bnet.CPD{D}=tabular_CPD(bnet,D,[0.9,0.2,0.3,0.1,0.1,0.8,0.7,0.9]);
- draw_graph(dag)
说明:有N=8个节点,建立有向无环图dag,并且这些点的值是离散的,这里1=False 2=True,node_sizes给出了所有状态
mk_bnet中names后的{}里面给出了各个节点的别名
利用tabular_CPD设置各个变量的边缘概率,对于A和S,定义顺序是False True;对于T、L和B这类,顺序是FF FT TF TT;对于D这类,顺序是FFF FFT FTF FTT TFF TFT TTF TTT
简单检查下A的概率
- engine=jtree_inf_engine(bnet);
- evidence=cell(1,N);
- [engine,loglik]=enter_evidence(engine,evidence);
- m=marginal_nodes(engine,A);
- m.T()
现在可以给定任意条件,然后计算概率了。
- 例如要计算任意组合条件下,个体分别得Tub、lung cancer和bronchitis的概率。下面代码计算了P(T=True|A=False,S=True,X=True,D=False)的概率
- engine=jtree_inf_engine(bnet);
- evidence=cell(1,N);
- evidence{A}=1;
- evidence{S}=2;
- evidence{X}=2;
- evidence{D}=1;
- [engine,loglik]=enter_evidence(engine,evidence);
- m=marginal_nodes(engine,T);
- m.T(2)