繁体   English   中英

如何向通过 Seaborn 热图渲染的混淆矩阵添加工具提示?

[英]How to add tooltips to a confusion matrix rendered via a Seaborn heatmap?

如何使我的 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用于 sklearn 混淆矩阵。

不幸的是,mplcursors 不适用于 seaborn 热图。 Seaborn 使用QuadMesh作为热图,它不支持必要的坐标拾取

在下面的代码中,我在单元格的中心添加了置信度,类似于 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}')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM