我有一个混淆矩阵:

import pandas as pd
import seaborn as sn
import matplotlib.pyplot as plt

data = {'y_Actual':    [3, 3, 1, 1, 0, 1, 2, 3, 1, 1, 1, 0, 2, 4, 3],
        'y_Predicted': [1, 2, 2, 1, 0, 1, 3, 0, 1, 0, 0, 0, 3, 4, 2]
        }

df = pd.DataFrame(data, columns=['y_Actual','y_Predicted'])
confusion_matrix = pd.crosstab(df['y_Actual'], df['y_Predicted'],
                               rownames=['Actual'], colnames=['Predicted'])

sn.heatmap(confusion_matrix, annot=True)
plt.show()

enter image description here

是否可以按对角值降序排列此混淆矩阵?

推荐答案

可以在对角线上使用numpy.argsort(降序的相反值)并重新索引:

import numpy as np
order = np.argsort(-confusion_matrix.to_numpy().diagonal())
# array([1, 0, 4, 2, 3])

sn.heatmap(confusion_matrix.iloc[order, order], annot=True)

输出:

enter image description here

Python相关问答推荐

如何在polars(pythonapi)中解构嵌套 struct ?

如何在python xsModel库中定义一个可选[December]字段,以产生受约束的SON模式

如何获得每个组的时间戳差异?

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

有没有一种ONE—LINER的方法给一个框架的每一行一个由整数和字符串组成的唯一id?

Python Pandas获取层次路径直到顶层管理

不允许 Select 北极滚动?

freq = inject在pandas中做了什么?''它与freq = D有什么不同?''

如何获得3D点的平移和旋转,给定的点已经旋转?

如何使用Azure Function将xlsb转换为xlsx?

需要帮助使用Python中的Google的People API更新联系人的多个字段'

如何为需要初始化的具体类实现依赖反转和接口分离?

如何在SQLAlchemy + Alembic中定义一个"Index()",在基表中的列上

为什么Visual Studio Code说我的代码在使用Pandas concat函数后无法访问?

在matplotlib中重叠极 map 以创建径向龙卷风图

.awk文件可以使用子进程执行吗?

两个名称相同但值不同的 Select 都会产生相同的值(discord.py)

保存由PYTHON在EXCEL中所做更改的问题

使用pyopencl、ArrayFire或另一个Python OpenCL库制作基于欧几里得距离的掩模