【问题标题】:Error: `data` and `reference` should be factors with the same levels错误:`data` 和 `reference` 应该是相同级别的因素
【发布时间】:2019-01-04 01:03:59
【问题描述】:

尝试使用 RandomForest 预测模型的准确性,但遇到以下错误。
错误:datareference 应该是具有相同水平的因子。

这是下面的代码

rfModel <- randomForest(Churn ~., data = training)
print(rfModel)
pred_rf <- predict(rfModel, testing)
caret::confusionMatrix(pred_rf, testing$Churn)
testing$Churn

训练和测试数据以 7:3 的比例拆分

在运行代码时也收到以下警告

Warning messages:
1: In get(results[[i]], pos = which(search() == packages[[i]])) :
  restarting interrupted promise evaluation
2: In get(results[[i]], pos = which(search() == packages[[i]])) :
  internal error -3 in R_decompress1

测试数据结构

str(testing)
'data.frame':   999 obs. of  18 variables:
 $ account_length        : int  84 75 147 141 65 62 85 93 76 73 ...
 $ International.plan    : Factor w/ 2 levels "No","Yes": 2 2 2 2 1 1 1 1 1 1 ...
 $ Voice.mail.plan       : Factor w/ 2 levels "No","Yes": 1 1 1 2 1 1 2 1 2 1 ...
 $ Number.vmail.messages : int  0 0 0 37 0 0 27 0 33 0 ...
 $ Total.day.minutes     : num  299 167 157 259 129 ...
 $ Total.day.calls       : int  71 113 79 84 137 70 139 114 66 90 ...
 $ Total.day.charge      : num  50.9 28.3 26.7 44 21.9 ...
 $ Total.eve.minutes     : num  61.9 148.3 103.1 222 228.5 ...
 $ Total.eve.calls       : int  88 122 94 111 83 76 90 111 65 88 ...
 $ Total.eve.charge      : num  5.26 12.61 8.76 18.87 19.42 ...
 $ Total.night.minutes   : num  197 187 212 326 209 ...
 $ Total.night.calls     : int  89 121 96 97 111 99 75 121 108 74 ...
 $ Total.night.charge    : num  8.86 8.41 9.53 14.69 9.4 ...
 $ Total.intl.minutes    : num  6.6 10.1 7.1 11.2 12.7 13.1 13.8 8.1 10 13 ...
 $ Total.intl.calls      : int  7 3 6 5 6 6 4 3 5 2 ...
 $ Total.intl.charge     : num  1.78 2.73 1.92 3.02 3.43 3.54 3.73 2.19 2.7 3.51 ...
 $ Customer.service.calls: int  2 3 0 0 4 4 1 3 1 1 ...
 $ Churn                 : chr  "0" "0" "0" "0" ...

训练集结构相同,有 2334 个观察值

pred_rf 的结构

 str(pred_rf)
 Factor w/ 2 levels "FALSE","TRUE": 1 1 1 1 2 2 1 1 1 1 ...
 - attr(*, "names")= chr [1:999] "4" "5" "8" "10" ...

请帮帮我。

【问题讨论】:

  • 你能提供最少的数据来重现错误吗?我怀疑训练和测试数据集之间的因子水平不同,但我不知道你的数据是什么样的
  • @George 我在我的问题中提供了我的数据结构。请再看看。谢谢
  • 绝对需要发布您的数据子集,例如使用dput,所以问题是可重现的,人们可以想象地解决它并为您提供答案。谢谢:)

标签: r machine-learning classification


【解决方案1】:

好的,我刚刚遇到了同样的问题并想通了。

查看您的str(testing),注意您的流失不是一个因素,而是一个chr

首先,您需要将 Churn 设置为一个因素,

Churn <- as.factor(testing$Churn)

再次检查您的str(testing),看看它实际上是否发生了变化。

现在你可以使用:

test_predictions = predict(rf_model, testing_set)
test_predictions

conf_matrix = confusionMatrix(test_predictions, Churn)
conf_matrix

见:https://community.rstudio.com/t/how-to-deal-with-rlang-errors/27248

【讨论】:

    猜你喜欢
    • 2020-03-16
    • 2021-12-20
    • 2021-03-18
    • 2019-11-21
    • 2019-06-20
    • 2020-09-17
    • 2021-09-20
    • 2020-08-16
    • 2020-08-17
    相关资源
    最近更新 更多