问题描述
我正在使用 R 包caret
中的函数confusionMatrix
计算我拥有的某些数据的一些统计信息.我一直将自己的预测以及实际值放入table
函数中,以便按如下方式在confusionMatrix
函数中使用该表:
I am using the function confusionMatrix
in the R package caret
to calculate some statistics for some data I have. I have been putting my predictions as well as my actual values into the table
function to get the table to be used in the confusionMatrix
function as so:
table(predicted,actual)
但是,有多种可能的结果(例如A,B,C,D),而我的预测并不总是代表所有可能性(例如,仅A,B,D). table
函数的结果输出不包括缺少的结果,并且看起来像这样:
However, there are multiple possible outcomes (e.g. A, B, C, D), and my predictions do not always represent all the possibilities (e.g. only A, B, D). The resulting output of the table
function does not include the missing outcome and looks like this:
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`.
confusionMatrix
函数无法处理丢失的结果并给出错误:
The confusionMatrix
function can't handle the missing outcome and gives the error:
Error in !all.equal(nrow(data), ncol(data)) : invalid argument type
有没有办法我可以以不同的方式使用table
函数来获取缺失的零行,或者以不同的方式使用confusionMatrix
函数来将缺失的结果视为零?
Is there a way I can use the table
function differently to get the missing rows with zeros or use the confusionMatrix
function differently so it will view missing outcomes as zero?
请注意:由于我是随机选择要测试的数据,因此有时在实际结果中也没有代表类别,而不仅仅是预测.我认为这不会改变解决方案.
As a note: Since I am randomly selecting my data to test with, there are times that a category is also not represented in the actual result as opposed to just the predicted. I don't believe this will change the solution.
推荐答案
您可以使用union
确保相似的级别:
You can use union
to ensure similar levels:
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)
这篇关于R包插入符号混淆矩阵,缺少类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!