R中的NaiveBayes无法预测 – factor(0) Levels:

我的数据集看起来像这样:

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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注