您当前的方法存在一些问题。首先,np.bincount(x)
将为您提供 每个 x 的正整数值的计数从 0 开始
并以max(x)结尾:
print(np.bincount([1, 1, 3, 3, 3, 4]))
# [0, 2, 0, 3, 1]
# i.e. [count for 0, count for 1, count for 2, count for 3, count for 4]
因此,如果不是acc.flat 中的每个位置都被编入索引,那么
np.bincount(raveled) 将大于唯一索引的数量。什么
您实际上想要的是acc.flat 中那些位置的计数
索引至少一次。
其次,您要做的是将 bin 计数分配给相应的
索引到acc.flat。你打电话给np.resize 所做的是重复部分
您的 bincounts 数组,以使其大小与acc.flat 相同,
然后将其重塑为与acc 相同的形状。这不会导致垃圾箱
计数被分配到acc中的正确位置!
我解决这个问题的方法是使用np.unique 而不是
np.bincount,并使用它返回唯一索引及其对应的
计数。然后可以使用这些将正确的计数分配给acc 内的正确唯一位置:
import numpy as np
# some example data
acc = np.zeros((4, 3))
legit_indices = np.array([[0, 1],
[0, 1],
[1, 2],
[1, 0],
[1, 0],
[1, 0]])
# convert the index array into a set of indices into acc.flat
flat_idx = np.ravel_multi_index(legit_indices.T, acc.shape)
# get the set of unique indices and their corresponding counts
uidx, ucounts = np.unique(flat_idx, return_counts=True)
# assign the count value to each unique index in acc.flat
acc.flat[uidx] = ucounts
# confirm that this matches the result of your for loop
acc2 = np.zeros_like(acc)
for ii, jj in legit_indices:
acc2[ii, jj] += 1
assert np.array_equal(acc, acc2)