【问题标题】:NaiveBayes in R Cannot Predict - factor(0) Levels:R 中的 NaiveBayes 无法预测 - 因子(0)水平:
【发布时间】:2013-11-26 12:09:17
【问题描述】:

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

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 将所有变量更改为因子,这似乎对我有用。但我仍然非常困惑幕后的“如何”和“为什么”。

【问题讨论】:

    标签: r machine-learning bayesian


    【解决方案1】:

    问题不在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
    

    【讨论】:

    • 嗯,非常感谢您的回答。我现在正在学习 naiveBayes,模型与我的手工计算一致。我想知道predict 确定 y==1 实际上如何具有更好的成本函数?成本函数在哪里?如何找到 R 中 y=0 和 y=1 的成本函数值?
    • 对不起,我无法回答这个问题,因为我对 naiveBayes 太熟悉了
    猜你喜欢
    • 2017-06-25
    • 2019-10-26
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多