R中的NaiveBayes无法预测
Posted
技术标签:
【中文标题】R中的NaiveBayes无法预测【英文标题】:NaiveBayes in R Cannot Predict 【发布时间】:2017-06-25 04:06:41 【问题描述】:我正在尝试使用 NaiveBayes 和使用 e1071 包的 Iris DataSet 进行一些分类,结果我无法像在 Rpart 中那样进行预测。如何解决这个问题,以便我可以基于我试图预测的 p4 构建混淆矩阵。
> table(iris$Species)
setosa versicolor virginica
50 50 50
> head(iris)
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
> set.seed(9850)
> g<-runif(nrow(iris))
> irisr <- iris[order(g),]
> m4 <- naiveBayes(Species~., data=irisr[1:100,], method="class")
> m4
Naive Bayes Classifier for Discrete Predictors
Call:
naiveBayes.default(x = X, y = Y, laplace = laplace, method = "class")
A-priori probabilities:
Y
setosa versicolor virginica
0.34 0.35 0.31
Conditional probabilities:
Sepal.Length
Y [,1] [,2]
setosa 5.000000 0.3797926
versicolor 5.857143 0.4545752
virginica 6.658065 0.7017949
Sepal.Width
Y [,1] [,2]
setosa 3.461765 0.4221264
versicolor 2.717143 0.3212894
virginica 2.990323 0.3543584
Petal.Length
Y [,1] [,2]
setosa 1.450000 0.1619016
versicolor 4.197143 0.4273624
virginica 5.600000 0.6066300
Petal.Width
Y [,1] [,2]
setosa 0.2558824 0.1159707
versicolor 1.2800000 0.1827889
virginica 2.0000000 0.2708013
> summary (m4)
Length Class Mode
apriori 3 table numeric
tables 4 -none- list
levels 3 -none- character
call 5 -none- call
> p4<- predict(m4, irisr[101:150,], type="class")
#Gives me this error ! How can I solve this ?
Error in UseMethod("predict") :
no applicable method for 'predict' applied to an object of class "naiveBayes"
【问题讨论】:
你应该指定你正在使用的包。我假设 e1071? 是的,我正在使用 e1071 包! 【参考方案1】:我知道答案了!
> m4 <- naiveBayes(as.factor(Species)~., data=irisr[1:100,], method="class")
> p4<-predict(m4, irisr[101:150,])
> p4
[1] virginica setosa versicolor virginica versicolor
[6] setosa setosa versicolor versicolor versicolor
[11] versicolor versicolor virginica setosa versicolor
[16] virginica virginica virginica versicolor virginica
[21] setosa virginica virginica setosa virginica
[26] setosa setosa versicolor setosa versicolor
[31] setosa virginica virginica virginica setosa
[36] virginica versicolor virginica setosa setosa
[41] virginica setosa virginica virginica virginica
[46] setosa virginica virginica virginica setosa
Levels: setosa versicolor virginica
> table(irisr[101:150,5], predicted=p4)
predicted
setosa versicolor virginica
setosa 16 0 0
versicolor 0 11 4
virginica 0 1 18
【讨论】:
以上是关于R中的NaiveBayes无法预测的主要内容,如果未能解决你的问题,请参考以下文章