Matplotlib怎样绘制混淆矩阵,代码是什么
Admin 2022-07-23 群英技术资讯 603 次浏览
对于机器学习多分类模型来说,其评价指标除了精度之外,常用的还有混淆矩阵和分类报告,下面来展示一下如何绘制混淆矩阵,这在论文中经常会用到。
代码如下:
import itertools import matplotlib.pyplot as plt import numpy as np # 绘制混淆矩阵 def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues): """ - cm : 计算出的混淆矩阵的值 - classes : 混淆矩阵中每一行每一列对应的列 - normalize : True:显示百分比, False:显示个数 """ if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] print("显示百分比:") np.set_printoptions(formatter={'float': '{: 0.2f}'.format}) print(cm) else: print('显示具体数字:') print(cm) plt.imshow(cm, interpolation='nearest', cmap=cmap) plt.title(title) plt.colorbar() tick_marks = np.arange(len(classes)) plt.xticks(tick_marks, classes, rotation=45) plt.yticks(tick_marks, classes) # matplotlib版本问题,如果不加下面这行代码,则绘制的混淆矩阵上下只能显示一半,有的版本的matplotlib不需要下面的代码,分别试一下即可 plt.ylim(len(classes) - 0.5, -0.5) fmt = '.2f' if normalize else '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], fmt), horizontalalignment="center", color="white" if cm[i, j] > thresh else "black") plt.tight_layout() plt.ylabel('True label') plt.xlabel('Predicted label') plt.show()
测试数据:
cnf_matrix = np.array([[8707, 64, 731, 164, 45], [1821, 5530, 79, 0, 28], [266, 167, 1982, 4, 2], [691, 0, 107, 1930, 26], [30, 0, 111, 17, 42]]) attack_types = ['Normal', 'DoS', 'Probe', 'R2L', 'U2R']
plot_confusion_matrix(cnf_matrix, classes=attack_types, normalize=True, title='Normalized confusion matrix')
效果:
plot_confusion_matrix(cnf_matrix, classes=attack_types, normalize=False, title='Normalized confusion matrix')
效果:
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
在本文中,您将了解Python中的多重继承以及如何在程序中使用它。还将了解多级继承和方法解析顺序。
python中break语句与continue语句有什么区别?当代码执行到break时,就会立刻结束break所在的循环;break语句是结束整个循环的过程,不在判断执行循环的条件是否成立。
python的新式类是2 2版本引进来的,我们可以将之前的类叫做经典类或者旧式类。为什么要在2 2中引进new style class呢?官方给的解释是:
这次还是围绕surface对象进行详细介绍,并形成完整的案例过程,文中有非常详细实现百叶窗动态效果的代码示例,需要的朋友可以参考下
这篇文章主要介绍了python基础之爬虫入门,文中有非常详细的代码示例,对正在学习python爬虫的小伙伴们有很好地帮助哟,需要的朋友可以参考下
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008