我想用bnlearn
与朴素贝叶斯算法分类任务。
我用this数据我的测试设置。其中3个变量是连续的()V2,V4,V10)和其它的是离散的。据我所知bnlearn
不能连续变量的工作,因此有必要将它们转换为因素或离散化。现在,我想所有的功能转化为因素。然而,我遇到了一些问题。下面是一个示例代码
dataSet <- read.csv("creditcard_german.csv", header=FALSE)
# ... split into trainSet and testSet ...
trainSet[] <- lapply(trainSet, as.factor)
testSet[] <- lapply(testSet, as.factor)
# V25 is the class variable
bn = naive.bayes(trainSet, training = "V25")
fitted = bn.fit(bn, trainSet, method = "bayes")
pred = predict(fitted , testSet)
...
对于这个代码我得到一个错误信息,同时呼吁predict()
“V1”具有不同数量的节点,在数据电平的。
当我从训练集去除V1,我得到了V2变量相同的错误。然而,当我做分解dataSet [] <- lapply(dataSet, as.factor)
,仅比它分割为训练和测试集的错误消失。
因此,这是对这个优雅的解决方案?因为在现实世界的应用测试和训练集可以是从不同的来源。有任何想法吗?
这个问题似乎被事实证明我的训练和测试数据集有不同的因子水平造成的。我使用rbind
命令将两个不同的dataframes(火车和测试)相结合,应用as.factor
得到全套的因素的完整数据集,然后切片因式分解数据帧回单独训练和测试数据集,解决了这个问题。
train <- read.csv("train.csv", header=FALSE)
test <- read.csv("test.csv", header=FALSE)
len_train = dim(train)[1]
len_test = dim(test)[1]
complete <- rbind(learn, test)
complete[] <- lapply(complete, as.factor)
train = complete[1:len_train, ]
l = len_train+1
lf = len_train + len_test
test = complete[l:lf, ]
bn = naive.bayes(train, training = "V25")
fitted = bn.fit(bn, train, method = "bayes")
pred = predict(fitted , test)
我希望这可以帮助。