import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import seaborn as sns
from matplotlib import rcParams
classes = ['1',' ','3','',' 5',' ','7']
confusion_matrix = np.array([
[18, 1, 0, 0, 0, 0, 0],
[11, 56, 14, 0, 0, 0, 0],
[0, 2, 12, 15, 0, 0, 0],
[0, 0, 15, 35, 23, 0, 0],
[0, 0, 0, 5, 38, 50, 1],
[0, 0, 0, 0, 16, 38, 9],
[0, 0, 0, 0, 0, 20, 35]],dtype=np.int)
proportion=[]
for i in confusion_matrix:
for j in i:
temp = (j / np.sum(i))*100
proportion.append(temp)
proportion = np.array(proportion).reshape(7,7)
config = {
"font.family": 'Times New Roman',
}
rcParams.update(config)
plt.imshow(proportion, interpolation='nearest', cmap=plt.cm.Blues)
# plt.title('Confusion Matrix')
tick_marks = np.arange(len(classes))
plt.colorbar().ax.tick_params(labelsize=14)
plt.xticks(tick_marks, classes, fontsize=14, fontname='Times New Roman')
plt.yticks(tick_marks, classes, fontsize=14, fontname='Times New Roman' , rotation=90)
thresh = confusion_matrix.max() / 2.
for i in range(len(classes)):
for j in range(len(classes)):
if i==j:
plt.text(j, i, '{:.2f}'.format(proportion[i, j]), va='center', ha='center', fontsize=12, color='white')
else:
plt.text(j, i, '{:.2f}'.format(proportion[i, j]), va='center', ha='center', fontsize=12, color='black')
plt.ylabel('True label',fontsize=16)
plt.xlabel('Predicted label',fontsize=16)
plt.tight_layout()
def savefig(filepath, filename, format='png', dpi=1200):
if not os.path.exists(filepath):
os.makedirs(filepath)
full_filename = os.path.join(filepath, filename)
plt.savefig(full_filename, format=format, dpi=dpi)
savefig('./confusion matrix images/', 'confusion matrix 1.png')
plt.show()
根据
使用Python绘制混淆矩阵Confusion Matrix、自定义样式_python confusion matrix-CSDN博客进行修改,只保留计算概率。