Seaborn混淆矩阵热力图显示异常,请求显示优化指导
优化120类犬种混淆矩阵热力图显示方案
我看你在处理120类犬种的混淆矩阵热力图时,只调整figsize还是没法正常显示——毕竟120个标签挤在一起,光调画布尺寸远远不够。结合你的代码,我给你几个针对性的优化方案:
核心优化方向
针对多类别(120类)的热力图,我们需要解决标签重叠、注释文字拥挤、布局裁剪这三个核心问题,下面是具体实现:
1. 调整标签与注释的显示样式
120个犬种名称作为坐标轴标签,默认字体和排列方式肯定会挤成一团。我们可以缩小标签字体、旋转x轴标签,同时调整注释文字大小,再让布局自动适配:
def show_confusion_matrix(test_labels,predictions): confusion = sk_metrics.confusion_matrix(np.argmax(test_labels,axis=1), np.argmax(predictions,axis=1)) confusion_normalized = confusion.astype('float') / confusion.sum(axis=1) axis_labels = list(uniquelabel) ## 120个犬种名称 # 用正方形画布配合square=True,更适配对称的混淆矩阵 fig, ax = plt.subplots(figsize=(40, 40)) ax = sns.heatmap(confusion_normalized, xticklabels=axis_labels, yticklabels=axis_labels, linewidths=0.1, cmap='Blues', annot=True, fmt='.2f', square=True, # 缩小单元格内的注释文字,避免重叠 annot_kws={"size": 6}) plt.title('Normalized Confusion Matrix (120 Dog Breeds)', fontsize=16) plt.ylabel("True Label", fontsize=12) plt.xlabel("Predicted Label", fontsize=12) # 调整坐标轴标签:x轴垂直旋转+缩小字体,y轴直接缩小字体 plt.xticks(rotation=90, fontsize=8) plt.yticks(fontsize=8) # 自动调整布局,防止标签被画布边缘裁剪 plt.tight_layout() # 如果需要保存图片,加bbox_inches='tight'避免裁剪 # plt.savefig('confusion_matrix.png', dpi=300, bbox_inches='tight') plt.show() show_confusion_matrix(y_test,predictions)
2. 可选:隐藏低占比注释(减少视觉干扰)
如果120类的注释还是过于密集,可以只显示大于某个阈值的单元格注释(比如只显示准确率>0.1的),减少无效信息:
# 生成自定义注释矩阵:只保留大于0.1的数值,其余为空字符串 annot_matrix = np.where(confusion_normalized > 0.1, confusion_normalized.round(2), '') ax = sns.heatmap(confusion_normalized, xticklabels=axis_labels, yticklabels=axis_labels, linewidths=0.1, cmap='Blues', annot=annot_matrix, # 使用自定义注释矩阵 fmt='', # 因为是字符串格式,无需数值格式化 square=True, annot_kws={"size": 7})
3. 额外提示:提升图片清晰度
如果最终显示或保存的图片模糊,可以在创建画布时指定更高的dpi,或者保存时提升分辨率:
# 创建画布时设置高dpi fig, ax = plt.subplots(figsize=(40, 40), dpi=150) # 保存图片时指定高分辨率 plt.savefig('confusion_matrix_highres.png', dpi=300, bbox_inches='tight')
这些改动应该能让你的120类混淆矩阵正常显示,标签和注释都不会重叠或被裁剪。
内容的提问来源于stack exchange,提问作者Sammy
相关产品推荐
相关产品推荐

