将 Python 中的数组划分为混淆矩阵

Dividing arrays in Python for confusion matrix

我有一个 2x2 的对象,我想将它除以 2x1,这样第一个分量除以第一行,第二个分量除以第二行。 我该怎么做?

cm = sklearn.metrics.confusion_matrix(Y1,Y2)
cm_sum = np.sum(cm, axis=1)
cm_perc = cm /  cm_sum.astype(float) * 100

你只需要有合适的维度。您要除的那个必须是列向量。我们使用 .rehshape(-1,1) 来实现。

a = np.array([[2,3], [5,6]])
print(a)
b = np.array([2, 4]).reshape(-1, 1)
print(b)
print(a/b)

输出

[[2 3]
 [5 6]]
[[2]
 [4]]
[[1.   1.5 ]
 [1.25 1.5 ]]

所以你的代码将是 -

Y1 = [1,0,1,0]
Y2 = [0,0,1,0]
cm = metrics.confusion_matrix(Y1,Y2)
cm_sum = np.sum(cm, axis=1).reshape(-1,1)
cm_perc = cm / cm_sum

您还可以在 np.sum 中使用 keepdims 参数,这将基本上保持维度,并且在这种情况下输出将是列向量。所以-

cm_sum = np.sum(cm, axis=1, keepdims=True)

也可以。