利用matplotlib绘制中文混淆矩阵(confusion_matrix)

from pylab import *
import numpy as np
import matplotlib.pyplot as plt
classes = ['猫','猴子','狗','兔子']
confusion_matrix = np.array([(666,7,43,18),(6,822,0,35),(24,1,668,1),(7,1,1,339)],dtype=np.float64)

proportion=[]
for i in confusion_matrix:
    for j in i:
        temp=j/(np.sum(i))
        proportion.append(temp)
        
pshow=[]
for i in proportion:
    pt="%.2f%%" % (i * 100)
    pshow.append(pt)
proportion=np.array(proportion).reshape(4,4)  # reshape(列的长度,行的长度)
pshow=np.array(pshow).reshape(4,4)
#print(pshow)
config = {
    "font.family":'SimHei',  # 设置字体类型,不同字体可参考http://t.csdn.cn/1JFcv
}
rcParams.update(config)
plt.imshow(proportion, interpolation='nearest', cmap=plt.cm.Blues)  #按照像素显示出矩阵
            # (改变颜色:'Greys', 'Purples', 'Blues', 'Greens', 'Oranges', 'Reds','YlOrBr', 'YlOrRd',
            # 'OrRd', 'PuRd', 'RdPu', 'BuPu','GnBu', 'PuBu', 'YlGnBu', 'PuBuGn', 'BuGn', 'YlGn')
plt.title('confusion_matrix')
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes,fontsize=14)
plt.yticks(tick_marks, classes,fontsize=14)
 
thresh = confusion_matrix.max() / 2.
#iters = [[i,j] for i in range(len(classes)) for j in range((classes))]
#ij配对,遍历矩阵迭代器
iters = np.reshape([[[i,j] for j in range(4)] for i in range(4)],(confusion_matrix.size,2))
for i, j in iters:
    if(i==j):
        plt.text(j, i, format(int(confusion_matrix[i, j])), va='center', ha='center', fontsize=12,color='white',weight=5)  # 显示对应的数字
#         plt.text(j, i + 0.12, pshow[i, j], va='center', ha='center', fontsize=12,color='white') # 显示百分比,需把前i改为i - 0.12
    else:
        plt.text(j, i, format(int(confusion_matrix[i, j])),va='center',ha='center',fontsize=12)   #显示对应的数字
#         plt.text(j, i+0.12, pshow[i, j], va='center', ha='center', fontsize=12) # 显示百分比,需把前i改为i - 0.12
 
plt.ylabel('预测值',fontsize=16)
plt.xlabel('真实值',fontsize=16)
plt.tight_layout()
plt.savefig(r'C:\Users\pc\Desktop\confusion_matrix')
plt.show()

利用matplotlib绘制中文混淆矩阵(confusion_matrix)_第1张图片

你可能感兴趣的:(python,数据挖掘,计算机视觉,矩阵)