r - 在测试和训练数据集上使用朴素贝叶斯函数
问题描述
我正在尝试在训练和测试数据集上使用 NaiveBayes 函数。我正在使用这个有用的网站:https ://rpubs.com/riazakhan94/naive_bayes_classifier_e1071
但是,由于某种原因它不起作用,这是我得到的错误:“表中的错误(train$Class,trainPred):所有参数必须具有相同的长度。”
这是我正在使用的代码,我猜它是一个超级简单的修复。数据集的 x 和 y 列在类列上进行预测:
https://github.com/samuelc12359/NaiveBayes.git
test <- read.csv(file="TestX.csv",header=FALSE)
train <- read.csv(file="TrainX.csv",header=FALSE)
Names <- c("x","y","Class")
colnames(test)<- Names
colnames(train)<- Names
NBclassfier=naiveBayes(Class~x+y, data=train)
print(NBclassfier)
trainPred=predict(NBclassfier,train, type="class")
trainTable=table(train$Class, trainPred)
testPred=predict(NBclassfier, newdata=test, type="class")
testTable=table(test$Class, testPred)
print(trainTable)
print(testTable)
解决方案
您需要将Class
列转换为因子,例如:
train$Class = factor(train$Class)
test$Class = factor(test$Class)
然后,当您调用naiveBayes()
训练并随后进行预测时,它会按照您的预期进行。
或者,您可以将预测类型更改为"raw"
并将它们直接转换为结果。比如像这样:
train_predictions = predict(NBclassfier,train, type="raw")
trainPred = 1 * (train_predictions[, 2] >= 0.5 )
trainTable=table(train$Class, trainPred)
test_predictions = predict(NBclassfier, newdata=test, type="raw")
testPred = 1 * (test_predictions[, 2] >= 0.5 )
testTable=table(test$Class, testPred)
print(trainTable)
print(testTable)
推荐阅读
- javascript - vue中页面刷新后如何显示加载的数据?
- mysql - MYSQL在由另一列排序的列中选择特定数量的重复值
- r - 为河图创建边
- javascript - 为点击事件定义和调用函数而不是内联函数
- django - 尝试使用子查询计算时差时出错
- uwp - Windows 应用商店不允许使用 runFullTrust 提交应用程序
- python - 动态构建代码并在 .write() python 中使用
- airflow - 气流 python 通过 XCOM 处理返回值
- spring-boot - 使用 Redis 服务器的用例
- javascript - 重新加载后相同的功能不给出相同的结果