Python 绘制混淆矩阵函数 confusion_matrix

Python 绘制混淆矩阵函数 confusion_matrix

代码如下:

def plot_confusion_matrix(y_true, y_pred, labels):
    import matplotlib.pyplot as plt
    from sklearn.metrics import confusion_matrix
    cmap = plt.cm.binary
    cm = confusion_matrix(y_true, y_pred)
    tick_marks = np.array(range(len(labels))) + 0.5
    np.set_printoptions(precision=2)
    cm_normalized = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    plt.figure(figsize=(10, 8), dpi=120)
    ind_array = np.arange(len(labels))
    x, y = np.meshgrid(ind_array, ind_array)
    intFlag = 0 # 标记在图片中对文字是整数型还是浮点型
    for x_val, y_val in zip(x.flatten(), y.flatten()):
        #

        if (intFlag):
            c = cm[y_val][x_val]
            plt.text(x_val, y_val, "%d" % (c,), color='red', fontsize=8, va='center', ha='center')

        else:
            c = cm_normalized[y_val][x_val]
            if (c > 0.01):
                #这里是绘制数字,可以对数字大小和颜色进行修改
                plt.text(x_val, y_val, "%0.2f" % (c,), color='red', fontsize=7, va='center', ha='center')
            else:
                plt.text(x_val, y_val, "%d" % (0,), color='red', fontsize=7, va='center', ha='center')
    if(intFlag):
        plt.imshow(cm, interpolation='nearest', cmap=cmap)
    else:
        plt.imshow(cm_normalized, interpolation='nearest', cmap=cmap)
    plt.gca().set_xticks(tick_marks, minor=True)
    plt.gca().set_yticks(tick_marks, minor=True)
    plt.gca().xaxis.set_ticks_position('none')
    plt.gca().yaxis.set_ticks_position('none')
    plt.grid(True, which='minor', linestyle='-')
    plt.gcf().subplots_adjust(bottom=0.15)
    plt.title('')
    plt.colorbar()
    xlocations = np.array(range(len(labels)))
    plt.xticks(xlocations, labels, rotation=90)
    plt.yticks(xlocations, labels)
    plt.ylabel('Index of True Classes')
    plt.xlabel('Index of Predict Classes')
    plt.savefig('confusion_matrix.jpg', dpi=300)
    plt.show()

参考

### 关于ResNet模型的混淆矩阵Python代码实现 在构建和评估深度学习模型时,混淆矩阵是一种重要的工具,用于可视化分类器性能。对于基于ResNet架构的图像分类任务而言,计算并展示混淆矩阵有助于理解模型预测准确性。 下面给出一段利用`sklearn.metrics.confusion_matrix`函数来创建混淆矩阵,并通过matplotlib库将其可视化的Python代码示例: ```python import numpy as np from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay import matplotlib.pyplot as plt from tensorflow.keras.applications.resnet import ResNet50 from tensorflow.keras.preprocessing.image import ImageDataGenerator # 加载预训练好的ResNet50模型(不包括顶层) base_model = ResNet50(weights='imagenet', include_top=False) # 假设已经准备好测试集的数据生成器test_generator datagen = ImageDataGenerator(rescale=1./255.) test_generator = datagen.flow_from_directory( 'path_to_test_data', target_size=(224, 224), batch_size=32, class_mode='categorical' ) # 获取真实标签y_true以及预测概率p_pred y_true = test_generator.classes preds = base_model.predict(test_generator) p_pred = preds.argmax(axis=-1) # 计算混淆矩阵 cm = confusion_matrix(y_true, p_pred) # 可视化混淆矩阵 disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=test_generator.class_indices.keys()) fig, ax = plt.subplots(figsize=(8, 8)) disp.plot(ax=ax) plt.show() ``` 此段代码首先加载了一个不含顶部全连接层的ResNet50模型作为基础模型[^1];接着定义了ImageDataGenerator对象以便读取图片文件夹中的数据;随后获取了真实的类别标签与经过softmax激活后的预测向量;最后调用了confusion_matrix方法得到混淆矩阵,并借助ConfusionMatrixDisplay类进行了图形绘制[^2]。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值