【问题标题】:numpy: ravel_multi_index increment different results from iterating over indices loopnumpy:ravel_multi_index 增加迭代索引循环的不同结果
【发布时间】:2015-02-11 09:09:22
【问题描述】:

我有一个索引数组(可能重复),其中我将另一个 2D 矩阵中的每个索引递增 1。有几个建议,这个 answer 建议使用 np.ravel_multi_index。

所以,我已经尝试过了,但他们似乎没有给我相同的答案。知道为什么吗?

raveled = np.ravel_multi_index(legit_indices.T, acc.shape)
counts = np.bincount(raveled)
acc = np.resize(counts, acc.shape)

acc2 = np.zeros(acc2.shape)
for i in legit_indices:
    acc2[i[0], i[1]] += 1

(Pdb) np.array_equal(acc, acc2)
False

(Pdb) acc[493][5]
135
(Pdb) acc2[493][5]
0.0

【问题讨论】:

    标签: python numpy scipy


    【解决方案1】:

    您当前的方法存在一些问题。首先,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)
    

    【讨论】:

    • 我了解了关于使用 np.unique 的第二部分。但我不太确定我得到关于 np.bincount 的部分是 np.bincount(raveled) 的长度将大于唯一索引的数量。 " 你介意详细说明或举例说明吗?
    • 我在上面举了一个例子:np.bincount([1, 1, 3, 3, 3, 4]) 为您提供索引 0、1、2、3 和 4 的计数,而您只需要实际出现至少一次的索引的计数(即1、3 和 4)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-28
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多