【问题标题】:How to add tooltips to a confusion matrix rendered via a Seaborn heatmap?如何向通过 Seaborn 热图呈现的混淆矩阵添加工具提示?
【发布时间】:2020-05-05 16:27:51
【问题描述】:

如何使我的 mat plot lib 具有交互性?例如,当我将鼠标悬停在混淆矩阵的每个单元格上时,我想显示该预测的实例。

confusion_mat_df = pd.DataFrame(confusion_mat,columns = pred_spectrum, index = actual_spectrum)

plt.figure(figsize=(7,5)) # width,height
sns.heatmap(confusion_mat_df, annot=True)

【问题讨论】:

  • 看看mplcursors,文档中包含了很多示例,this 可能会有所帮助。
  • 是的,我想使用这些工具,但我还没有看到如何将它们实现到 sklearn 混淆矩阵中
  • 当我在问题中更新时,我实际上转换为 df,然后用 sns 绘图。有小费吗?谢谢!

标签: python matplotlib confusion-matrix mplcursors


【解决方案1】:

这里有一个示例来说明如何将mplcursors 用于 sklearn 混淆矩阵。

不幸的是,mplcursors 不适用于 seaborn 热图。 Seaborn 使用QuadMesh 作为热图,它不支持必要的coordinate picking

在下面的代码中,我在单元格的中心添加了置信度,类似于 seaborn 的。我还更改了文本和箭头的颜色,以便于阅读。您需要根据自己的情况调整颜色和尺寸。

from sklearn.metrics import confusion_matrix
from matplotlib import pyplot as plt
import mplcursors

y_true = ["cat", "ant", "cat", "cat", "ant", "bird", "dog"]
y_pred = ["ant", "ant", "cat", "cat", "ant", "cat", "dog"]
labels = ["ant", "bird", "cat", "dog"]
confusion_mat = confusion_matrix(y_true, y_pred, labels=labels)

fig, ax = plt.subplots()
heatmap = plt.imshow(confusion_mat, cmap="jet", interpolation='nearest')

for x in range(len(labels)):
    for y in range(len(labels)):
        ax.annotate(str(confusion_mat[x][y]), xy=(y, x),
                    ha='center', va='center', fontsize=18, color='white')

plt.colorbar(heatmap)
plt.xticks(range(len(labels)), labels)
plt.yticks(range(len(labels)), labels)
plt.ylabel('Predicted Values')
plt.xlabel('Actual Values')

cursor = mplcursors.cursor(heatmap, hover=True)
@cursor.connect("add")
def on_add(sel):
    i, j = sel.target.index
    sel.annotation.set_text(f'{labels[i]} - {labels[j]} : {confusion_mat[i, j]}')
    sel.annotation.set_fontsize(12)
    sel.annotation.get_bbox_patch().set(fc="papayawhip", alpha=0.9, ec='white')
    sel.annotation.arrow_patch.set_color('white')

plt.show()

PS:注解可以是多行的,例如:

sel.annotation.set_text(f'Predicted: {labels[i]}\nActual: {labels[j]}\n{confusion_mat[i, j]:5}')

【讨论】:

  • 太棒了!非常感谢!事实上,就我而言,我将 conf 矩阵转换为 df,然后用 sns 绘制。
  • 现在我想在每次点击单元格时打开一个 json 文件。
  • 那么如果我首先将conf矩阵转换为df,我该怎么做
  • 也许你可以写confusion_mat_df [i][j]而不是confusion_mat[i, j]。但保留原始混淆矩阵似乎更方便,因为它是一种更紧凑的格式。
猜你喜欢
  • 2020-12-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-07
  • 2020-02-23
  • 2022-06-10
  • 1970-01-01
相关资源
最近更新 更多