【问题标题】:How to compute a confusion matrix derived from multiple columns?如何计算从多列派生的混淆矩阵?
【发布时间】:2021-04-28 05:51:35
【问题描述】:

我有两个要计算混淆矩阵的 DataFrame。

以下是“df_responses”结构的示例:

Question 1      |  Red  |  Blue  | Yellow | None of the Above |   
Participant ID  |       |        |        |                   |
1               |   1   |    1   |    1   |       0           |
2               |   0   |    0   |    0   |       1           |
3               |   1   |    0   |    1   |       0           |

以下是“df_actual”的结构示例:

Question 1      |  Red  |  Blue  | Yellow | None of the Above |   
                |       |        |        |                   |
1               |   1   |    0   |    1   |       0           |
2               |   1   |    0   |    1   |       0           |
3               |   1   |    0   |    1   |       0           |

理想情况下,我还想创建一个新的 DataFrame,其中包含每个参与者的 True Positive 和 False Negative 分数,如下所示:

Question 1      | True Positive | False Negative | 
Participant ID  |               |                | 
1               |     2         |       0        |
2               |     0         |       2        |
3               |     2         |       0        | 

我试过了(@John Mommers):

for x in range(len(df_responses)):
    tn, fp, fn, tp = confusion_matrix(df_responses, df_actual).ravel()
    print (f'Nr:{i}  true neg:{tn}  false pos:{fp}   false neg:{fn}   true pos:{tp}')

但是,我得到了一个

ValueError: multilabel-indicator is not supported. 

是否有其他方法可以计算 TP 和 FN?


加法(数据作为文本):

df_responses

{'Red': {1: 1, 2: 0, 3: 1},
'Blue': {1: 1, 2: 0, 3: 0},
'Yellow': {1: 1, 2: 0, 3: 1},
'None of the above': {1: 0, 2: 1, 3: 0}}

df_actual

{'Red': {1: 1, 2: 1, 3: 1},
'Blue': {1: 0, 2: 0, 3: 0},
'Yellow': {1: 1, 2: 1, 3: 1},
'None of the above': {1: 0, 2: 0, 3: 0}}
  

【问题讨论】:

  • 你能用df.to_dict()将你的数据作为文本重新发布吗?
  • 是的,我已经添加了!
  • 参与者2的真阳性是什么
  • 参与者2的真阳性为零

标签: python scikit-learn confusion-matrix


【解决方案1】:

你可以创建你想要的df,例如:

df = pd.DataFrame()   
df["tp"] = np.sum((df_actual == 1) & (df_responses == 1), axis=1)
df["fp"] = np.sum((df_actual == 0) & (df_responses == 1), axis=1)

请注意,这并不是真正的混淆矩阵 - 在这种情况下,您的行是预测的,列是标签值(反之亦然),值作为计数。对于多值标签/响应,这可能没有明确定义,这就是您在使用 sklearn 时遇到错误的原因。

【讨论】:

    【解决方案2】:

    您不能以这种方式使用sklearn 函数confusion_matrix,因为它仅支持一维标签,而在您的情况下,您有四个标签。这就是您收到错误 multilabel-indicator is not supported 的原因。

    所以你必须将数据框的每一行都传递给这个函数。

    for x in range(len(df_responses)):
       y_responses = df_responses.iloc[x].to_numpy()
       y_actual = df_actual.iloc[x].to_numpy()
       tn, fp, fn, tp = confusion_matrix(y_responses, y_actual).ravel()
       print (f'Nr:{i} true neg:{tn} false pos:{fp} false neg:{fn} true pos:{tp}')
    

    【讨论】:

      猜你喜欢
      • 2017-02-25
      • 2018-04-01
      • 2018-04-16
      • 1970-01-01
      • 2017-09-25
      • 2018-10-30
      • 2012-05-29
      • 2020-03-23
      相关资源
      最近更新 更多