gpt4 book ai didi

python - 查找向量矩阵的最频繁行或模式 - Python/NumPy

转载 作者:太空狗 更新时间:2023-10-30 02:55:06 24 4
gpt4 key购买 nike

我有一个形状为 (?,n) 的 numpy 数组,表示一个 n 维向量的向量。

我想找到出现频率最高的行。

到目前为止,最好的方法似乎是遍历所有条目并存储一个计数,但 numpy 或 scipy 没有内置的东西来执行此任务似乎很可耻。

最佳答案

这是一种使用 NumPy views 的方法,它应该非常高效 -

def mode_rows(a):
a = np.ascontiguousarray(a)
void_dt = np.dtype((np.void, a.dtype.itemsize * np.prod(a.shape[1:])))
_,ids, count = np.unique(a.view(void_dt).ravel(), \
return_index=1,return_counts=1)
largest_count_id = ids[count.argmax()]
most_frequent_row = a[largest_count_id]
return most_frequent_row

sample 运行-

In [45]: # Let's have a random arrayb with three rows(2,4,8) and two rows(1,7)
...: # being duplicated. Thus, the most freequent row must be 2 here.
...: a = np.random.randint(0,9,(9,5))
...: a[4] = a[8]
...: a[2] = a[4]
...:
...: a[1] = a[7]
...:

In [46]: a
Out[46]:
array([[8, 8, 7, 0, 7],
[7, 8, 2, 6, 1],
[2, 2, 5, 7, 6],
[6, 5, 8, 8, 5],
[2, 2, 5, 7, 6],
[5, 7, 3, 6, 3],
[2, 8, 7, 2, 0],
[7, 8, 2, 6, 1],
[2, 2, 5, 7, 6]])

In [47]: mode_rows(a)
Out[47]: array([2, 2, 5, 7, 6])

关于python - 查找向量矩阵的最频繁行或模式 - Python/NumPy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43554819/

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