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": "预测值"},         "yaxis": {"title": "实际值"}    }    fig = go.Figure(data=go.Heatmap(z=confusion_matrix,                                    x=class_names,                                    y=class_names,                                    hoverongaps=False),                    layout=layout)    fig.show()

结果是

enter image description here

如何在每个单元格内显示数字,而不是悬停时显示,像这样enter image description here


回答:

你可以使用带注释的热图ff.create_annotated_heatmap()来实现这个效果:

enter image description here

完整代码:

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()

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注