介绍
今天就跟大家聊聊有关怎么在python中使用confusion_matrix绘制一个混淆矩阵,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
<强>总结强>
涉及到分类问题,我们经常需要通过可视化混淆矩阵来分析实验结果进而得出调参思路,本文介绍如何利用python绘制混淆矩阵(confusion_matrix),本文只提供代码,给出必要注释。
<强>代码强>
#, - *编码:utf - 8 - * 得到sklearn.metrics import  confusion_matrix import matplotlib.pyplot  as plt import numpy  as np #标签表示你不同类别的代号,比如这里的演示中有13个类别 labels =,(& # 39;一个# 39;,,& # 39;b # 39;,, & # 39; c # 39;,, & # 39; f # 39;,, & # 39;舌鳎# 39;,,& # 39;h # 39;,, & # 39;我# 39;,,& # 39;强生# 39;,,& # 39;k # 39;,, & # 39; l # 39;,, & # 39;猴# 39;,,& # 39;n # 39;,, & # 39; o # 39;】 & # 39;& # 39;& # 39; 具体解释一下re_label.txt和pr_label.txt这两个文件,比如你有100个样本 去做预测,这100个样本中一共有10类,那么首先这100个样本的真实标签你一定 是知道的,一共有10个类别,用(0,9)表示,则re_label.txt文件中应该有100 个数字,第n个数字代表的是第n个样本的真实标签(100个样本自然就有100个 数字)。 同理,pr_label.txt里面也应该有1——个数字,第n个数字代表的是第n个样本经过 你训练好的网络预测出来的预测标签。 这样,re_label.txt和pr_label.txt这两个文件分别代表了你样本的真实标签和预测标签,然后读到y_true和y_pred这两个变量中计算后面的混淆矩阵。当然,不一定非要使用这种txt格式的文件读入的方式,只要你最后将你的真实 标签和预测标签分别保存到y_true和y_pred这两个变量中即可。 & # 39;& # 39;& # 39; 时间=y_true np.loadtxt(& # 39; . ./数据/re_label.txt& # 39;) 时间=y_pred np.loadtxt(& # 39; . ./数据/pr_label.txt& # 39;) 时间=tick_marks np.array(范围(len(标签))),+ 0.5 def plot_confusion_matrix(厘米,,title=& # 39; Confusion 矩阵# 39;,,提出=plt.cm.binary): plt.imshow才能(cm,插值=& # 39;最近的# 39;,,提出=提出) plt.title才能(标题) plt.colorbar才能() 时间=xlocations 才能;np.array(范围(len(标签))) plt.xticks才能(xlocations,标签,旋转=90) plt.yticks才能(xlocations,,标签) plt.ylabel才能(& # 39;True 标签# 39;) plt.xlabel才能(& # 39;Predicted 标签# 39;) 时间=cm 才能;confusion_matrix (y_true, y_pred) np.set_printoptions才能(精度=2) ,, 时间=cm_normalized cm.astype(& # 39;浮动# 39;),/,cm.sum(轴=1)(:,,np.newaxis] print cm_normalized plt.figure (figsize=(12,, 8), dpi=120) 时间=ind_array np.arange (len(标签) 时间=x,, y np.meshgrid (ind_array, ind_array) for x_val, y_val 拷贝zip (x.flatten (),, y.flatten ()): c 才能=,cm_normalized [y_val] [x_val] if 才能;c 祝辞,0.01: ,,,plt.text (x_val, y_val,,“% 0.2 f", %, (c),颜色=& # 39;红色# 39;,,字形大?7,,va=& # 39;中心# 39;,,哈=& # 39;中心# 39;) #,offset 从而,蜱虫 plt.gca () .set_xticks (tick_marks,?True) plt.gca () .set_yticks (tick_marks,?True) plt.gca () .xaxis.set_ticks_position(& # 39;没有# 39;) plt.gca () .yaxis.set_ticks_position(& # 39;没有# 39;) plt.grid(真的,,=& # 39;小# 39;,,线型=& # 39;& # 39;) plt.gcf () .subplots_adjust (=0.15) plot_confusion_matrix (cm_normalized, title=& # 39; Normalized confusion 矩阵# 39;) #,show confusion 矩阵 plt.savefig(& # 39; . ./数据/confusion_matrix.png& # 39;,,格式=& # 39;png # 39;) plt.show结果()
看完上述内容,你们对怎么在python中使用confusion_matrix绘制一个混淆矩阵有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注行业资讯频道,感谢大家的支持。