混淆矩阵代码
混淆矩阵对数据可视化很有用,我在做轴承故障诊断时,也用到了这个混淆矩阵,我在下面贴出来两种代码,供大家使用借鉴,我也是从网上找的改的
# 开发时间:2022/8/4 19:35
# 绘制混淆矩阵
import torch
from matplotlib import pyplot as plt
import numpy as np
import itertools
def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
Input
- cm : 计算出的混淆矩阵的值
- classes : 混淆矩阵中每一行每一列对应的列
- normalize : True:显示百分比, False:显示个数
"""
if normalize:
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
print("Normalized confusion matrix")
else:
print('Confusion matrix, without normalization')
print(cm)
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)
fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, cm[i, j].numpy(),
horizontalalignment="center",
color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
# 计算混淆矩阵
def confusion_matrix(preds, labels, conf_matrix):
preds = torch.argmax(preds, 1)
for p, t in zip(preds, labels):
conf_matrix[t, p] += 1
return conf_matrix
# 混淆矩阵定义
def plot_confusion_matrix(cm, classes,title='Confusion matrix',cmap=plt.cm.jet):
cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks,('good','bad'))
plt.yticks(tick_marks,('good','bad'))
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
plt.text(j, i, '{:.2f}'.format(cm[i, j]), horizontalalignment="center",color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('真实类别')
plt.xlabel('预测类别')
plt.savefig('test_xx.png', dpi=200, bbox_inches='tight', transparent=False)
plt.show()
# 显示混淆矩阵
def plot_confuse(model, x_val, y_val):
predictions = model.predict_classes(x_val)
truelabel = y_val.argmax(axis=-1) # 将one-hot转化为label
conf_mat = confusion_matrix(y_true=truelabel, y_pred=predictions)
plt.figure()
plot_confusion_matrix(conf_mat, range(np.max(truelabel)+1))