【问题标题】:multiprocessing pool.map on a function inside other function多处理 pool.map 在其他函数内的函数上
【发布时间】:2019-05-18 06:30:03
【问题描述】:

假设我有一个函数可以为相同的输入提供不同的结果,并且需要对相同的输入执行多次以获得平均值(我会画一个简单的例子,但实际上随机性的来源是train_test_split来自sklearn.model_selection,如果这很重要)

define f(a,b):
    output=[]
    for i in range(0,b):
        output[i] = np.mean(np.random.rand(a,))
    return np.mean(output)

这个函数的参数是在另一个函数中定义的(同样,一个简单的例子,如果这些不是高效的/pythonistic,请不要介意):

define g(c,d):
    a = c
    b = c*d
    result=f(a,b)
    return(result)

我想使用multiprocessing 来加快执行时间,而不是使用for 循环。我发现pool.applypool.startmap 都不能解决问题(执行时间增加),只有pool.map 有效。但是,它只能接受一个参数(在这种情况下 - 迭代次数)。我尝试重新定义f 如下:

define f(number_of_iterations):
    output=np.mean(np.random.rand(a,))
    return output

然后使用pool.map如下:

import multiprocessing as mp
define g(c,d):
    temp=[]
    a = c
    b = c*d
    pool = mp.Pool(mp.cpu_count())
    temp = pool.map(f, [number_of_iterations for number_of_iterations in b])
    pool.close()
    result=np.mean(temp)
    return(result)

基本上,使f 成为单参数函数的复杂解决方法。希望f 仍会选择参数a,但是,执行g 会导致关于a 未定义的错误。

有没有办法让 pool.map 在这种情况下工作?

【问题讨论】:

    标签: python python-3.x multiprocessing


    【解决方案1】:

    我认为functool.partial 可以解决您的问题。这是一个实现:https://stackoverflow.com/a/25553970/9177173 这里是文档:https://docs.python.org/3.7/library/functools.html#functools.partial

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-18
      • 2015-08-25
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 2018-04-03
      • 1970-01-01
      相关资源
      最近更新 更多