gpt4 book ai didi

r - R 中的 NaiveBayes 无法预测 - 因子 (0) 级别 :

转载 作者:行者123 更新时间:2023-11-30 08:23:22 27 4
gpt4 key购买 nike

我有一个如下所示的数据集:

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 函数没有返回任何内容?

# 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 帮助手册中的示例进行操作,它对我有用。我不确定我的方法有什么问题。非常感谢!

我认为在应用 naivebayes 模型之前数据类型可能有问题,我尝试使用 as.factor 将所有变量更改为因子,这似乎对我有用。但我仍然非常困惑幕后的“如何”和“为什么”是什么。

最佳答案

问题不在于 predict() 函数,而在于您的模型定义。

naiveBayes() 的帮助文件说:

Computes the conditional a-posterior probabilities of a categorical class variable 
given independent predictor variables using the Bayes rule.

因此 y 值应该是分类的,但在您的情况下它们是数字。

解决方案是将 flu 转换为因子。

model <- naiveBayes(as.factor(flu)~., data=data.flu)
predict(model, patient)
[1] 1
Levels: 0 1

关于r - R 中的 NaiveBayes 无法预测 - 因子 (0) 级别 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19961441/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com