我将5个混淆矩阵的结果存储在一个数组中。现在我必须计算混淆矩阵的总和,然后我想用它来计算真阳性、假阳性、假阴性和真阴性。以下是我正在使用的代码:
cm_decision_tree = []
cm_decision_tree.append(confusion_matrix(y_test, decision_tree_pred))
print (cm_decision_tree)
[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)]
matrix_result_average=cm_decision_tree.mean(axis=0)
当我尝试使用上面的代码片段计算该结果的平均值时,出现此错误
1 from statistics import mean
2 matrix_result_average=cm_decision_tree.mean(axis=0)
AttributeError: 'list' object has no attribute 'mean'
我的预期结果是根据多个混淆矩阵的总和计算真阳性、假阳性、假阴性和真阴性。
sklearn.metrics.confusion_matrix
返回一个 np.ndarray
,您的对象 cm_decision_tree
代表 list
的 numpy.ndarray
。要计算混淆矩阵的总和,您可以执行以下操作:
cm_decision_tree_summed = np.sum(cm_decision_tree, axis=0)
print(cm_decision_tree_summed)
# [[ 9 53]
# [17 24]]
请注意,这个求和混淆矩阵本质上包含真阳性、假阳性等,这就是为什么不需要额外计算的原因。
用于复制错误的代码:
import numpy as np
matrix_1 = np.array(
[[0, 9],[4, 2]]
)
matrix_2 = np.array(
[[4, 6], [1, 6]]
)
matrix_3 = np.array(
[[1, 10], [0, 9]]
)
matrix_4 = np.array(
[[4, 14], [5, 5]]
)
matrix_5 = np.array(
[[0, 14], [7, 2]]
)
cm_decision_tree = [matrix_1, matrix_2, matrix_3, matrix_4, matrix_5]
matrix_result_average=cm_decision_tree.mean(axis=0) # AttributeError: 'list' object has no attribute 'mean'