You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中从5分类模型的混淆矩阵提取性能指标?

适配5分类任务的混淆矩阵指标计算函数修改方案

问题背景

我在Python中构建了一个目标为5类的多分类模型,得到如下混淆矩阵:

confusion_matrix(y_test, model.predict(X_test))

[[2006 114 80 312 257]
 [567  197 87 102 155]
 [256  84  316 39 380]
 [565  30  67 592 546]
 [363  71  186 301 1402]]

需要基于上述混淆矩阵计算以下指标:

  • True Negative(TN)
  • False Positive(FP)
  • False Negative(FN)
  • True Positive(TP)
  • Accuracy(准确率)
  • True Positive Rate(真正例率,召回率)
  • False Positive Rate(假正例率)
  • True Negative Rate(真负例率,特异度)
  • False Negative Rate(假负例率)

已有一个适用于二分类任务的计算函数:

def xx(model, X_test, y_test):
    CM = confusion_matrix(y_test, model.predict(X_test))
    print(CM)

    print("-"*40)

    TN = CM[0][0]
    FP = CM[0][1]
    FN = CM[1][0]
    TP = CM[1][1]
    sensitivity=TP/float(TP+FN)
    specificity=TN/float(TN+FP)

    print("True Negative:", TN)
    print("False Positive:", FP)
    print("False Negative:", FN)
    print("True Positive:", TP)
    print("Accuracy", round((TN + TP) / len(model.predict(X_test)) * 100, 2), "%")
    print("True Positive rate",round(TP/(TP+FN)*100,2), "%")
    print("False Positive rate",round(FP/(FP+TN)*100,2), "%")
    print("True Negative rate",round(TN/(FP+TN)*100,2), "%")
    print("False Negative rate",round(FN/(FN+TP)*100,2), "%")

修改思路

多分类任务中,上述指标需要针对每个类别单独计算(二分类是二元对立判断,多分类需对每个类别做独立的"是/非"判定):

  1. TP:混淆矩阵当前类别对角线元素(真实为该类且预测正确的样本数)
  2. FN:当前类别所在行的非对角线元素总和(真实为该类但预测错误的样本数)
  3. FP:当前类别所在列的非对角线元素总和(真实为其他类但被预测为该类的样本数)
  4. TN:总样本数减去TP、FN、FP的和(既不是真实该类,也不是预测该类的样本数)
  5. Accuracy:全局指标,所有正确分类的样本数(对角线元素总和)除以总样本数

修改后的函数

from sklearn.metrics import confusion_matrix

def calculate_multiclass_metrics(model, X_test, y_test):
    y_pred = model.predict(X_test)
    CM = confusion_matrix(y_test, y_pred)
    print("混淆矩阵:")
    print(CM)
    print("-" * 60)

    total_samples = len(y_test)
    # 计算全局准确率
    overall_accuracy = round(CM.trace() / total_samples * 100, 2)
    print(f"全局准确率: {overall_accuracy} %")
    print("-" * 60)

    # 遍历每个类别计算指标
    num_classes = CM.shape[0]
    for cls in range(num_classes):
        print(f"=== 类别 {cls} 的指标 ===")
        # 计算TP/TN/FP/FN
        TP = CM[cls][cls]
        FN = CM[cls].sum() - TP
        FP = CM[:, cls].sum() - TP
        TN = total_samples - TP - FN - FP

        # 计算各类率指标,避免除以0报错
        tpr = round(TP / (TP + FN) * 100, 2) if (TP + FN) != 0 else 0.0
        fpr = round(FP / (FP + TN) * 100, 2) if (FP + TN) != 0 else 0.0
        tnr = round(TN / (FP + TN) * 100, 2) if (FP + TN) != 0 else 0.0
        fnr = round(FN / (TP + FN) * 100, 2) if (TP + FN) != 0 else 0.0

        # 打印结果
        print(f"True Positive (TP): {TP}")
        print(f"False Negative (FN): {FN}")
        print(f"False Positive (FP): {FP}")
        print(f"True Negative (TN): {TN}")
        print(f"True Positive Rate (召回率): {tpr} %")
        print(f"False Positive Rate: {fpr} %")
        print(f"True Negative Rate (特异度): {tnr} %")
        print(f"False Negative Rate: {fnr} %")
        print("-" * 40)

函数说明

  • 先输出全局准确率,再逐个输出每个类别的细分指标
  • 增加分母为0的判断逻辑,避免运行时报错
  • 输出格式更清晰,区分全局指标与单类别指标
  • 兼容任意数量的分类任务(不限于5类)

内容的提问来源于stack exchange,提问作者dingaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 03:09:26