混淆矩阵计算和绘制

from sklearn.metrics import confusion_matrix
result = confusion_matrix(test_labels, predicted_labels)
plot_confusion_matrix(result)
def plot_confusion_matrix(cm, title='Confusion matrix', cmap=plt.cm.Blues):
    """
    Plots confusion matrix, 
    
    cm - confusion matrix(np.array()数组)
    """
    plt.figure(1, figsize=(15, 12), dpi=160)
    plt.imshow(cm, interpolation='nearest', cmap=cmap)
    plt.title(title)
    plt.colorbar()
    plt.tight_layout()
    plt.ylabel('True label')
    plt.xlabel('Predicted label')

    plt.show()  
# print result
Confusion matrix:
[[ 46  23  24  12  23]
 [  5  64  35   3   9]
 [  9   0 100   2   7]
 [ 27   7  33  22  23]
 [ 19   5  42  22  38]]

在这里插入图片描述

def plot_Confusion_matrix(metrix):
    # coding=utf-8
    import matplotlib.pyplot as plt
    import numpy as np

    confusion = np.zeros((5, 5))
    for i in range(len(metrix)):
        for j in range(len(metrix[0])):
            confusion[i][j] = round(metrix[i][j] / sum(metrix[i]), 2)
    print(confusion)

    # confusion = np.array(([91, 0, 0], [0, 92, 1], [0, 0, 95]))
    # 热度图,后面是指定的颜色块,可设置其他的不同颜色
    plt.imshow(confusion, cmap=plt.cm.Blues, interpolation='nearest')
    # ticks 坐标轴的坐标点
    # label 坐标轴标签说明
    indices = np.array(range(len(confusion)))
    # 第一个是迭代对象,表示坐标的显示顺序,第二个参数是坐标轴显示列表
    # plt.xticks(indices, [0, 1, 2])
    # plt.yticks(indices, [0, 1, 2])
    label_name = ["school", "residence", "industrial", "commerce", "commonality"]
    plt.xticks(indices, label_name, rotation=50)
    plt.yticks(indices, label_name)

    plt.colorbar()

    plt.xlabel('Predicted label')
    plt.ylabel('True label')
    plt.title('Confusion_matrix')
    plt.ylim(len(confusion) - 0.5, -0.5)

    # plt.rcParams两行是用于解决标签不能显示汉字的问题
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False

    # 显示数据
    for first_index in range(len(confusion)):  # 第几行
        for second_index in range(len(confusion[first_index])):  # 第几列
            # plt.text(first_index, va='center', ha='center')
            plt.text(first_index, second_index,
                     confusion[first_index][second_index],
                     color="white" if first_index == second_index else"black",
                     fontsize=10, va='center', ha='center')  # 数字居中
    # 在matlab里面可以对矩阵直接imagesc(confusion)
    # 显示
    plt.savefig('./confusion_matrix.png', format='png')
    plt.show()

在这里插入图片描述

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值