我的数据集看起来像这样:
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 flu1 1 0 M 1 02 1 1 N 0 13 1 0 S 1 14 0 1 M 1 15 0 0 N 0 06 0 1 S 1 17 0 1 S 0 08 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
函数对我返回空值?
# 我可以看到模型已经成功创建。model <- naiveBayes(flu~., data=data.flu)# 我创建了一个新的数据patient <- data.frame(chills = c(1), runnyNose = c(0), headache = c("M"), fever = c(1))> predict(model, patient)factor(0)Levels:# 我尝试用训练数据,仍然不起作用> predict(model, data.flu[,-5])factor(0)Levels:
我按照naiveBayes帮助手册中的示例尝试过,它对我来说是有效的。我不确定我的方法哪里出了问题。非常感谢!
我认为在应用naivebayes模型之前,数据类型可能有问题,我尝试使用as.factor
将所有变量转换为因子,看起来对我有效。但我仍然非常困惑幕后是如何运作的以及为什么会这样。
回答:
问题不在于predict()
函数,而在于你的模型定义。
naiveBayes()
的帮助文件中说:
使用贝叶斯规则计算给定独立预测变量的分类类变量的条件后验概率。
所以y值应该是分类变量,但在你的情况下它们是数值型的。
解决方案是将flu
转换为因子。
model <- naiveBayes(as.factor(flu)~., data=data.flu)predict(model, patient)[1] 1Levels: 0 1