python将confusion_matrix函数得到的混淆矩阵输出到excel,便于自己绘图

因为混淆矩阵的结果是数组类型的,ndarray,所以按照输出二维列表就行。
代码如下:

# 画混淆矩阵
    Confuse = confusion_matrix(target_list, pred_list, labels=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
    output = open('confuse_res20.xls', 'w', encoding='gbk')
    output.write('confuse_res20\n')
    for i in range(len(Confuse)):
        for j in range (len(Confuse[i])):
            output.write(str(Confuse[i][j]))  # write函数不能写int类型的参数,所以使用str()转化
            output.write('\t')
        output.write('\n')  # 写完一行立马换行
    output.close()
可以使用Python中的Matplotlib库来生成混淆矩阵图像。以下是一个示例代码,其中红色部分可以改为黑色: ```python import matplotlib.pyplot as plt import numpy as np # 创建混淆矩阵 confusion_matrix = np.array([[100, 10, 5], [25, 80, 15], [10, 20, 70]]) # 绘图 fig, ax = plt.subplots() im = ax.imshow(confusion_matrix, cmap='Reds') # 添加文本 for i in range(confusion_matrix.shape[0]): for j in range(confusion_matrix.shape[1]): text = ax.text(j, i, confusion_matrix[i, j], ha='center', va='center', color='black') # 设置轴标签 ax.set_xlabel('预测标签') ax.set_ylabel('真实标签') # 添加分类标签 labels = ['类别1', '类别2', '类别3'] ax.set_xticks(np.arange(len(labels))) ax.set_yticks(np.arange(len(labels))) ax.set_xticklabels(labels) ax.set_yticklabels(labels) # 设置网格线 ax.set_xticks(np.arange(confusion_matrix.shape[1]+1)-.5, minor=True) ax.set_yticks(np.arange(confusion_matrix.shape[0]+1)-.5, minor=True) ax.grid(which='minor', color='w', linestyle='-', linewidth=3) # 设置标题 ax.set_title('混淆矩阵') # 显示图像 plt.show() ``` 在上面的代码中,我们使用`imshow`函数来创建混淆矩阵,使用`text`函数添加每个单元格的数字,使用`set_xticklabels`和`set_yticklabels`函数添加标签,使用`grid`函数添加网格线,使用`set_title`函数添加标题。通过设置`color`参数为'black',我们可以将数字颜色设置为黑色。如果要将其他部分设置为透明,可以通过设置`alpha`参数来实现。 你可以根据需要调整代码中的参数,例如更改混淆矩阵,更改标签,更改标题等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值