python - 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")
这个情节有两个问题。
- y 轴标签被切断(真实标签)。x 标签也被切断。
- 名称对于 x 轴来说太长了。
为了解决我尝试使用的第一个问题poof(bbox_inches='tight')
,不幸的是它不适用于 sklearn。在第二种情况下,我为2.尝试了以下解决方案,这导致情节完全扭曲。
总而言之,我正在努力解决这两个问题。
解决方案
我认为最简单的方法是切换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)
结果:
推荐阅读
- multithreading - Docker 容器而不是多处理
- r - 如何使用 RevoScaleR 在 SQL Server 中创建表?
- swift - 无法将“AProtocol”.Protocol 类型的值转换为预期的参数类型协议
- javascript - 如何计算 window.prompt 中的单词并按出现次数对其进行排序?
- wordpress - Wordpress自定义字段在指定日期后删除帖子?
- android - 如何使用 window.setSoftInputMode() 组合状态和调整
- ajax - Django 文件上传 Ajax
- javascript - 如何使用 Webpack 独立捆绑 JS 和 CSS 文件?
- c# - DependencyInjection:在调用之前初始化类(必需)?
- flutter - 检测 Flutter 上的推送路由