这种混淆矩阵怎么画?如何在以下基础上实现该效果?
class DrawConfusionMatrix:
def __init__(self, labels_name):
"""
:param num_classes: 分类数目
"""
self.labels_name = labels_name
self.num_classes = len(labels_name)
self.matrix = np.zeros((self.num_classes, self.num_classes), dtype="float32")
def update(self, predicts, labels):
"""
:param predicts: 一维预测向量,eg:array([0,5,1,6,3,...],dtype=int64)
:param labels: 一维标签向量:eg:array([0,5,0,6,2,...],dtype=int64)
:return:
"""
for predict, label in zip(predicts, labels):
self.matrix[predict, label] += 1
def draw(self):
per_sum = self.matrix.sum(axis=1) # 计算每行的和,用于百分比计算
for i in range(self.num_classes):
self.matrix[i] = (self.matrix[i] / per_sum[i]) # 百分比
plt.imshow(self.matrix, cmap=plt.cm.Blues) # 仅画出颜色格子,没有值
plt.title("Normalized confusion matrix") # title
plt.xlabel("Predict label")
plt.ylabel("Truth label")
plt.yticks(range(5), self.labels_name) # y轴标签
plt.xticks(range(5), self.labels_name, rotation=45) # x轴标签
for x in range(5):
for y in range(5):
value = float(format('%.2f' % self.matrix[y, x])) # 数值处理
plt.text(x, y, value, verticalalignment='center', horizontalalignment='center') # 写值
plt.tight_layout() # 自动调整子图参数,使之填充整个图像区域
plt.colorbar() # 色条
plt.savefig('./confusionImage/cifar_fs/fs_HFFDK.jpg', bbox_inches='tight') # bbox_inches='tight'可确保标签信息显示全
plt.show()
if __name__ =="__main__":
labels_name=['1', '2', '3', '4', '5']
drawconfusionmatrix = DrawConfusionMatrix(labels_name=labels_name) # 实例化
for index, (labels, imgs) in enumerate(test_loader):
labels_pd = model(imgs)
predict_np = np.argmax(labels_pd.cpu().detach().numpy(), axis=-1) # array([0,5,1,6,3,...],dtype=int64)
labels_np = labels.numpy() # array([0,5,0,6,2,...],dtype=int64)
drawconfusionmatrix.update(predict_np, labels_np) # 将新批次的predict和label更新(保存)
drawconfusionmatrix.draw() # 根据所有predict和label,画出混淆矩阵
图中是一个 5 * 5 的矩阵,矩阵种的每一个小块中包含着16个样本,也就是有5类,每一类有16个样本进行判断。主要是如何画出小矩形块中的16个小矩形?
如果能够基于此代码进行优化的话十分感谢您的帮助~