朴素贝叶斯分类(e1071)无法工作($levels返回NULL)

6

我使用naiveBayes(e1071 http://en.wikibooks.org/wiki/Data_Mining_Algorithms_In_R/Classification/Na%C3%AFve_Bayes)对我的数据集进行分类(分类类别:“class”0/1)。这是我的做法:

library(e1071)
arrhythmia <- read.csv(file="/home/.../arrhythmia.csv", head=TRUE, sep=",")

#devide into training and test data 70:30
trainingIndex <- createDataPartition(arrhythmia$class, p=.7, list=F)
arrhythmia.training <- arrhythmia[trainingIndex,]
arrhythmia.testing <- arrhythmia[-trainingIndex,]

nb.classifier <- naiveBayes(class ~ ., data = arrhythmia.training)
predict(nb.classifier,arrhythmia.testing[,-260])

分类器功能失效,以下是我获得的信息:
> predict(nb.classifier,arrhythmia.testing[,-260])
factor(0)
Levels: 

> str(arrhythmia.training)
'data.frame':   293 obs. of  260 variables:
 $ age                         : int  75 55 13 40 44 50 62 54 30 46 ...
 $ sex                         : int  0 0 0 1 0 1 0 1 0 1 ...
 $ height                      : int  190 175 169 160 168 167 170 172 170 158 ...
 $ weight                      : int  80 94 51 52 56 67 72 58 73 58 ...
 $ QRSduration                 : int  91 100 100 77 84 89 102 78 91 70 ...
 $ PRinterval                  : int  193 202 167 129 118 130 135 155 180 120 ...
 # and so on (260 attributes)

> str(arrhythmia.training[260])
'data.frame':   293 obs. of  1 variable:
 $ class: int  1 0 1 0 0 1 1 1 1 0 ...


> nb.classifier$levels
NULL

我尝试使用包含的数据集(鸢尾花)并一切正常。我的方法有什么问题吗?

2个回答

7

请确保您将类变量视为因子;即

nb.classifier <- naiveBayes(as.factor(class) ~ ., data = arrhythmia.training)

顺便说一下,你不需要在预测调用中排除类变量。

1

您的数据框中每个由字符串组成的变量都需要被视为因子。

如果该变量不是因子,请使用以下命令:

    df$var1 <- as.factor(df$var1)

这包括类变量。
注意:如果一个变量是数字,你不需要将它转换为因子。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接