You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何调整fastai中绘制的混淆矩阵的显示大小

解决方案

fastai的plot_confusion_matrix底层直接基于matplotlib实现,你可以通过以下方式调整混淆矩阵尺寸,也可以直接适配sklearn的相关绘制逻辑:

方法1:调用fastai接口时直接指定尺寸参数

直接在plot_confusion_matrix方法中传入figsize(画布宽高,单位英寸)和dpi(清晰度)参数即可,20个分类建议设置如下,你可以根据显示效果自行调整数值:

import matplotlib.pyplot as plt
from fastai.interpret import ClassificationInterpretation

interp = ClassificationInterpretation.from_learner(learn)
# 宽15,高12,清晰度100
interp.plot_confusion_matrix(figsize=(15, 12), dpi=100)
# 可选:旋转x轴标签避免分类名重叠
plt.xticks(rotation=45, ha='right')
plt.show()

方法2:全局修改matplotlib默认配置

如果你需要所有绘图都默认用大尺寸,可以提前设置matplotlib的全局参数:

import matplotlib.pyplot as plt
from fastai.interpret import ClassificationInterpretation

# 全局设置默认画布尺寸和清晰度
plt.rcParams['figure.figsize'] = (15, 12)
plt.rcParams['figure.dpi'] = 100

interp = ClassificationInterpretation.from_learner(learn)
interp.plot_confusion_matrix()
plt.show()

适配sklearn的自定义绘制方案

如果你要使用sklearn相关的绘制逻辑,可以直接从interp对象中提取预测和真实标签,后续完全按照sklearn的流程操作即可:

import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import confusion_matrix

# 提取标签和预测结果
y_true = interp.y_true.numpy()
y_pred = interp.preds.argmax(dim=1).numpy()
# 获取分类名称
class_names = learn.dls.vocab

# 计算混淆矩阵
cm = confusion_matrix(y_true, y_pred)

# 自定义绘制
plt.figure(figsize=(15, 12), dpi=100)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues',
            xticklabels=class_names,
            yticklabels=class_names)
plt.xlabel('预测类别')
plt.ylabel('真实类别')
plt.xticks(rotation=45, ha='right')
plt.show()

内容的提问来源于stack exchange,提问作者Jean-Francois T.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 14:15:00