1

我正在使用 R 中的 bnlearn 包来构建一个使用数据和专家知识的定制拟合离散贝叶斯网络。http://www.bnlearn.com/examples/custom/

这需要使用 bn.fit() 创建一个 bn.fit 对象并修改感兴趣节点的局部分布。对于离散贝叶斯网络(或条件高斯网络中的离散节点),可以使用 coef() 从 bn.fit 对象中提取条件概率表,对其进行更新和重新保存。

library(bnlearn)
dag = model2network("[A][C][F][B|A][D|A:C][E|B:F]")  #creates a network
fitted <- bn.fit(dag, learning.test) #(determines conditional probability 
given data in learning.test)
fitted[[3]]  #CP for node [C] as example, fitted$C also works 
cpt <- coef(fitted[[3]]) #extract coefficients from table
cpt[1:length(cpt)] = c(0.50, 0.25, 0.25)  #new CPs
fitted$C<-cpt #assign new CPs to joint CP table
fitted$C #Works

Parameters of node C (multinomial distribution)

Conditional probability table:
a    b    c 
0.50 0.25 0.25 

我想通过索引bn.fit对象来更新大量节点,即

fitted[[3]][[4]][1:3]<-cpt  #returns error
fitted[[3]][[4]]<-cpt       #returns error

Error in check.nodes(name, x) : 
nodes must be a vector of character strings, the labels of the nodes.

鉴于 [[ 和 $ 运算符之间的等价性,任何人都可以解释为什么会这样以及可能的解决方法。

identical(fitted$C,fitted[[3]])
TRUE

谢谢

4

1 回答 1

1

由于您的示例的最后一行显示对象是相同的,因此它表明$<-and的调度方法[[<-可能不同或未实际定义,但是,这并不是这里发生的情况。

该行的相关功能fitted$C<-cptbnlearn:::'$<-.bn.fit'。查看此代码会导致 bnlearn:::'[[<-.bn.fit'. 所以有为[[和定义的方法$。再次查看代码,导致bnlearn:::check.nodes,快速阅读最后一个函数表明您需要将 a 传递character给 的name参数bnlearn:::'[[<-.bn.fit',并且它需要位于图中的节点名称集中。因此,为什么fitted[[3]] <- cpt, and fitted[[3]][[4]]<-cpt, 和其他迭代不起作用(当您传递3时,它既character不是节点名称也不是节点名称。

作为替代方案,如果您可以稍微更改您的工作流程,您可以使用fitted[["C"]] <- cpt,这将比通过索引传递更安全。如果您确实想通过索引,您可以通过索引提取 cpd 节点名称。

于 2017-09-27T21:32:58.813 回答