python matplotlib绘图、混淆矩阵 汉字字体、数字、英文字母的设置( 二 )


第一张图的要求我们就用绘制好了 。
绘制混淆矩阵
【python matplotlib绘图、混淆矩阵 汉字字体、数字、英文字母的设置】有些中文期刊,图中要求不能出现英文,所以就需要将混淆矩阵的坐标轴标签设置为中文 。下图2所示为混淆矩阵汉字为宋体,数字符号为新罗马字体
代码如下:
from __future__ import print_functionfrom matplotlib import pyplot as pltimport numpy as npimport itertoolsfrom sklearn.metrics import confusion_matrix,accuracy_score#以下代码为绘制混淆矩阵的代码def plot_confusion_matrix(y_true, y_pred, title="混淆矩阵",cmap=plt.cm.Blues, save_flg=False):#classes = [str(i) for i in range(7)]classes=['<5%','5%','7%','9%','11%','13%','15%']labels = range(7)cm = confusion_matrix(y_true, y_pred, labels=labels)plt.figure(figsize=(5, 4))plt.imshow(cm, interpolation='nearest', cmap=cmap)plt.title(title, fontsize=7.5,fontfamily="SimSun")plt.colorbar()tick_marks = np.arange(len(classes))plt.xticks(tick_marks, classes, fontsize=7.5)plt.yticks(tick_marks, classes, fontsize=7.5)plt.rcParams['font.sans-serif']=['TimesNewRoman']plt.rcParams['axes.unicode_minus'] =Falsethresh = cm.max() / 2.for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):plt.text(j, i, cm[i, j],horizontalalignment="center",color="white" if cm[i, j] > thresh else "black")plt.ylabel('真实值', fontsize=7.5,fontfamily="SimSun")plt.xlabel('预测值', fontsize=7.5,fontfamily="SimSun")if save_flg:plt.savefig("./confusion_matrix.png")plt.show()#主函数def main():#以下代码为读取.txt文件代码 with open('pred.txt', 'r') as file:for line in file:pred_label = [int(i) for i in line.split(',')[1:-2]]print(pred_label)with open('true.txt', 'r') as file:for line in file:true_label = [int(i) for i in line.split(',')[1:-2]]print(true_label)#直接打印测试准确率print('accuracy_score:',accuracy_score(true_label, pred_label))#调用混淆矩阵,生成可视化图plot_confusion_matrix(true_label,pred_label, save_flg=True)if __name__ =='__main__':main()
主函数main()中的pred.txt和true.txt 为列表格式的文件,可以自己直接手写,也可以由程序直接导出 。我在之前的文章.0自制神经网络数据集及预测结果(混淆矩阵)可视化 中有消息介绍,此处不做过多叙述 。
本文到此结束,整理不易,喜欢的话点个赞呗