如何用Python绘制预测值为行、真实值为列的2x2混淆矩阵
解决方法
你可以通过调整confusion_matrix的传入参数顺序和标签顺序快速实现需求,以下是可直接运行的修改后代码:
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') # 核心调整:交换y_true和y_pred的传入位置,标签顺序改为正类1在前、负类0在后 cm = confusion_matrix(y_pred, y_true, labels=[1, 0]) print(cm) disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=[1, 0]) disp.plot() # 手动指定轴含义,避免默认显示歧义 plt.xlabel('真实标签') plt.ylabel('预测标签') plt.show()
运行后输出的混淆矩阵结构完全符合你的要求:
TP | FP FN | TN
原理说明
- sklearn的
confusion_matrix默认第一个参数对应行标签,第二个参数对应列标签,因此交换y_true和y_pred的传入顺序,就能实现行是预测值、列是真实值的结构。 - 原标签顺序是
[0,1](负类在前正类在后),所以TN在左上角,把标签顺序改为[1,0]正类在前,就可以把TP移到左上角的位置。
如果你不想修改confusion_matrix的入参,也可以直接对原始混淆矩阵做变换,效果完全一致:
# 先拿到默认结构的混淆矩阵 cm = confusion_matrix(y_true, y_pred, labels=[0, 1]) # 转置交换行列对应关系 + 反转行和列顺序把正类移到前面 cm_adjusted = cm.T[::-1, ::-1] disp = ConfusionMatrixDisplay(confusion_matrix=cm_adjusted, display_labels=[1, 0]) disp.plot() plt.xlabel('真实标签') plt.ylabel('预测标签') plt.show()
内容的提问来源于stack exchange,提问作者Zion
相关产品推荐
相关产品推荐

