首页 > 解决方案 > 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)

此外,我已经尝试通过使用以下问题中的想法来修复它:

  1. ConfusionMatrix 中的错误数据和参考因素必须具有相同数量的水平 R CARET

  2. 混淆矩阵中的错误:数据和参考因素必须具有相同的水平数

但这对我没有帮助。

你能帮我解决这个错误吗?

如有任何想法和意见,我将不胜感激。在此先感谢您。

标签: rrandom-forestr-caretconfusion-matrix

解决方案


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,非常感谢你)


推荐阅读