绘制混淆矩阵热力图

Python绘制混淆矩阵热力图


用matplotlib绘制混淆矩阵,可以通过改变 imshow 函数中的 cmap 参数来修改颜色。cmap 参数接受一个 colormap 的名字,你可以选择许多不同的 colormap,例如 ‘viridis’, ‘plasma’, ‘inferno’, ‘magma’, ‘cividis’, ‘cool’, ‘hot’ 等等。具体的 colormap 可以参考 matplotlib 的文档。

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap, Normalize

conf_arr = [[33, 2, 0, 0, 0, 0, 0, 0, 0, 1, 3],
            [3, 31, 0, 0, 0, 0, 0, 0, 0, 0, 0],
            [0, 4, 41, 0, 0, 0, 0, 0, 0, 0, 1],
            [0, 1, 0, 30, 0, 6, 0, 0, 0, 0, 1],
            [0, 0, 0, 0, 38, 10, 0, 0, 0, 0, 0],
            [0, 0, 0, 3, 1, 39, 0, 0, 0, 0, 4],
            [0, 2, 2, 0, 4, 1, 31, 0, 0, 0, 2],
            [0, 1, 0, 0, 0, 0, 0, 36, 0, 2, 0],
            [0, 0, 0, 0, 0, 0, 1, 5, 37, 5, 1],
            [3, 0, 0, 0, 0, 0, 0, 0, 0, 39, 0],
            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 38]]

# 自定义渐变颜色
colors = ['#ffffff', '#ffcccc', '#ff6666', '#ff0000', '#990000']
custom_cmap = LinearSegmentedColormap.from_list('custom_cmap', colors)

# 归一化对象,定义最小值和最大值
norm = Normalize(vmin=0, vmax=np.max(conf_arr))

norm_conf = []
for i in conf_arr:
    a = 0
    tmp_arr = []
    a = sum(i, 0)
    for j in i:
        tmp_arr.append(float(j)/float(a))
    norm_conf.append(tmp_arr)

fig = plt.figure()
plt.clf()
ax = fig.add_subplot(111)
ax.set_aspect(1)
res = ax.imshow(np.array(conf_arr), cmap=custom_cmap, norm=norm, interpolation='nearest')

# 获取矩阵的宽度和高度
width, height = np.array(conf_arr).shape

# 使用 range 替换 xrange
for x in range(width):
    for y in range(height):
        ax.annotate(str(conf_arr[x][y]), xy=(y, x),
                    horizontalalignment='center',
                    verticalalignment='center',
                    color='black')

cb = fig.colorbar(res)

# 调整 alphabet 使其不会超出索引范围
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[:width]
plt.xticks(range(width), alphabet)
plt.yticks(range(height), alphabet)

plt.savefig('confusion_matrix.png', format='png')
plt.show()

效果图如下:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ccwRadar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值