【问题标题】:Rendering a confusion matrix渲染混淆矩阵
【发布时间】:2019-08-06 11:13:23
【问题描述】:

我正在使用jupyterlab,专门渲染一个混淆矩阵。但是,在渲染矩阵时,似乎有什么问题,因为图形没有完全渲染。

我已经安装了 sklearn 软件包,但仍然是同样的问题。我尝试了不同的替代方案,但仍然呈现一个截断的混淆矩阵。

下面是一个我知道会呈现正确混淆矩阵的代码示例。

from sklearn.metrics import classification_report, confusion_matrix
import itertools
import matplotlib.pyplot as plt
def plot_confusion_matrix(cm, classes,
                          normalize=False,
                          title='Confusion matrix',
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

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

    fmt = '.2f' 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 label')
    plt.xlabel('Predicted label')
# Compute confusion matrix
cnf_matrix = confusion_matrix(y_test, yhat, labels=[2,4])
np.set_printoptions(precision=2)

print (classification_report(y_test, yhat))

# Plot non-normalized confusion matrix
plt.figure()
plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False,  title='Confusion matrix')

从上面的代码中,我得到了这个混淆矩阵:

但是,我希望有一个非截断的混淆矩阵,例如:

致谢:@Calvin Duy Canh Tran

2019 年 8 月 5 日更新:

为了不怀疑上面使用的代码,我使用了额外的参考:相反,我尝试了作为混淆矩阵文档示例之一的代码scikit-learn。链接就是这个https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html

在运行上述代码之前,我安装了对应的模块:

pip install -q scikit-plot

不幸的是,输出继续渲染截断的矩阵(见图):

正确的输出应该是这个(忽略方向):

【问题讨论】:

  • 看看plot_confusion_matrix in this source
  • 你传递了 2 个类 classes=['Benign(2)','Malignant(4)'],为什么你期望输出中有 3 个类?
  • 看看 YellowBrick 模块。它为 sklearn 提供了很好的可视化效果,并提供了良好的启动文档。 scikit-yb.org/en/latest
  • @pciunkiewicz 谢谢!使用 YellowBrick,渲染工作正常。

标签: python scikit-learn renderer confusion-matrix


【解决方案1】:

matplotlib 3.1.1 版和 scikit-plot 之间似乎存在冲突。参考这个 GitHub issue,它显示了类似的问题。

将 matplotlib 降级到 3.1.0 版本可能是一个立即修复。

【讨论】:

  • 嗨!我尝试了您的建议,但混淆矩阵仍然以错误的方式呈现。
  • 不知道,你怎么了!你能在你的问题中添加一些可重复的例子吗?
  • 我添加了它。在 udpate 中,我使用了在 Scikit-learn 文档中用作示例的代码。链接是这个:Scikit-learn Example
  • 我认为您的问题类似于this
  • 谢谢,sudo pip3 uninstall matplotlib && sudo pip3 install matplotlib==3.1.0 对我有用!
【解决方案2】:

不要将混淆矩阵作为输入参数传递给绘图函数。您需要传递y_test, y_pred,混淆矩阵将在内部计算。

要绘制它,请使用:

def plot_confusion_matrix(y_true, y_pred, classes,
                          normalize=False,
                          title=None,
                          cmap=plt.cm.Blues):
    """
    This function prints and plots the confusion matrix.
    Normalization can be applied by setting `normalize=True`.
    """
    if not title:
        if normalize:
            title = 'Normalized confusion matrix'
        else:
            title = 'Confusion matrix, without normalization'

    # Compute confusion matrix
    cm = confusion_matrix(y_true, y_pred)
    # Only use the labels that appear in the data
    classes = classes[unique_labels(y_true, y_pred)]
    if normalize:
        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        print("Normalized confusion matrix")
    else:
        print('Confusion matrix, without normalization')

    print(cm)

    fig, ax = plt.subplots()
    im = ax.imshow(cm, interpolation='nearest', cmap=cmap)
    ax.figure.colorbar(im, ax=ax)
    # We want to show all ticks...
    ax.set(xticks=np.arange(cm.shape[1]),
           yticks=np.arange(cm.shape[0]),
           # ... and label them with the respective list entries
           xticklabels=classes, yticklabels=classes,
           title=title,
           ylabel='True label',
           xlabel='Predicted label')

    # Rotate the tick labels and set their alignment.
    plt.setp(ax.get_xticklabels(), rotation=45, ha="right",
             rotation_mode="anchor")

    # Loop over data dimensions and create text annotations.
    fmt = '.2f' if normalize else 'd'
    thresh = cm.max() / 2.
    for i in range(cm.shape[0]):
        for j in range(cm.shape[1]):
            ax.text(j, i, format(cm[i, j], fmt),
                    ha="center", va="center",
                    color="white" if cm[i, j] > thresh else "black")
    fig.tight_layout()
    return ax


# Plot non-normalized confusion matrix
plot_confusion_matrix(y_test, y_pred, classes=['Benign(2)','Malignant(4)'],normalize= False,  title='Confusion matrix')

而不是

plot_confusion_matrix(cnf_matrix, classes=['Benign(2)','Malignant(4)'],normalize= False,  title='Confusion matrix')

参考:https://scikit-learn.org/stable/auto_examples/model_selection/plot_confusion_matrix.html

【讨论】:

  • 嗨!谢谢!我尝试了您的上述建议,但问题仍然存在。查看我今天所做的问题的更新。
猜你喜欢
  • 2015-12-17
  • 2020-10-01
  • 2012-01-20
  • 2019-11-23
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 2014-07-09
  • 2018-09-26
相关资源
最近更新 更多