【发布时间】:2016-06-25 20:00:55
【问题描述】:
我在 R 中有一个 bnlearn 模型,它是使用具有 4 个分类变量和 8 个数值变量的 gs 函数学习的。
当我尝试使用测试集验证我的模型时,在尝试预测某些节点时出现此错误:
check.fit.vs.data 中的错误(拟合 = 对象,数据 = 数据,子集 = 对象[[节点]]$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 中的错误(拟合 = 对象,数据 = 数据,子集 = 对象[[节点]]$parents):
“A”在节点和数据中具有不同的级别数。
【问题讨论】:
-
请向我们展示您的代码;最好是重现问题的最小、完整示例。
-
那么,
mydata$A的级别数与myvalidation$A相同吗?根据另一条评论,除非您提供您的数据,否则几乎不可能为您提供帮助。 -
是的。 mydata$A 和 myvalidation$A 的级别数相同。准确地说是 2。
-
你能用
table(mydata$A, myvalidation$A, exclude=NULL)编辑你的问题吗?这会返回什么all.equal(sort(unique(mydata$A)), sort(unique(myvalidation$A)))
标签: r