gpt4 book ai didi

python - 如何拆分 numpy 数组并对拆分数组执行某些操作 [Python]

转载 作者:太空狗 更新时间:2023-10-30 01:05:49 25 4
gpt4 key购买 nike

这个问题之前只问过一部分([1] [2]),解释了如何拆分numpy数组。我是 Python 的新手。我有一个包含 262144 个项目的数组,想将它拆分成长度为 512 的小数组,分别对它们进行排序并总结它们的前五个值,但我不确定如何超出这一行:

np.array_split(vector, 512)

如何调用和分析每个数组?继续使用 numpy 数组是个好主意,还是我应该恢复并改用字典?

最佳答案

这样的拆分不是一个有效的解决方案,相反我们可以 reshape ,这有效地将子数组创建为 2D 数组的行。这些将是输入数组的 View ,因此不需要额外的内存。然后,我们将获取 argsort 索引并在每行中选择前五个索引,最后将它们相加以获得所需的输出。

因此,我们会有这样的实现 -

N = 512 # Number of elements in each split array
M = 5 # Number of elements in each subarray for sorting and summing

b = a.reshape(-1,N)
out = b[np.arange(b.shape[0])[:,None], b.argsort(1)[:,:M]].sum(1)

逐步示例运行 -

In [217]: a   # Input array
Out[217]: array([45, 19, 71, 53, 20, 33, 31, 20, 41, 19, 38, 31, 86, 34])

In [218]: N = 7 # 512 for original case, 7 for sample

In [219]: M = 5

# Reshape into M rows 2D array
In [220]: b = a.reshape(-1,N)

In [224]: b
Out[224]:
array([[45, 19, 71, 53, 20, 33, 31],
[20, 41, 19, 38, 31, 86, 34]])

# Get argsort indices per row
In [225]: b.argsort(1)
Out[225]:
array([[1, 4, 6, 5, 0, 3, 2],
[2, 0, 4, 6, 3, 1, 5]])

# Select first M ones
In [226]: b.argsort(1)[:,:M]
Out[226]:
array([[1, 4, 6, 5, 0],
[2, 0, 4, 6, 3]])

# Use fancy-indexing to select those M ones per row
In [227]: b[np.arange(b.shape[0])[:,None], b.argsort(1)[:,:M]]
Out[227]:
array([[19, 20, 31, 33, 45],
[19, 20, 31, 34, 38]])

# Finally sum along each row
In [228]: b[np.arange(b.shape[0])[:,None], b.argsort(1)[:,:M]].sum(1)
Out[228]: array([148, 142])

使用 np.argpartition 提升性能-

out = b[np.arange(b.shape[0])[:,None], np.argpartition(b,M,axis=1)[:,:M]].sum(1)

运行时测试-

In [236]: a = np.random.randint(11,99,(512*512))

In [237]: N = 512

In [238]: M = 5

In [239]: b = a.reshape(-1,N)

In [240]: %timeit b[np.arange(b.shape[0])[:,None], b.argsort(1)[:,:M]].sum(1)
100 loops, best of 3: 14.2 ms per loop

In [241]: %timeit b[np.arange(b.shape[0])[:,None], \
np.argpartition(b,M,axis=1)[:,:M]].sum(1)
100 loops, best of 3: 3.57 ms per loop

关于python - 如何拆分 numpy 数组并对拆分数组执行某些操作 [Python],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41920367/

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