如何在Python中计算多个混淆矩阵总和并推导TP、FP、FN、TN
问题:多个混淆矩阵求和并计算TP/FP/FN/TN
我将5个混淆矩阵存储在列表cm_decision_tree中,想要计算这些矩阵的总和,再据此提取True Positive(TP)、False Positive(FP)、False Negative(FN)和True Negative(TN)。但运行代码时出现错误:
cm_decision_tree = [] cm_decision_tree.append(confusion_matrix(y_test, decision_tree_pred)) # 打印结果为包含5个numpy数组的列表 [array([[ 0, 9], [ 4, 2]], dtype=int64), array([[ 4, 6], [1, 6]], dtype=int64), array([[ 1, 10], [ 0, 9]], dtype=int64), array([[ 4, 14], [ 5, 5]], dtype=int64), array([[ 0, 14], [ 7, 2]], dtype=int64)] # 尝试计算均值时报错 from statistics import mean matrix_result_average=cm_decision_tree.mean(axis=0)
错误信息:
AttributeError: 'list' object has no attribute 'mean'
错误原因
Python原生列表(list)没有mean()方法,且statistics.mean仅用于计算一维数值的均值,无法处理多维数组组成的列表。必须先将列表转换为numpy数组,才能使用numpy的数组运算方法。
解决方案
步骤1:将列表转为numpy数组
利用numpy.array()把存储混淆矩阵的列表转换为多维numpy数组,这样就能使用numpy的求和、求均值方法。
步骤2:计算混淆矩阵的总和(或均值)
使用sum(axis=0)对所有混淆矩阵按元素求和,若需要均值则用mean(axis=0)。
步骤3:提取TP/FP/FN/TN
二分类混淆矩阵的标准结构为[[TN, FP], [FN, TP]],直接从总矩阵中提取对应位置的数值即可。
完整代码示例:
import numpy as np # 转换列表为numpy数组 cm_array = np.array(cm_decision_tree) # 计算所有混淆矩阵的总和 total_confusion_matrix = cm_array.sum(axis=0) # 提取指标 TN, FP = total_confusion_matrix[0] FN, TP = total_confusion_matrix[1] # 输出结果 print("总和混淆矩阵:\n", total_confusion_matrix) print(f"TP: {TP}, FP: {FP}, FN: {FN}, TN: {TN}")
运行上述代码后,就能得到所有混淆矩阵的总和,并正确提取四个指标。
内容的提问来源于stack exchange,提问作者Haseeb Tariq
相关产品推荐
相关产品推荐

