簡體   English   中英

在R中將數據擬合到bnlearn模型

[英]fitting data to bnlearn model in R

我在R中有一個bnlearn模型,可以使用具有4個分類變量和8個數字變量的gs函數來學習該模型。 當我嘗試使用測試集驗證模型時,嘗試預測某些節點時出現此錯誤:

check.fit.vs.data中的錯誤(已擬合=對象,數據=數據,子集=對象[[node]] $ parents):
“關鍵字”在節點和數據中具有不同數量的級別。

bnlearn不能同時使用數字變量和分類變量嗎? 如果可能,我在做什么錯?

mydata$A <- as.factor(mydata$A)
mydata$B <- as.numeric(mydata$B)
mydata$C <- as.numeric(mydata$C)
mydata$D <- as.numeric(mydata$D)
mydata$E <- as.factor(mydata$E)
mydata$F <- as.numeric(mydata$F)
mydata$G <- as.numeric(mydata$G)
mydata$H <- as.numeric(mydata$H)
mydata$I <- as.numeric(mydata$I)
mydata$J <- as.numeric(mydata$J)
mydata$K <- as.numeric(mydata$K)
mydata$L <- as.numeric(mydata$L)
mydata$M <- as.numeric(mydata$M)
mydata$N <- as.numeric(mydata$N)
mydata$O <- as.numeric(mydata$O)
mydata$P <- as.numeric(mydata$P)
mydata$Q <- as.numeric(mydata$Q)


#create vector of black arcs
temp1=vector(mode = "character", length = 0)
for (i in 1:length(varnames)){
    for (j in 1:length(varnames)){
        temp1 <- c(temp1,varnames[i])
        }
    }

temp2=vector(mode = "character", length = 0)
for (i in 1:length(varnames)){
    temp2 <- c(temp2,varnames)
    }

#creat to arcs of the model
arcdata = read.csv("C:/users/asaf/desktop/in progress/whitearcs.csv", header = T)
wfrom=arcdata[,1]
wto=arcdata[,2]

whitelist = data.frame(from = wfrom,to =wto)

#block unwanted arcs

blacklist = data.frame(from = temp1, to = temp2)

#fit and plot the model

#gaussian method
model = gs(mydata, whitelist = whitelist, blacklist = blacklist)



#inference procedure

learntmodel = bn.fit(model,mydata,method = "mle",debug = F)

graphviz.plot(learntmodel)
myvalidation=read.csv("C:/users/asaf/desktop/in progress/val.csv",    header = T)
#predicate A
pred = predict(learntmodel, node="A", myvalidation)
myvalidation$A <- pred

#predicate B
pred = predict(learntmodel, node="B", myvalidation)
myvalidation$B <- pred

此時,它將引發以下錯誤:

check.fit.vs.data中的錯誤(已擬合=對象,數據=數據,子集=對象[[node]] $ parents):
“ A”在節點和數據中具有不同數量的級別。

bnlearn無法同時使用混合變量(定性和定量),我讀到有可能在deal包中使用。

另一種可能性是使用discretize將連續變量轉換為離散變量:

dmydata <- discretize(mydata, breaks = 2, method = "interval")

model <- gs(dmydata, whitelist = whitelist, blacklist = blacklist)

...並繼續您的代碼。

實際上,我今天遇到了同樣的問題,我通過確保與所討論的那個節點連接的其他節點(即$ A)也具有相同數量的級別來解決了該問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM