如何让混淆矩阵热力图颜色基于分类正确率百分比
修改混淆矩阵热力图的颜色映射逻辑
要实现热力图颜色基于单元格数值占对应真实类别(行)总数的百分比,而非原始计数,只需调整热力图的颜色数据源,同时保留原始数值作为标注,具体实现如下:
修改后的完整代码
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 原始混淆矩阵 cf_matrix = np.array([[50, 2, 38], [7, 43, 32], [1, 0, 4]]) labels = ['col1','col2','col3'] df_confusion = pd.DataFrame(cf_matrix, index=labels, columns=labels) # 计算每行总和,生成百分比矩阵(用于颜色映射) row_totals = df_confusion.sum(axis=1) percent_matrix = df_confusion.div(row_totals, axis=0) # 添加总计行和列(保持原始计数的总计逻辑) df_confusion['TOTAL'] = row_totals df_confusion.loc['TOTAL'] = df_confusion.sum() # 为百分比矩阵补充总计行和列 percent_matrix['TOTAL'] = 1.0 # 行总计对应100%占比 percent_matrix.loc['TOTAL'] = df_confusion.loc['TOTAL'] / df_confusion.loc['TOTAL', 'TOTAL'] plt.figure(figsize=(24, 10)) sns.set(font_scale=1.5) # 核心修改:用百分比矩阵控制颜色,原始矩阵显示标注 ax = sns.heatmap(percent_matrix, annot=df_confusion, cmap='Blues', fmt="d") ax.set_title('Confusion Matrix (Color by Row Percentage)\n\n', size=22) ax.set_xlabel('\nPredicted Values', size=20) ax.set_ylabel('Actual Values ', size=20) plt.show()
关键修改说明
- 生成百分比矩阵:通过
df_confusion.div(row_totals, axis=0)让每个单元格数值除以所在行的总和,得到该行的占比,这个矩阵是热力图颜色深浅的依据 - 分离颜色与标注:调用
sns.heatmap时,data参数传入percent_matrix(决定颜色),annot参数传入原始的df_confusion(显示真实计数),fmt="d"确保标注以整数形式展示 - 总计行/列适配:行总计的百分比设为1.0(即100%),列总计的百分比按该列总计占整体总数的比例计算,保证颜色逻辑统一
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

