gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:19:08 25 4
gpt4 key购买 nike

Mn 分别为 d x dd 维 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)]

关于python - 快速计算矩阵元素的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35244858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com