python - Plotly:如何使用热图制作带注释的混淆矩阵?
问题描述
我喜欢使用 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": "Predicted value"},
"yaxis": {"title": "Real value"}
}
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 ff
z = [[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']
# change each element of z to type string for annotations
z_text = [[str(y) for y in x] for x in z]
# set up figure
fig = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, colorscale='Viridis')
# add title
fig.update_layout(title_text='<i><b>Confusion matrix</b></i>',
#xaxis = dict(title='x'),
#yaxis = dict(title='x')
)
# add custom xaxis title
fig.add_annotation(dict(font=dict(color="black",size=14),
x=0.5,
y=-0.15,
showarrow=False,
text="Predicted value",
xref="paper",
yref="paper"))
# add custom yaxis title
fig.add_annotation(dict(font=dict(color="black",size=14),
x=-0.35,
y=0.5,
showarrow=False,
text="Real value",
textangle=-90,
xref="paper",
yref="paper"))
# adjust margins to make room for yaxis title
fig.update_layout(margin=dict(t=50, l=200))
# add colorbar
fig['data'][0]['showscale'] = True
fig.show()
推荐阅读
- c - 数据库介绍的时间效率
- winforms - 如何将 winforms 应用程序部署到 Azure DevOps
- java - 如何在具有多个滚动元素的 Web 应用程序中执行窗口水平滚动?
- react-native - 在 React Navigation v5 中隐藏路线
- javascript - $(location).attr('href',url) 函数的加载和卸载
- node.js - Node.js 检查选项
- phone-call - 如何从 Ameyo 的印度电话号码中删除 +91
- locust - 如何在蝗虫性能测试脚本中从 csv 文件中读取数据?
- ios - 如何在 NSFetchedResultsController 中触发部分更新
- java - 一个组件需要一个名为“userService”的 bean,但找不到该 bean。这个错误是否有依赖关系