numpy中两个矩阵之间有多少行相等

How many rows are equals between two matrices in numpy

我正在为多标签分类问题训练神经网络。我有两行 A 和 B,大小为 BxL(B = 批量大小,L = 标签数),其中 A 是小批量的实际标签,B 是我的模型做出的预测,类似这样:

A = array([[0., 1., 0.],
          [0., 1., 1.],
          [0., 1., 0.],
          [0., 0., 0.]])

B = array([[1., 1., 0.],
          [0., 1., 1.],
          [0., 0., 0.],
          [0., 1., 0.]])

我想计算有多少样本被正确分类(也就是说,A 和 B 中有多少行相等)

我想知道是否有办法使用 tensor/numpy 并行函数...

类似

sum(torch.eq(A,B, axis=0)) # that doesn't exists

您可以将 numpyall 一起使用:

np.sum((A == B).all(1))
#1

这通过搜索每行中的所有值是否匹配来实现。

>>> A == B
array([[False,  True,  True],
       [ True,  True,  True],
       [ True, False,  True],
       [ True, False,  True]])

为您提供元素匹配的位置,然后 all(axis=1) returns 行的布尔值,其中所有值为 True:

>>> (A == B).all(1)
array([False,  True, False, False])

显示索引 1 处的行是两个数组之间的精确匹配。

然后,对布尔数组求和即可得到此类行的计数。