我获取了一个文本数据(在Mahabharata中的Krishna和Arjuna之间的对话)。我手动为其创建了节点级和CPD,是否有任何方法可以使其自动化?以下是我已实现的代码
library(bnlearn)
set.seed(3)
net <- model2network("[Kauravas][Krishna][Rules|Kauravas][Karma|Rules][Concept|Krishna][Arjuna|Krishna:Concept][Fight|Arjuna:Karma]")
plot(net)
graphviz.plot(net,highlight = NULL, layout = "dot", shape = "ellipse", main = NULL, sub = NULL)
library(gRain)
Ka <- c("yes", "no")
Rul <- c("yes","no")
Karm<- c("yes","no")
Fig<- c("yes","no")
Kri=c("yes","no")
Con=c("yes","no")
Arj=c("yes","no")
cptKauravas <- matrix(c(0.85, 0.15), ncol=2, dimnames=list(NULL, Ka)) #[1]
cptKrishna <- matrix(c(0.81, 0.19), ncol=2, dimnames=list(NULL, Kri)) #[2]
cptRules <- matrix(c(0.01, 0.99, 0.33, 0.67), ncol=2, dimnames=list("Rules"=Rul, "Kauravas"= Ka )) #[1]
cptKarma <- matrix(c(0.01, 0.99, 0.33, 0.67), ncol=2, dimnames=list("Karma"=Karm, "Rules"= Rul )) #[1]
cptConcept <- matrix(c(0.01, 0.99, 0.33, 0.67), ncol=2, dimnames=list("Concept"=Con, "Krishna"= Kri )) #[1]
cptArjuna <- c(0.3, 0.7, 0.14, 0.86, 0.125, 0.875, 0.125, 0.875)
dim(cptArjuna) <- c(2, 2, 2)
dimnames(cptArjuna) <- list("Arjuna"=Arj, "Concept"=Con, "Krishna"=Kri)
cptFight <- c(0.3, 0.7, 0.14, 0.86, 0.125, 0.875, 0.125, 0.875) #[4]
dim(cptFight) <- c(2, 2, 2)
dimnames(cptFight) <- list("Fight"=Fig, "Arjuna"=Arj, "Karma"=Karm)
net.disc <- custom.fit(net, dist=list(Kauravas=cptKauravas, Rules=cptRules,Karma=cptKarma, Fight=cptFight, Krishna=cptKrishna, Concept=cptConcept, Arjuna=cptArjuna))
#set.seed(3)
probyes <- cpquery(net.disc, (Fight=="yes"),Arjuna=="yes" & Concept=="yes" & Rules=="yes",n=1000000)
probyes
probno <- cpquery(net.disc, (Fight=="no"),Arjuna=="yes" & Concept=="yes" & Rules=="yes",n=1000000)
probno
probyes<- cpquery(net.disc, (Arjuna=="yes"),Fight=="yes" & Concept=="yes",n=1000000 )
probyes
probyes<- cpquery(net.disc, (Krishna=="yes"),Fight=="yes" & Concept=="yes",n=1000000 )
probyes