alex_bn_lee

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

【796】Confusion Matrix 混淆矩阵相关

参考:sklearn.metrics.confusion_matrix

参考:Confusion matrix

参考:Matplotlib setting title bold while using "Times New Roman"

参考:seaborn.heatmap

参考:Choosing Colormaps in Matplotlib(colorbar关键字)


一、创建 Confusion Matrix (方法一)

import numpy as np
import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
# 两个数组存储在npy文件中了,下面为读取
y_true = list(np.load('y_true.npy'))
y_pred = list(np.load('y_pred.npy'))
# 计算混淆矩阵数量
C2 = confusion_matrix(y_true, y_pred, labels=[0, 1, 2])
# 计算百分比
C2_normal = np.round(C2/np.sum(C2, axis=1).reshape(-1, 1), 2)
sns.set()
sns.heatmap(C2_normal, cmap="YlGnBu", annot=True)
# 设置全局字体
plt.rcParams['font.sans-serif'] = 'Times New Roman'
# 设置x轴y轴的显示内容,并加粗
plt.xlabel("Predicted label", fontweight='bold')
plt.ylabel('True label', fontweight='bold')
# 设置x轴y轴的显示刻度
plt.xticks([0, 1, 2], [-1, 0, 1])
plt.yticks([0, 1, 2], [-1, 0, 1])
# 图像显示
#plt.show()
# 图像存储,PDF为矢量图
plt.savefig("Confusion_matrix.pdf")

效果:

通过 Adobe Acrobat 调整标签位置

参考:How to Plot Confusion Matrix Heatmap in Python

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

参考:How to format xticklabels in a confusion matrix plotted with scikit-learn / matplotlib?


二、创建 Confusion Matrix (方法二)

import seaborn as sns
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
# 两个数组存储在npy文件中了,下面为读取
y_true = list(np.load('y_true.npy'))
y_pred = list(np.load('y_pred.npy'))
# 计算混淆矩阵数量
C2 = confusion_matrix(y_true, y_pred, labels=[0, 1, 2])
# 计算百分比
C2_normal = np.round(C2/np.sum(C2, axis=1).reshape(-1, 1), 2)
sns.set()
f, ax = plt.subplots()
sns.heatmap(C2_normal, cmap="YlGnBu", annot=True, ax=ax) # heatmap
#ax.set_title('Normalized confusion maxtrix') # title
ax.set_xlabel('Predicted label')
ax.set_ylabel('True label')
ax.xaxis.set_ticklabels([-1, 0, 1])
ax.yaxis.set_ticklabels([-1, 0, 1])

效果:

参考:python画混淆矩阵(confusion matrix)


三、设置 matplotlib.pyplot 全局字体

import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'Times New Roman'

参考:matplotlib字体设置看这一篇就够了

posted on   McDelfino  阅读(316)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示