Seaborn Confusion Matrix (heatmap) 2 配色方案(正确的对角线 vs 错误的休息)

Num*_*uis 2 python matplotlib heatmap confusion-matrix seaborn

背景

在混淆矩阵中,对角线表示预测标签与正确标签匹配的情况。所以对角线是好的,而所有其他单元都是坏的。为了向非专家阐明 CM 中什么是好的和什么是坏的,我想给对角线赋予与其他颜色不同的颜色。我想用Python 和 Seaborn来实现这一点。

基本上我试图实现这个问题在 R 中的作用(ggplot2 Heatmap 2 Different Color Schemes - Confusion Matrix: Matches in Different Color Scheme than Missclassifications

带有热图的普通 Seaborn 混淆矩阵

import numpy as np
import seaborn as sns

cf_matrix = np.array([[50, 2, 38],
                      [7, 43, 32],
                      [9,  4, 76]])

sns.heatmap(cf_matrix, annot=True, cmap='Blues')  # cmap='OrRd'
Run Code Online (Sandbox Code Playgroud)

这导致此图像:

Seaborn 混淆矩阵与颜色图“蓝调”

目标

我想用例如着色非对角线单元格cmap='OrRd'。所以我想会有 2 个颜色条,1 个蓝色用于对角线,1 个用于其他单元格。优选地,两个颜色条的值匹配(因此两者都是例如 0-70 而不是 0-70 和 0-40)。我将如何处理这个问题?

以下不是用代码制作的,而是用照片编辑软件制作的:

所需的混淆矩阵配色方案

Diz*_*ahi 5

您可以mask=在调用中使用heatmap()来选择要显示的单元格。对对角线和 off_diagonal 单元格使用两个不同的掩码,您可以获得所需的输出:

import numpy as np
import seaborn as sns

cf_matrix = np.array([[50, 2, 38],
                      [7, 43, 32],
                      [9,  4, 76]])

vmin = np.min(cf_matrix)
vmax = np.max(cf_matrix)
off_diag_mask = np.eye(*cf_matrix.shape, dtype=bool)

fig = plt.figure()
sns.heatmap(cf_matrix, annot=True, mask=~off_diag_mask, cmap='Blues', vmin=vmin, vmax=vmax)
sns.heatmap(cf_matrix, annot=True, mask=off_diag_mask, cmap='OrRd', vmin=vmin, vmax=vmax, cbar_kws=dict(ticks=[]))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果您想花哨,可以使用 GridSpec 创建轴以获得更好的布局:

将 numpy 导入为 np 将 seaborn 导入为 sns

import numpy as np
import seaborn as sns

cf_matrix = np.array([[50, 2, 38],
                      [7, 43, 32],
                      [9,  4, 76]])

vmin = np.min(cf_matrix)
vmax = np.max(cf_matrix)
off_diag_mask = np.eye(*cf_matrix.shape, dtype=bool)

fig = plt.figure()
sns.heatmap(cf_matrix, annot=True, mask=~off_diag_mask, cmap='Blues', vmin=vmin, vmax=vmax)
sns.heatmap(cf_matrix, annot=True, mask=off_diag_mask, cmap='OrRd', vmin=vmin, vmax=vmax, cbar_kws=dict(ticks=[]))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明