Skip to main content
 首页 » 编程设计

python之快速计算矩阵元素的出现次数

2024年10月24日13Terrylee

令 M 和 n 分别为 d x d 和 d 维 numpy 整数数组。我想计算 (n(i), n(j), M(i,j)) 形式的三元组的数量。因此,我想要一个 numpy 数组,这样每个条目都会计算这样一个三元组的出现次数。

编辑 M 是对称的,我不想计算 i=j 的三元组。

我目前正在使用 itertools.product(用于遍历所有对)和 numpy.bincount 来执行此操作,但它太慢了。有没有更聪明的方法,可能是使用 numpy?

请您参考如下方法:

由于数组包含整数,您可以将每个三元组视为可线性索引的元素。这是一种考虑到该哲学的方法,因此避免了循环,就像这样-

# Form n(i) x n(j) array and then append with "columnar" M(i,j) array 
nn_arr = n[np.array(list(itertools.product(range(5), repeat=2)))] 
 
nn_M_arr = np.concatenate((nn_arr,M.reshape(-1,1)),axis=1) 
 
# Get linear indices version 
dims = nn_M_arr.max(0)+1 
lidx = np.ravel_multi_index(nn_M_arr.T,dims) 
 
# Get unique indices and the counts 
_, idx, counts = np.unique(lidx,return_index=True,return_counts=True) 
 
# Get corresponding unique triplets using unique indices and zip with counts 
out = zip(map(tuple,nn_M_arr[idx]),counts) 

sample 运行-

In [206]: M 
Out[206]:  
array([[1, 0, 0, 2, 0], 
       [1, 1, 2, 0, 2], 
       [0, 0, 2, 0, 1], 
       [2, 1, 2, 0, 2], 
       [1, 1, 1, 1, 0]]) 
 
In [207]: n 
Out[207]: array([0, 1, 1, 1, 2]) 
 
In [208]: out 
Out[208]:  
[((0, 0, 1), 1), 
 ((0, 1, 0), 2), 
 ((0, 1, 2), 1), 
 ((0, 2, 0), 1), 
 ((1, 0, 0), 1), 
 ((1, 0, 1), 1), 
 ((1, 0, 2), 1), 
 ((1, 1, 0), 4), 
 ((1, 1, 1), 2), 
 ((1, 1, 2), 3), 
 ((1, 2, 1), 1), 
 ((1, 2, 2), 2), 
 ((2, 0, 1), 1), 
 ((2, 1, 1), 3), 
 ((2, 2, 0), 1)]