r - R:RF模型中的混淆矩阵返回错误:data`和`reference`应该是具有相同水平的因素
问题描述
我是 R 的新手,想解决二进制分类任务。
数据集的因子变量 LABELS 有 2 个类:第一个 - 0,第二个 - 1。下一张图片显示了它的实际头部: TimeDate 列 - 它只是索引。类分布定义为:
print("the number of values with % in factor variable - LABELS:")
percentage <- prop.table(table(dataset$LABELS)) * 100
cbind(freq=table(dataset$LABELS), percentage=percentage)
我也知道 Slot2 列是根据公式计算的:
Slot2 = Var3 - Slot3 + Slot4
Var1,Var2,Var3,Var4 特征是在分析相关矩阵后选择的。
在开始建模之前,我将数据集划分为训练和测试部分。我尝试使用下一个代码为二进制分类任务构建随机森林模型:
rf2 <- randomForest(LABELS ~ Var1 + Var2 + Var3 + Var4,
data=train, ntree = 100,
mtry = 4, importance = TRUE)
print(rf2)
结果是:
Call:
randomForest(formula = LABELS ~ Var1 + Var2 + Var3 + Var4,
data = train, ntree = 100, mtry = 4, importance = TRUE)
Type of random forest: classification
Number of trees: 100
No. of variables tried at each split: 4
OOB estimate of error rate: 0.16%
Confusion matrix:
0 1 class.error
0 164957 341 0.002062941
1 280 233739 0.001196484
当我尝试进行预测时:
# Prediction & Confusion Matrix - train data
p1 <- predict(rf2, train, type="prob")
print("Prediction & Confusion Matrix - train data")
confusionMatrix(p1, train$LABELS)
# # Prediction & Confusion Matrix - test data
p2 <- predict(rf2, test, type="prob")
print("Prediction & Confusion Matrix - test data")
confusionMatrix(p2, test$LABELS)
我在 R 中收到一个错误:
[1] "Prediction & Confusion Matrix - train data"
Error: `data` and `reference` should be factors with the same levels.
Traceback:
1. confusionMatrix(p1, train$LABELS)
2. confusionMatrix.default(p1, train$LABELS)
3. stop("`data` and `reference` should be factors with the same levels.",
. call. = FALSE)
此外,我已经尝试通过使用以下问题中的想法来修复它:
但这对我没有帮助。
你能帮我解决这个错误吗?
如有任何想法和意见,我将不胜感激。在此先感谢您。
解决方案
R中的错误:
Error: `data` and `reference` should be factors with the same levels.
通过更改预测函数中的类型参数来修复,正确的代码:
# Prediction & Confusion Matrix - train data
p1 <- predict(rf2, train, type="response")
print("Prediction & Confusion Matrix - train data")
confusionMatrix(p1, train$LABELS)
@Camille,非常感谢你)
推荐阅读
- r - 替换 r 中的字符串模式
- google-apps-script - 包括已更改单元格的整行
- node.js - 运行示例测试时出现赛普拉斯错误。赛普拉斯崩溃并显示错误 ECONNRESET
- computational-geometry - 如何从 vtkMarchingSquares 获得定向轮廓
- cognos - Cognos 图 - 根据不同维度的值指定样式
- rabbitmq - Spring streamBridge 在启动时创建rabbitmq队列
- android - Android ViewModel 正在泄漏
- xamarin.forms - Xamarin.Forms 中的设置列表
- sql - Sql需要对列进行多次求和并将结果水平拆分为一行
- python-3.x - Django 单元测试句柄 PermissionDenied