【问题标题】:Error: `data` and `reference` should be factors with the same levels. Using confusionMatrix (caret)错误:`data` 和 `reference` 应该是相同级别的因素。使用confusionMatrix(插入符号)
【发布时间】:2019-06-20 00:53:44
【问题描述】:

使用caret 包中的confusionMatrix() 函数时出现错误。为了重现该示例,我使用了 mlbench 包中的 Sonar 数据集。

library(mlbench)
data(Sonar)

rows <- sample(nrow(Sonar))
Sonar <- Sonar[rows, ]


split <- round(nrow(Sonar) * 0.6)
adiestramiento <- Sonar[1:split, ]
experimental <- Sonar[(split + 1):nrow(Sonar), ]

model <- glm(Class ~ ., family = binomial(link = "logit"), adiestramiento)
p <- predict(model, experimental, type = "response")
p_class <- ifelse(p > 0.5, "M", "R")

library(caret)
confusionMatrix(p_class, experimental[["Class"]])

我在运行confusionMatrix() 时遇到的错误是

错误:datareference 应该是相同级别的因子`

我检查了p_classexperimental[["Class"]] 具有相同数量的对象 (83)。

知道发生了什么吗?

【问题讨论】:

    标签: r r-caret confusion-matrix


    【解决方案1】:

    问题在于data 或者在这种情况下p_class 必须是一个因素。所以,我们应该使用

    confusionMatrix(factor(p_class), experimental[["Class"]])
    # Confusion Matrix and Statistics
    # 
    #           Reference
    # Prediction  M  R
    #          M 17 20
    #          R 33 13
    # ...
    

    【讨论】:

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