【问题标题】:How to plot 2x2 confusion matrix with predictions in rows an real values in columns?如何绘制 2x2 混淆矩阵,其中行中的预测和列中的实际值?
【发布时间】:2022-01-07 14:42:12
【问题描述】:

我知道我们可以使用以下示例代码用 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

【问题讨论】:

    标签: python machine-learning scikit-learn confusion-matrix


    【解决方案1】:

    (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]]
    

    【讨论】:

      【解决方案2】:

      不确定“绘制此图”是什么意思,但如果您只是想移动数据元素,您可以使用 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
      

      【讨论】:

      • "plot this" 表示混淆矩阵,其中行中的预测和列中的实际值作为实际绘图而不是文本输出
      • @Zion 您的问题中没有任何 plot (无论是否真实),只有文本输出。这里的帖子完全按照要求回答了这个问题。
      猜你喜欢
      • 2020-06-17
      • 1970-01-01
      • 2016-01-31
      • 2016-06-04
      • 2021-01-24
      • 2021-02-13
      • 2014-12-21
      • 2020-07-31
      相关资源
      最近更新 更多