首页 > 解决方案 > ConfusionMatrixDisplay(Scikit-Learn)绘图标签超出范围

问题描述

以下代码绘制了一个混淆矩阵:

from sklearn.metrics import ConfusionMatrixDisplay

confusion_matrix = confusion_matrix(y_true, y_pred)
target_names = ["aaaaa", "bbbbbb", "ccccccc", "dddddddd", "eeeeeeeeee", "ffffffff", "ggggggggg"]
disp = ConfusionMatrixDisplay(confusion_matrix=confusion_matrix, display_labels=target_names)
disp.plot(cmap=plt.cm.Blues, xticks_rotation=45)
plt.savefig("conf.png")

混淆矩阵

这个情节有两个问题。

  1. y 轴标签被切断(真实标签)。x 标签也被切断。
  2. 名称对于 x 轴来说太长了。

为了解决我尝试使用的第一个问题poof(bbox_inches='tight'),不幸的是它不适用于 sklearn。在第二种情况下,我为2.尝试了以下解决方案,这导致情节完全扭曲。

总而言之,我正在努力解决这两个问题。

标签: pythonplotscikit-learnconfusion-matrix

解决方案


我认为最简单的方法是切换tight_layout并添加pad_inches=一些东西。

from sklearn.metrics import confusion_matrix
from sklearn.metrics import ConfusionMatrixDisplay
import matplotlib.pyplot as plt
from numpy.random import default_rng

rand = default_rng()
y_true = rand.integers(low=0, high=7, size=500)
y_pred = rand.integers(low=0, high=7, size=500)


confusion_matrix = confusion_matrix(y_true, y_pred)
target_names = ["aaaaa", "bbbbbb", "ccccccc", "dddddddd", "eeeeeeeeee", "ffffffff", "ggggggggg"]
disp = ConfusionMatrixDisplay(confusion_matrix=confusion_matrix, display_labels=target_names)
disp.plot(cmap=plt.cm.Blues, xticks_rotation=45)

plt.tight_layout()
plt.savefig("conf.png", pad_inches=5)

结果:

混淆矩阵,其中轴中的所有文本都是可见的。


推荐阅读