R中的NaiveBayes无法预测-因子(0)级别: [英] NaiveBayes in R Cannot Predict - factor(0) Levels:
问题描述
我有一个像这样的数据集:
I have a dataset looks like this:
data.flu <- data.frame(chills = c(1,1,1,0,0,0,0,1), runnyNose = c(0,1,0,1,0,1,1,1), headache = c("M", "N", "S", "M", "N", "S", "S", "M"), fever = c(1,0,1,1,0,1,0,1), flu = c(0,1,1,1,0,1,0,1) )
> data.flu
chills runnyNose headache fever flu
1 1 0 M 1 0
2 1 1 N 0 1
3 1 0 S 1 1
4 0 1 M 1 1
5 0 0 N 0 0
6 0 1 S 1 1
7 0 1 S 0 0
8 1 1 M 1 1
> str(data.flu)
'data.frame': 8 obs. of 5 variables:
$ chills : num 1 1 1 0 0 0 0 1
$ runnyNose: num 0 1 0 1 0 1 1 1
$ headache : Factor w/ 3 levels "M","N","S": 1 2 3 1 2 3 3 1
$ fever : num 1 0 1 1 0 1 0 1
$ flu : num 0 1 1 1 0 1 0 1
为什么predict
函数什么也没给我返回?
Why predict
function returns me nothing?
# I can see the model has been successfully created.
model <- naiveBayes(flu~., data=data.flu)
# I created a new data
patient <- data.frame(chills = c(1), runnyNose = c(0), headache = c("M"), fever = c(1))
> predict(model, patient)
factor(0)
Levels:
# I tried with the training data, still won't work
> predict(model, data.flu[,-5])
factor(0)
Levels:
我尝试按照naiveBayes中的帮助手册中的示例进行操作,它对我有用.我不确定我的方法有什么问题.非常感谢!
I tried following the examples in the help manual in naiveBayes and it works for me. I am not sure what is wrong with my approach. Thanks a lot!
我认为在应用naivebayes模型之前,数据类型可能有问题,我尝试使用as.factor
更改所有变量以分解为因子,这似乎对我有用.但是我仍然非常困惑幕后的如何"和为什么".
I think there might be something wrong with the data type before applying the naivebayes model, I tried to change all the variables to factor using as.factor
and it seems like working for me. But I am still super confused what is the 'How' and 'Why' behind the scene.
推荐答案
问题不在predict()
函数中,而是在模型定义中.
Problem isn't in the predict()
function but in your model definition.
naiveBayes()
的帮助文件说:
Computes the conditional a-posterior probabilities of a categorical class variable
given independent predictor variables using the Bayes rule.
所以y值应该是分类的,但在您的情况下,它们是数字.
So y values should be categorical but in your case they are numeric.
解决方案是将flu
转换为因数.
Solution is to convert flu
to factor.
model <- naiveBayes(as.factor(flu)~., data=data.flu)
predict(model, patient)
[1] 1
Levels: 0 1
这篇关于R中的NaiveBayes无法预测-因子(0)级别:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!