Bootstrap

好看的混淆矩阵

网上绘制的混淆矩阵都不太满意。。。经过本人多次实验,如下混淆矩阵最为美观,特此记录

import matplotlib
matplotlib.use('Agg')
from matplotlib import rcParams

import matplotlib.pyplot as plt
import numpy as np

# 给定混淆矩阵
cm = np.array([[6839, 1609],
               [311, 0]])

proportion = []
length = len(cm)

# 计算每个单元格的比例
for i in cm:
    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(length, length)
pshow = np.array(pshow).reshape(length, length)

config = {
    "font.family": 'Times New Roman',  # 设置字体类型
}
rcParams.update(config)

# 绘制混淆矩阵
plt.imshow(proportion, interpolation='nearest', cmap=plt.cm.Blues)
plt.title("Confusion Matrix", fontsize=20)
plt.colorbar()
classes = ["Car", "Backgroud"]
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, fontsize=17)
plt.yticks(tick_marks, classes, fontsize=17)

iters = np.reshape([[[i, j] for j in range(length)] for i in range(length)], (cm.size, 2))
for i, j in iters:
    if (i == j):
        plt.text(j, i - 0.12, format(cm[i, j]), va='center', ha='center', fontsize=18,
                 color='white', weight=5)
        plt.text(j, i + 0.12, pshow[i, j], va='center', ha='center', fontsize=17, color='white')
    else:
        plt.text(j, i - 0.12, format(cm[i, j]), va='center', ha='center', fontsize=18)
        plt.text(j, i + 0.12, pshow[i, j], va='center', ha='center', fontsize=17)

plt.ylabel('True Label', fontsize=18)
plt.xlabel('Predict Label', fontsize=18)
plt.tight_layout()

# 保存图像
plt.savefig('confusion_matrix.png')

;