如何解决带注释的热图轴顺序取决于数据类型
我正在尝试使用带注释的热图在 Plotly 中绘制混淆矩阵。现在我注意到由于某种原因,Y 轴会根据标签的数据类型翻转,即使我将数据类型强制为字符串也是如此。
下面的代码将提供两个图,其中第二个图与第一个图相比具有倒置的 Y 轴。第一个是我希望它显示的方式,无论类名的数据类型如何。
在哪里更改顺序,我如何强制它保持提供的列表顺序?
'''
import numpy as np
confm = array([[10,4,1,0],[1,20,10,[0,7,30,3,40,2],2,50]])
labels = [1,5]
import plotly.graph_objects as go
import plotly.figure_factory as ff
def plot_matrix(confm,class_names):
z = np.round(confm,2) # for readability
class_names = [str(c) for c in class_names] # force all to string
fig = ff.create_annotated_heatmap(z,colorscale='reds',xtype='array',ytype='array',x=class_names,y=class_names[::-1],# invert order
)
fig.update_layout(
title='Confusion matrix',width=600,height=600,margin=dict(pad=20),plot_bgcolor='white',xaxis=dict(title='Prediction',showticklabels = True,side='bottom',tickmode='array',tickvals=class_names,ticktext=class_names),yaxis=dict(title='Truth',ticktext=class_names[::-1])
)
fig.show()
plot_matrix(confm,5])
plot_matrix(confm,['a','b','c','d','e'])
'''
解决方法
很明显plotly 库会在可能的情况下转换回整数/数字。为了保持行为不变,你可以
class_names = [str(c)+"\0" for c in class_names] # force all to string
只需附加一个 null ascii 字符,然后防止它被强制转换回数字。
,这可以直接从 scikit 与 confm 一起使用,无需经过转换。唯一仍然打破它的是混合标签数据类型:
import plotly.graph_objects as go
import plotly.figure_factory as ff
from sklearn.metrics import confusion_matrix
def plot_matrix(confm,class_names):
z = np.round(confm,2)
z = z[::-1]
fig = ff.create_annotated_heatmap(z,colorscale='reds',xtype='array',ytype='array',x=class_names,y=class_names,)
fig.update_layout(
title='Confusion matrix',width=600,height=600,margin=dict(pad=20),plot_bgcolor='white',xaxis=dict(title='Prediction',# Prediction
showticklabels = True,side='bottom',tickmode='array',tickvals=class_names,ticktext=class_names),yaxis=dict(title='Truth',# Truth
tickmode='array',ticktext=class_names[::-1]
)
)
fig.show()
truth = ['a','a','b','b']
pred = ['a','a']
labels = ['a','b']
confm = confusion_matrix(truth,pred,labels)
plot_matrix(confm,labels)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。