R包插入符号混乱矩阵缺少类别

Bar*_*ker 8 r missing-data confusion-matrix r-caret

我使用的功能confusionMatrix[Rcaret来计算一些数据我有一些统计数字.我一直把我的预测以及我的实际值放到函数中,以便tableconfusionMatrix函数中使用表格,如下所示:

table(predicted,actual)
Run Code Online (Sandbox Code Playgroud)

但是,有多种可能的结果(例如A,B,C,D),我的预测并不总是代表所有可能性(例如只有A,B,D).table函数的结果输出不包括缺少的结果,如下所示:

    A    B    C    D
A  n1   n2   n2   n4  
B  n5   n6   n7   n8  
D  n9  n10  n11  n12
# Note how there is no corresponding row for `C`.
Run Code Online (Sandbox Code Playgroud)

confusionMatrix函数无法处理缺失的结果并给出错误:

Error in !all.equal(nrow(data), ncol(data)) : invalid argument type
Run Code Online (Sandbox Code Playgroud)

有没有一种方法可以使用table不同的函数来获取缺少的零行或使用confusionMatrix不同的函数,以便将缺失的结果视为零?

作为注释:由于我随机选择要测试的数据,有时候实际结果中也没有表示类别,而只是预测.我不相信这会改变解决方案.

Bor*_*lis 22

您可以使用union以确保类似的级别:

library(caret)

# Sample Data
predicted <- c(1,2,1,2,1,2,1,2,3,4,3,4,6,5) # Levels 1,2,3,4,5,6
reference <- c(1,2,1,2,1,2,1,2,1,2,1,3,3,4) # Levels 1,2,3,4

u <- union(predicted, reference)
t <- table(factor(predicted, u), factor(reference, u))
confusionMatrix(t)
Run Code Online (Sandbox Code Playgroud)


fot*_*ton 5

首先要注意的是,除了使用对象调用之外,confusionMatrix还可以调用它.但是,如果和(都被视为s)没有相同数量的级别,则该函数会抛出错误.confusionMatrix(predicted, actual)tablepredictedactualfactor

这个(以及caret包因为他们没有首先获得依赖关系而向我发出错误的事实)是我建议创建自己的函数的原因:

# Create a confusion matrix from the given outcomes, whose rows correspond
# to the actual and the columns to the predicated classes.
createConfusionMatrix <- function(act, pred) {
  # You've mentioned that neither actual nor predicted may give a complete
  # picture of the available classes, hence:
  numClasses <- max(act, pred)
  # Sort predicted and actual as it simplifies what's next. You can make this
  # faster by storing `order(act)` in a temporary variable.
  pred <- pred[order(act)]
  act  <- act[order(act)]
  sapply(split(pred, act), tabulate, nbins=numClasses)
}

# Generate random data since you've not provided an actual example.
actual    <- sample(1:4, 1000, replace=TRUE)
predicted <- sample(c(1L,2L,4L), 1000, replace=TRUE)

print( createConfusionMatrix(actual, predicted) )
Run Code Online (Sandbox Code Playgroud)

这会给你:

      1  2  3  4
[1,] 85 87 90 77
[2,] 78 78 79 95
[3,]  0  0  0  0
[4,] 89 77 82 83
Run Code Online (Sandbox Code Playgroud)