【问题标题】:R Generic solution to create 2*2 confusion matrixR创建2 * 2混淆矩阵的通用解决方案
【发布时间】:2014-09-11 13:33:17
【问题描述】:

我的问题与one 有关使用table() 函数在R 中生成混淆矩阵有关。我正在寻找不使用包(例如插入符号)的解决方案。

假设这些是我们在二元分类问题中的predictionslabels

predictions <- c(0.61, 0.36, 0.43, 0.14, 0.38, 0.24, 0.97, 0.89, 0.78, 0.86, 0.15,  0.52, 0.74, 0.24)
labels      <- c(1,    1,    1,    0,    0,     1,    1,    1,    0,     1,    0,    0,    1,    0)

对于这些值,下面的解决方案可以很好地为阈值 = 0.5 创建一个 2*2 混淆矩阵:

# Confusion matrix for threshold = 0.5
conf_matrix <- as.matrix(table(predictions>0.5,labels))
  conf_matrix
     labels
       0 1
 FALSE 4 3
 TRUE  2 5

但是,如果我选择小于 min(predictions) 或大于 max(predictions) 的任何值,我不会得到 2*2 矩阵,因为数据不会出现 FALSE 或 TRUE,例如:

conf_matrix <- as.matrix(table(predictions>0.05,labels))
  conf_matrix
     labels
       0 1
  TRUE 6 8

我需要一种能够为 0 到 1 之间的所有可能阈值(决策边界)始终生成 2*2 混淆矩阵的方法,因为我将其用作优化中的输入。有没有办法可以调整 table 函数,让它总是在这里返回一个 2*2 矩阵?

【问题讨论】:

    标签: r confusion-matrix


    【解决方案1】:

    您可以将阈值预测作为因子变量来实现:

    (conf_matrix <- as.matrix(table(factor(predictions>0.05, levels=c(F, T)), labels)))
    #        labels
    #         0 1
    #   FALSE 0 0
    #   TRUE  6 8
    

    【讨论】:

    • 好的,谢谢!我尝试使用table() 参数,例如dnnexclude。但相反,我应该形成一个新因素来解释非发生类。
    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 2020-07-06
    • 2018-09-18
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多