2015-02-11 174 views
0

我有一个索引数组(可能重复),其中我在另一个二维矩阵中的每个这些索引增加1.有几个建议,并且这个answer建议使用np.ravel_multi_indexnumpy: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 

回答

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所要做的就是重复您的二进制数组中的部分 ,以使其与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) 
+0

我理解了关于使用np.unique的第二部分。但我不太确定,我得到的关于np.bincount的部分是np.bincount(raveled)的长度将大于唯一索引的数目。 “你介意详细说明还是陈述一个例子? – goh 2015-02-11 14:30:59

+0

我举了一个例子:'np.bincount([1,3,3,3,4])'给你指数为0,1,2,3和4,而你只希望实际发生的指数至少有一次(即1,3和4)。 – 2015-02-11 14:42:43