如何改变fastai中混淆矩阵的大小?

Jea*_* T. 4 python data-visualization machine-learning confusion-matrix fast-ai

我正在使用以下代码绘制混淆矩阵fastai

interp = ClassificationInterpretation.from_learner(learn)
interp.plot_confusion_matrix()
Run Code Online (Sandbox Code Playgroud)

但我最终得到了一个超级小的矩阵,因为我有大约 20 个类别:

小混淆矩阵

我找到了 sklearns 的相关问题,但不知道如何将其应用于 fastai (因为我们不pyplot直接使用。

Jea*_* T. 5

如果您检查该函数的代码ClassificationInterpretation.plot_confusion_matrix(在文件fastai /terpret.py中),您将看到以下内容:

    def plot_confusion_matrix(self, normalize=False, title='Confusion matrix', cmap="Blues", norm_dec=2,
                              plot_txt=True, **kwargs):
        "Plot the confusion matrix, with `title` and using `cmap`."
        # This function is mainly copied from the sklearn docs
        cm = self.confusion_matrix()
        if normalize: cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
        fig = plt.figure(**kwargs)
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
        plt.title(title)
        tick_marks = np.arange(len(self.vocab))
        plt.xticks(tick_marks, self.vocab, rotation=90)
        plt.yticks(tick_marks, self.vocab, rotation=0)
Run Code Online (Sandbox Code Playgroud)

这里的关键是 line fig = plt.figure(**kwargs),所以基本上,该函数plot_confusion_matrix会将其参数传播到绘图函数。

所以你可以使用其中之一:

  • dpi=xxx(例如dpi=200
  • figsize=(xxx, yyy)

请参阅 StackOverflow 上的这篇文章,了解它们之间的关系: /sf/answers/3334768181/

所以对于你的情况,你可以这样做:

interp.plot_confusion_matrix(figsize=(12, 12))
Run Code Online (Sandbox Code Playgroud)

混淆矩阵看起来像:

大混淆矩阵

仅供参考:这也适用于其他绘图函数,例如

interp.plot_top_losses(20, nrows=5, figsize=(25, 25))
Run Code Online (Sandbox Code Playgroud)