[英]Classification with naiveBayes (e1071) does not work ($levels returns NULL)
我使用naiveBayes(e1071 http://en.wikibooks.org/wiki/Data_Mining_Algorithms_In_R/Classification/Na%C3%AFve_Bayes )对我的数据集进行分类(Classification class:“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
我试图使用包含数据集(虹膜),一切正常。 我的做法有什么问题?
确保将类变量视为因子; 即
nb.classifier <- naiveBayes(as.factor(class) ~ ., data = arrhythmia.training)
顺便说一句,您不需要从预测调用中排除类变量。
数据框中由字符串组成的每个变量都需要被视为一个因子。
如果变量不是因素,请使用以下命令:
df$var1 <- as.factor(df$var1)
这包括类变量。
注意:如果一个变量是数字,则不需要将其变为因子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.