我喜欢用Plotly来可视化一切,我正在尝试用Plotly来可视化一个混淆矩阵,我的代码如下:
def plot_confusion_matrix(y_true, y_pred, class_names): confusion_matrix = metrics.confusion_matrix(y_true, y_pred) confusion_matrix = confusion_matrix.astype(int) layout = { "title": "Confusion Matrix", "xaxis": {"title": "预测值"}, "yaxis": {"title": "实际值"} } fig = go.Figure(data=go.Heatmap(z=confusion_matrix, x=class_names, y=class_names, hoverongaps=False), layout=layout) fig.show()
结果是
回答:
你可以使用带注释的热图ff.create_annotated_heatmap()
来实现这个效果:
完整代码:
import plotly.figure_factory as ffz = [[0.1, 0.3, 0.5, 0.2], [1.0, 0.8, 0.6, 0.1], [0.1, 0.3, 0.6, 0.9], [0.6, 0.4, 0.2, 0.2]]x = ['healthy', 'multiple diseases', 'rust', 'scab']y = ['healthy', 'multiple diseases', 'rust', 'scab']# 将z的每个元素转换为字符串以便注释z_text = [[str(y) for y in x] for x in z]# 设置图形fig = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, colorscale='Viridis')# 添加标题fig.update_layout(title_text='<i><b>混淆矩阵</b></i>', #xaxis = dict(title='x'), #yaxis = dict(title='x') )# 添加自定义x轴标题fig.add_annotation(dict(font=dict(color="black",size=14), x=0.5, y=-0.15, showarrow=False, text="预测值", xref="paper", yref="paper"))# 添加自定义y轴标题fig.add_annotation(dict(font=dict(color="black",size=14), x=-0.35, y=0.5, showarrow=False, text="实际值", textangle=-90, xref="paper", yref="paper"))# 调整边距以便为y轴标题留出空间fig.update_layout(margin=dict(t=50, l=200))# 添加颜色条fig['data'][0]['showscale'] = Truefig.show()