python - 如何加速 Numpy 数组过滤/选择?

标签 python performance numpy parallel-processing multiprocessing

我有大约 40k 行,我想测试这些行上的各种选择组合。通过选择,我的意思是 bool 掩码。 mask /滤光片数量在250MM左右。

当前的简化代码:

np_arr = np.random.randint(1, 40000, 40000)
results = np.empty(250000000)
filters = np.random.randint(1, size=(250000000, 40000))
for i in range(250000000):
    row_selection = np_arr[filters[i].astype(np.bool_)] # Select rows based on next filter
    # Performing simple calculations such as sum, prod, count on selected rows and saving to result
    results[i] = row_selection.sum() # Save simple calculation result to results array

我尝试了 Numba 和 Multiprocessing,但由于大部分处理是在过滤器选择而不是计算中进行的,所以这并没有太大帮助。

解决这个问题的最有效方法是什么?有什么办法可以并行化吗?据我所知,我需要遍历每个过滤器,然后分别计算总和、产品、计数等,因为我不能并行应用过滤器(即使应用过滤器后的计算非常简单)。

感谢有关性能改进/加速的任何建议。

最佳答案

要在 Numba 中获得良好的性能,只需避免屏蔽并因此避免非常昂贵的数组副本。您必须自己实现过滤器,但是您提到的过滤器应该没有任何问题。

并行化也很容易做到。

示例

import numpy as np
import numba as nb

max_num = 250000 #250000000
max_num2 = 4000#40000
np_arr = np.random.randint(1, max_num2, max_num2)
filters = np.random.randint(low=0,high=2, size=(max_num, max_num2)).astype(np.bool_)

#Implement your functions like this, avoid masking
#Sum Filter
@nb.njit(fastmath=True)
def sum_filter(filter,arr):
  sum=0.
  for i in range(filter.shape[0]):
    if filter[i]==True:
      sum+=arr[i]
  return sum

#Implement your functions like this, avoid masking
#Prod Filter
@nb.njit(fastmath=True)
def prod_filter(filter,arr):
  prod=1.
  for i in range(filter.shape[0]):
    if filter[i]==True:
      prod*=arr[i]
  return sum

@nb.njit(parallel=True)
def main_func(np_arr,filters):
  results = np.empty(filters.shape[0])
  for i in nb.prange(max_num):
    results[i]=sum_filter(filters[i],np_arr)
    #results[i]=prod_filter(filters[i],np_arr)
  return results

关于python - 如何加速 Numpy 数组过滤/选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53434568/

相关文章:

python - PyCharm 中 numpy 的问题

python - 如何找到被分水岭分割的区域的中心点?

python-3.x - 进行 FFT 的最快方法

python标签不实时更新

python - ctypes - 从 C++ 函数获取输出到 Python 对象

c++ - 分支预测 vs 分支目标预测

performance - Haproxy SNI 与 HTTP 主机 ACL 检查性能

python - 向随机游走图添加动画 [Python]

python - 如何在Python中拥有数组的数组

sql-server-2005 - SQL Server 2005阻止问题(ASYNC_NETWORK_IO)