0

为了计算混淆矩阵(而不是准确性),可能需要在预测标签和真实标签上循环。如果下一个代码没有给出所需的结果,如何以 numpy 的方式执行该操作?

>> a = np.zeros((5, 5))
>> indices = np.array([
      [0, 0], 
      [2, 2],
      [4, 4],
      [0, 0],
      [2, 2],
      [4, 4],
   ])
np.add.at(a, indices, 1)
>> a
>> array([
   [4., 4., 4., 4., 4.],
   [0., 0., 0., 0., 0.],
   [4., 4., 4., 4., 4.],
   [0., 0., 0., 0., 0.],
   [4., 4., 4., 4., 4.]
])

# Wanted 
>> array([
   [2., 0., 0., 0., 0.],
   [0., 0., 0., 0., 0.],
   [0., 0., 2., 0., 0.],
   [0., 0., 0., 0., 0.],
   [0., 0., 0., 0., 2.]
])
4

1 回答 1

1

文件说If first operand has multiple dimensions, indices can be a tuple of array like index objects or slice objects.

使用下一个元组达到想要的结果。

np.add.at(a, (indices[:, 0], indices[:, 1]), 1)
于 2020-03-17T17:50:43.880 回答