用于2D数组的np.ufunc.at

问题描述 投票:0回答:1

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

>> 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.]
])
python numpy numpy-broadcasting numpy-ufunc numpy-indexing
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)
© www.soinside.com 2019 - 2024. All rights reserved.