ConfusionMatrixDisplay (Scikit-Learn) 绘图标签超出范围

Jür*_* K. 2 python plot confusion-matrix 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")
Run Code Online (Sandbox Code Playgroud)

混淆矩阵

这个情节有两个问题。

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

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

总而言之,我正在为这两个问题而苦苦挣扎。

Ale*_*yes 8

我认为最简单的方法是切换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)
Run Code Online (Sandbox Code Playgroud)

结果:

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