Python 绘制混淆矩阵

这篇的文章的好多代码都源自于博客,我只是把他们重新整合,然后变成了我需要的漂亮的,适合放在论文中图片代码。 

参考链接:

https://blog.csdn.net/weixin_38314865/article/details/88989506

https://www.cnblogs.com/ZHANG576433951/p/11233159.html

https://blog.csdn.net/qq_37851620/article/details/100642566?utm_source=app&app_version=4.7.1

https://blog.csdn.net/Poul_henry/article/details/88294297

https://mathpretty.com/10675.html

import numpy as np
import itertools
import matplotlib.pyplot as plt


# 绘制混淆矩阵
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    Input
    - cm : 计算出的混淆矩阵的值
    - classes : 混淆矩阵中每一行每一列对应的列
    - normalize : True:显示百分比, False:显示个数
    """
    if normalize:
        matrix = cm
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')
    plt.figure()
    # 设置输出的图片大小
    figsize = 8, 6
    figure, ax = plt.subplots(figsize=figsize)
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    # 设置title的大小以及title的字体
    font_title= {'family': 'Times New Roman',
                  'weight': 'normal',
                  'size': 15,
                  }
    plt.title(title,fontdict=font_title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45,)
    plt.yticks(tick_marks, classes)
    # 设置坐标刻度值的大小以及刻度值的字体
    plt.tick_params(labelsize=15)
    labels = ax.get_xticklabels() + ax.get_yticklabels()
    print (labels)
    [label.set_fontname('Times New Roman') for label in labels]
    if normalize:
        fm_int = 'd'
        fm_float = '.3%'
        thresh = cm.max() / 2.
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            plt.text(j, i, format(cm[i, j], fm_float),
                     horizontalalignment="center", verticalalignment='bottom',family = "Times New Roman", weight = "normal",size = 15,
                     color="white" if cm[i, j] > thresh else "black")
            plt.text(j, i, format(matrix[i, j], fm_int),
                     horizontalalignment="center", verticalalignment='top',family = "Times New Roman", weight = "normal",size = 15,
                     color="white" if cm[i, j] > thresh else "black")
    else:
        fm_int = 'd'
        thresh = cm.max() / 2.
        for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
            plt.text(j, i, format(cm[i, j], fm_int),
                     horizontalalignment="center", verticalalignment='bottom',
                     color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    # 设置横纵坐标的名称以及对应字体格式
    # font_lable = {'family': 'Times New Roman',
    #               'weight': 'normal',
    #               'size': 15,
    #               }
    # plt.ylabel('True label', font_lable)
    # plt.xlabel('Predicted label', font_lable)

    plt.savefig('confusion_matrix.eps', dpi=600, format='eps')
    plt.savefig('confusion_matrix.png', dpi=600, format='png')


cnf_matrix = np.array([[109653, 2, 0, 1, 0],
                       [0, 104180, 2, 0, 0],
                       [1, 0, 110422, 1, 0],
                       [9, 1, 1, 104380, 0],
                       [13, 0, 0, 3, 767875]])
attack_types = ['Normal', 'DoS', 'Probe', 'R2L', 'U2R']

plot_confusion_matrix(cnf_matrix, classes=attack_types, normalize=True, title='Normalized confusion matrix')

 

  • 1
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Python绘制混淆矩阵,可以使用sklearn.metrics包的confusion_matrix函数。首先,需要将预测结果和真实标签以类似的格式赋值给y_pred和y_true变量。然后,可以使用confusion_matrix函数生成混淆矩阵C,可以通过labels参数指定类别的标签。接下来,可以使用matplotlib.pyplot的函数绘制矩阵图,使用plt.matshow(C, cmap=plt.cm.Reds)来展示混淆矩阵的颜色。可以使用plt.annotate函数在矩阵图显示每个元素的值。最后,可以使用plt.xlabel和plt.ylabel函数设置x轴和y轴的标签。最后,使用plt.show函数显示绘制好的混淆矩阵图。 [1 [2] 示例代码如下: ```python from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt y_pred = [] # 预测结果 y_true = [] # 真实标签 C = confusion_matrix(y_true, y_pred, labels=['0','1','2','3','4']) plt.matshow(C, cmap=plt.cm.Reds) for i in range(len(C)): for j in range(len(C)): plt.annotate(C[j, i], xy=(i, j), horizontalalignment='center', verticalalignment='center') plt.ylabel('True label') plt.xlabel('Predicted label') plt.show() ``` 这段代码会根据给定的预测结果和真实标签生成混淆矩阵,并使用矩阵图展示混淆矩阵的颜色。每个元素表示预测为某个类别的样本数量。通过调整代码的参数和标签,可以根据不同的需求进行自定义。 [1 [2 [3<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [详解使用python绘制混淆矩阵(confusion_matrix)](https://download.csdn.net/download/weixin_38580959/12861679)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [利用python绘制混淆矩阵](https://blog.csdn.net/weixin_43818631/article/details/121309660)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值