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