我想制作一个混淆矩阵,允许我点击任何单元格,从而打开那些预测结果的文件。例如,当我点击第i行第j列的单元格时,应该打开一个json文件,显示所有实际类型为i但我预测为类型j的项目。
回答:
您可以尝试使用mplcursor来在点击单元格时执行操作。mplcursor
有一个参数hover=
,当设置为False(默认值)时,点击时会显示注释。您可以隐藏注释并执行其他类型的操作。mplcursor
有助于识别您点击的位置。
您可以不隐藏注释,而是用文件内容填充它。要关闭注释,可以右键点击它,或者左键点击打开另一个注释。
以下是一些包含虚构的json文件字段的演示代码:
from sklearn.metrics import confusion_matrixfrom matplotlib import pyplot as pltimport mplcursorsimport jsony_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()