使用python画混淆矩阵(并解决坐标重叠问题)

本文详细介绍了如何使用Python从.mat文件加载预测与真实标签数据,将其转换为列表,并利用sklearn库生成混淆矩阵。通过matplotlib进行混淆矩阵的可视化,展示了类别间的预测准确性,特别适用于40类分类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import scipy.io
p='D:/debug/predict_array'
r='D:/debug/real_array'
dataP=scipy.io.loadmat(p);# dataP类型为dictionary
dataR=scipy.io.loadmat(r);
predict=dataP['predict_array']#获得其中的矩阵数据
real=dataR['real_array'] #此行往上:将matlab中的矩阵提取到python中
real=real.tolist()#将矩阵转化为列表
predict=predict.tolist()

from itertools import chain
real=list(chain.from_iterable(real))
predict=list(chain.from_iterable(predict))#将二维列表转为一维`import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.metrics import confusion_matrix

def plot_confusion_matrix(confusion):
    plt.imshow(confusion,cmap=plt.cm.Blues)
    plt.title('Confusion Matrix')
    plt.colorbar()
    
    labels = range(1,41)
    tick_marks = np.arange(len(labels))
    plt.xticks(tick_marks, labels)
    plt.yticks(tick_marks, labels)
    ax = plt.gca()
    #解决坐标重叠问题
    for ind, label in enumerate(ax.xaxis.get_ticklabels()):
        if ind % 3 == 0:  # every 10th label is kept
            label.set_visible(True)
        else:
            label.set_visible(False)
    for ind, label in enumerate(ax.yaxis.get_ticklabels()):
        if ind % 3 == 0:  # every 10th label is kept
            label.set_visible(True)
        else:
            label.set_visible(False)
    plt.ylabel('True Label')
    plt.xlabel('Predicted Label')
    #plt.savefig('confusion_matrix_40class.pdf', format='pdf')
   
    plt.show()
    
if __name__ == '__main__':
    confusion = confusion_matrix(predict, real)#混淆矩阵简单应用
    #confusion = np.log10(confusion)
    plot_confusion_matrix(confusion)
    print(confusion)
%matplotlib inline   `
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值