【问题标题】:How to accelerate the application of the following for loop and function?如何加速以下for循环和函数的应用?
【发布时间】:2019-10-02 04:00:48
【问题描述】:

我有以下 for 循环:

for j in range(len(list_list_int)):
    arr_1_, arr_2_, arr_3_ = foo(bar, list_of_ints[j])
    arr_1[j,:] = arr_1_.data.numpy()
    arr_2[j,:] = arr_2_.data.numpy()
    arr_3[j,:] = arr_3_.data.numpy()

我想用多处理申请foo,主要是因为它需要很长时间才能完成。我尝试用funcy's chunks 方法分批做:

for j in chunks(1000, list_list_int):
    arr_1_, arr_2_, arr_3_ = foo(bar, list_of_ints[j])
    arr_1[j,:] = arr_1_.data.numpy()
    arr_2[j,:] = arr_2_.data.numpy()
    arr_3[j,:] = arr_3_.data.numpy()

但是,我收到了list object cannot be interpreted as an integer。使用多处理应用 foo 的正确方法是什么?

【问题讨论】:

  • 根据文档和我自己的测试,您所称的方式 应该 工作。不知道为什么不这样做,但您可以尝试明确指定一个步骤(如果您想要默认行为,该步骤应该与第一个参数具有相同的值)。
  • 是否有其他方法可以应用该功能? @马克
  • 来自for j in chunks(1000, list_list_int):j不是整数,是list_list_int的子列表,所以,你需要再次迭代ji.stack.imgur.com/JXDmZ.png
  • 感谢@KingStone 的帮助,你能举个例子吗?
  • 我用代码屏幕更新了我的评论。但是,块不能提高速度。 stackoverflow.com/questions/11515944 怎么样

标签: python-3.x numpy iteration batch-processing funcy


【解决方案1】:
list_list_int = [1,2,3,4,5,6]
for j in chunks(2, list_list_int):
  for i in j:
    avg_, max_, last_ = foo(bar, i)

【讨论】:

  • 还是一样,类型错误列表索引必须是整数而不是切片。谢谢!
  • 请分享list_list_int?
  • 两者都一样我只是改了名字
  • list_of_ints 是一个嵌套的整数列表
  • list_of_ints 看起来像这样:[[1,2],[3,4],[5,6]]
【解决方案2】:

如果您希望在 numpy 数组上执行并行操作,那么我会使用 Dask

只需几行代码,您的操作应该能够轻松地在多个进程上运行,高度开发的 Dask 调度程序将为您平衡负载。与其他并行库(如 joblib)相比,Dask 的一个巨大优势在于它维护了原生 numpy API。

import dask.array as da

# Setting up a random array with dimensions 10K rows and 10 columns
# This data is stored distributed across 10 chunks, and the columns are kept together (1_000, 10)
x = da.random.random((10_000, 10), chunks=(1_000, 10))
x = x.persist()  # Allow the entire array to persist in memory to speed up calculation


def foo(x):
    return x / 10


# Using the native numpy function, apply_along_axis, applying foo to each row in the matrix in parallel
result_foo = da.apply_along_axis(foo, 0, x)

# View original contents
x[0:10].compute()

# View sample of results
result_foo = result_foo.compute()
result_foo[0:10]

【讨论】:

    【解决方案3】:

    我没有安装chunks,但从我怀疑它生成的文档中(对于大小为 2 的块,来自:

    alist = [[1,2],[3,4],[5,6],[7,8]]                                     
    j = [[1,2],[3,4]]
    j = [[5,6],[7,8]]   
    

    会产生错误:

    In [116]: alist[j]                                                              
    TypeError: list indices must be integers or slices, not list
    

    如果您的foo 无法处理完整的列表列表,我看不出它将如何处理拆分为块的列表。显然它一次只能处理一个子列表。

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 1970-01-01
      • 1970-01-01
      • 2022-01-15
      • 2015-05-27
      • 2021-09-03
      • 1970-01-01
      • 2020-02-28
      • 2011-09-22
      相关资源
      最近更新 更多