python绘制混淆矩阵

之前就了解过混淆矩阵,但是一直没有实践,今天刚好有数据实践一下,这里记录一下代码实现过程,方便以后查阅。

关于混淆矩阵,在这篇博客也提到过:机器学习|模型评估——AUC

matplotlib实现

import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
def plot_confusion_matrix(cm, labels_name, title, colorbar=False, cmap=None):
    plt.imshow(cm, interpolation='nearest', cmap=cmap)    # 在特定的窗口上显示图像
    for i in range(len(cm)):
        for j in range(len(cm)):
            plt.annotate(cm[j, i], xy=(i, j), horizontalalignment='center', verticalalignment='center')
    if colorbar:
        plt.colorbar()
    num_local = np.array(range(len(labels_name)))    
    plt.xticks(num_local, labels_name)    # 将标签印在x轴坐标上
    plt.yticks(num_local, labels_name)    # 将标签印在y轴坐标上
    plt.title(title)    # 图像标题
    plt.ylabel('True label')    
    plt.xlabel('Predicted label')
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]
cm = confusion_matrix(y_true, y_pred)
print(cm)

在这里插入图片描述

plot_confusion_matrix(cm, ["ant", "bird", "cat"], "Confusion Matrix")

在这里插入图片描述

sklearn实现

sklearn.metrics.ConfusionMatrixDisplay

在这里插入图片描述

from_estimator

在这里插入图片描述

from_predictions

在这里插入图片描述
在这里插入图片描述

代码实现

from sklearn.metrics import confusion_matrix
from sklearn.metrics import ConfusionMatrixDisplay
y_true = [2, 0, 2, 2, 0, 1]
y_pred = [0, 0, 2, 2, 0, 2]
ConfusionMatrixDisplay.from_predictions(y_true, y_pred, display_labels=["ant", "bird", "cat"], cmap=plt.cm.Reds, colorbar=True)
plt.title("Confusion Matrix")

在这里插入图片描述

颜色参考

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述在这里插入图片描述
在这里插入图片描述

参考资料

Python中生成并绘制混淆矩阵(confusion matrix)

利用python绘制混淆矩阵

Visualizations with Display Objects

sklearn.metrics.ConfusionMatrixDisplay

  • 9
    点赞
  • 84
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值