3

如何使我的 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)
4

1 回答 1

2

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

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

在下面的代码中,我在单元格的中心添加了置信度,类似于 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}')
于 2020-01-20T12:56:09.660 回答