我可以按下混淆矩阵中的一个单元格从而打开一个文件吗?

Can I press on a cell in a confusion matrix and thereby open a file?

我想制作一个混淆矩阵,允许我按下任何单元格,从而打开这些预测结果的文件。例如,当我按下第 i 行第 j 列中的单元格时,它应该打开一个 json 文件,该文件向我显示所有真正属于 i 类型但我预测它们为 j 类型的项目。

您可以尝试使用 mplcursor to perform an action when you click on a cell. An mplcursor has a parameter hover=,当设置为 False(默认值)时,它会在您单击时显示注释。您可以取消注释并执行其他类型的操作。 mplcursor 有助于识别您点击的位置。

您可以用文件的内容填充它,而不是隐藏注释。要关闭注释,请右键单击它,或左键单击以打开另一个注释。

这是一些演示代码,其中包含一些为 json 文件发明的虚拟字段:

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

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

heatmap = plt.imshow(confusion_mat, cmap="plasma", interpolation='nearest')

plt.colorbar(heatmap, ticks=range(3))

plt.xticks(range(len(labels)), labels)
plt.yticks(range(len(labels)), labels)

cursor = mplcursors.cursor(heatmap, hover=False)
@cursor.connect("add")
def on_add(sel):
    i, j = sel.target.index
    filename = f'filename_{i}_{j}.json'
    text = f'Data about pred:{labels[i]} – actual:{labels[j]}\n'
    try:
        with open(filename) as json_file:
            data = json.load(json_file)
            for p in data['people']:
                text += f"Name: {p['name']}\n"
                text += f"Trials: {p['trials']}\n"
    except:
        text += f'file {filename} not found'
    sel.annotation.set_text(text)

plt.show()