Python 如何计算由多列导出的混淆矩阵?
我有两个数据帧,我想计算一个混淆矩阵 以下是“df_响应”的结构示例:Python 如何计算由多列导出的混淆矩阵?,python,scikit-learn,confusion-matrix,Python,Scikit Learn,Confusion Matrix,我有两个数据帧,我想计算一个混淆矩阵 以下是“df_响应”的结构示例: Question 1 | Red | Blue | Yellow | None of the Above | Participant ID | | | | | 1 | 1 | 1 | 1 | 0 | 2 |
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 |
Question 1 | Red | Blue | Yellow | None of the Above |
| | | | |
1 | 1 | 0 | 1 | 0 |
2 | 1 | 0 | 1 | 0 |
3 | 1 | 0 | 1 | 0 |
下面是“df_actual”的结构示例:
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 |
Question 1 | Red | Blue | Yellow | None of the Above |
| | | | |
1 | 1 | 0 | 1 | 0 |
2 | 1 | 0 | 1 | 0 |
3 | 1 | 0 | 1 | 0 |
理想情况下,我还希望创建一个新的数据框架,其中包含每个参与者的真阳性和假阴性分数,如下所示:
Question 1 | True Positive | False Negative |
Participant ID | | |
1 | 2 | 0 |
2 | 0 | 2 |
3 | 2 | 0 |
我试过(@johnmommers):
然而,我得到了一份工作
ValueError: multilabel-indicator is not supported.
有没有其他方法可以计算TP和FN
添加(数据为文本):
您不能以这种方式使用
sklearn
函数conflusion\u matrix
,因为它只支持一维标签,在您的情况下,您有四个标签。这就是为什么会出现错误多标签指示器不受支持的原因
因此,您必须将数据帧的每一行传递给此函数
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}')
您可以通过以下方式创建所需的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出现错误的原因。您可以使用
df.to_dict()
以文本形式重新发布数据吗?是的,我添加了它!参与者2的真阳性是什么?参与者2的真阳性是零