如何绘制不带颜色编码的混淆矩阵。

4

在stackoverflow上,像123这样的问题中,混淆矩阵通常是使用颜色来表示的。

但在我的情况下,我不想使用颜色,特别是因为我的数据集往往存在严重的类别不平衡,少数类总是用浅颜色显示。我希望它能够显示每个单元格中实际/预测数量的数字,而不是使用颜色。

目前,我使用以下代码:

def plot_confusion_matrix(cm, classes, title,
                          normalize=False,
                          file='confusion_matrix',
                          cmap=plt.cm.Blues):
    
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        cm_title = "Normalized confusion matrix"
    else:
        cm_title = title

    # print(cm)

    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(cm_title)
    plt.colorbar()
    tick_marks = np.arange(len(classes))
    plt.xticks(tick_marks, classes, rotation=45)
    plt.yticks(tick_marks, classes)

    fmt = '.3f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j, i, format(cm[i, j], fmt),
                 horizontalalignment="center",
                 color="white" if cm[i, j] > thresh else "black")

    plt.tight_layout()
    plt.ylabel('True class')
    plt.xlabel('Predicted class')
    plt.tight_layout()
    plt.savefig(file + '.png')

输出结果:

enter image description here

所以我只想显示数字。

2个回答

4

使用 seaborn.heatmap 函数,并设置灰度(colormap)为主色调,同时将 vmin=0, vmax=0:

import seaborn as sns

sns.heatmap(cm, fmt='d', annot=True, square=True,
            cmap='gray_r', vmin=0, vmax=0,  # set all to white
            linewidths=0.5, linecolor='k',  # draw black grid lines
            cbar=False)                     # disable colorbar

# re-enable outer spines
sns.despine(left=False, right=False, top=False, bottom=False)

Complete function:

def plot_confusion_matrix(cm, classes, title,
                          normalize=False,
                          file='confusion_matrix',
                          cmap='gray_r',
                          linecolor='k'):
    
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        cm_title = 'Confusion matrix, with normalization'
    else:
        cm_title = title

    fmt = '.3f' if normalize else 'd'
    sns.heatmap(cm, fmt=fmt, annot=True, square=True,
                xticklabels=classes, yticklabels=classes,
                cmap=cmap, vmin=0, vmax=0,
                linewidths=0.5, linecolor=linecolor,
                cbar=False)
    sns.despine(left=False, right=False, top=False, bottom=False)

    plt.title(cm_title)
    plt.ylabel('True class')
    plt.xlabel('Predicted class')
    plt.tight_layout()
    plt.savefig(f'{file}.png')

1
您可以使用一个颜色的ListedColormap作为色图。使用Seaborn可以自动化很多东西,包括:
  • 在正确位置设置注释,黑色或白色取决于单元格的亮度
  • 一些参数用于设置分割线
  • 参数用于设置刻度标签
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
import numpy as np
import pandas as pd
import seaborn as sns

def plot_confusion_matrix(cm, classes, title,
                          normalize=False, file='confusion_matrix', background='aliceblue'):
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        plt.title("Normalized confusion matrix")
    else:
        plt.title(title)

    fmt = '.3f' if normalize else 'd'
    sns.heatmap(np.zeros_like(cm), annot=cm, fmt=fmt,
                xticklabels=classes, yticklabels=classes,
                cmap=ListedColormap([background]), linewidths=1, linecolor='navy', clip_on=False, cbar=False)
    plt.tick_params(axis='x', labelrotation=30)

    plt.tight_layout()
    plt.ylabel('True class')
    plt.xlabel('Predicted class')
    plt.tight_layout()
    plt.savefig(file + '.png')

cm = np.random.randint(1, 20000, (5, 5))
plot_confusion_matrix(cm, [*'abcde'], 'title')

heatmap with single color


cmap 处有一个括号问题。 - tumultous_rooster
SyntaxError: unmatched ')' - tumultous_rooster
啊,糟糕,我的错。我会删除我的评论。 - tumultous_rooster

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接