参考:sklearn.metrics.confusion_matrix
参考:Matplotlib setting title bold while using "Times New Roman"
参考:Choosing Colormaps in Matplotlib(colorbar关键字)
1. 创建 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)
2. 创建 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)
1. 设置 matplotlib.pyplot
全局字体
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = 'Times New Roman'
2.
标签:796,plt,matrix,Confusion,import,np,C2,confusion,Matrix From: https://www.cnblogs.com/alex-bn-lee/p/16996313.html