我知道我們可以使用以下示例代碼使用 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
uj5u.com熱心網友回復:
(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]]

uj5u.com熱心網友回復:
不確定“繪制此”是什么意思,但是如果您只是想移動資料元素,則可以使用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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/373175.html
