如何绘制 2x2 混淆矩阵,行中有预测,列中有实际值?

How to plot 2x2 confusion matrix with predictions in rows an real values in columns?

我知道我们可以使用以下示例代码使用 sklearn 绘制混淆矩阵。

from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt

y_true = [1, 0, 1, 1, 0, 1]
y_pred = [0, 0, 1, 1, 0, 1]

print(f'y_true: {y_true}')
print(f'y_pred: {y_pred}\n')

cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
print(cm)
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
disp.plot()
plt.show()

我们有:

TN | FP
FN | TP

但我希望将预测标签放在行或 y 轴上,将真值或实际值标签放在列或 x 轴上。如何使用 Python?

绘制此图

我想要的:

TP | FP
FN | TN

不确定“绘制此图”是什么意思,但如果您只是想移动数据元素,则可以使用 iloc[] 和赋值

df

    0   1
0   TN  FP
1   FN  TP


df.iloc[0,0], df.iloc[1,1]=df.iloc[1,1],df.iloc[0,0]

df
    0   1
0   TP  FP
1   FN  TN

(1) 这是一种反转 TP/TN.

的方法

代码

"""
Reverse True and Prediction labels

References:
    https://github.com/scikit-learn/scikit-learn/blob/0d378913b/sklearn/metrics/_plot/confusion_matrix.py
    https://scikit-learn.org/stable/modules/generated/sklearn.metrics.ConfusionMatrixDisplay.html
"""

from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay
import matplotlib.pyplot as plt

y_true = [1, 0, 1, 1, 0, 1]
y_pred = [0, 0, 1, 1, 0, 1]

print(f'y_true: {y_true}')
print(f'y_pred: {y_pred}\n')

# Normal
print('Normal')
cm = confusion_matrix(y_true, y_pred, labels=[0, 1])
print(cm)
disp = ConfusionMatrixDisplay(confusion_matrix=cm)
disp.plot()

plt.savefig('normal.png')
plt.show()

# Reverse TP and TN
print('Reverse TP and TN')
cm = confusion_matrix(y_pred, y_true, labels=[1, 0])  # reverse true/pred and label values
print(cm)
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[1, 0])  # reverse display labels
dp = disp.plot()
dp.ax_.set(ylabel="My Prediction Label")  # modify ylabel of ax_ attribute of plot
dp.ax_.set(xlabel="My True Label")        # modify xlabel of ax_ attribute of plot

plt.savefig('reverse.png')
plt.show()

输出

y_true: [1, 0, 1, 1, 0, 1]
y_pred: [0, 0, 1, 1, 0, 1]

Normal
[[2 0]
 [1 3]]

Reverse TP and TN
[[3 0]
 [1 2]]

(2) 另一种方法是交换值并用 sns/matplotlib.

绘制它

代码

import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt


y_true = [1, 0, 1, 1, 0, 1]
y_pred = [0, 0, 1, 1, 0, 1]

cm = confusion_matrix(y_true, y_pred)
print(cm)
cm_11 = cm[1][1]     # backup value in cm[1][1]
cm[1][1] = cm[0][0]  # swap
cm[0][0] = cm_11     # swap
print(cm)

ax = sns.heatmap(cm, annot=True)

plt.yticks([1.5, 0.5], ['0', '1'], ha='right')
plt.xticks([1.5, 0.5], ['0', '1'], ha='right')

ax.set(xlabel='True Label', ylabel='Prediction Label')
plt.savefig('reverse_tp_tn.png')
plt.show()

输出

[[2 0]
 [1 3]]
[[3 0]
 [1 2]]