【问题标题】:Error during parallel computing of a function in Python 3.5, best approach?在 Python 3.5 中并行计算函数时出错,最好的方法是什么?
【发布时间】:2018-01-15 18:36:14
【问题描述】:

我有下一个从单独代码中调用的函数,我想使用多处理并行运行它:

def GridParallel(vec_main, vec_egf, vec_lp):

    VR_list = []
    Synthetics = []

    for i in vec_main:

        ''' 
        List with VR vectors for each iteration of egf values, the size of the list is 
        given by the len of vec_egf
        '''

        temp_VR = []
        temp_Synth = []

        for j in vec_egf:

            for k in vec_lp:

                synth = Synthetic(Frequency=frequency_vector, LongPeriod_amp=k, 
                                        Corner_egf=j , Corner_main=i, 
                                         gamma=gamma, fall_off=fall_off)


                VR = Variance_Reduction(data=data, model=synth)

                temp_VR.append(VR)
                temp_Synth.append(synth)


        VR_list.append(temp_VR)
        Synthetics.append(temp_Synth)


    VR_array = np.asarray(VR_list)
    VR_max_values = np.amax(VR_array, axis=1) 


    # Corner index
    corner_index = VR_max_values.argmax()
    #corner_index = np.nonzero(VR_max_values == np.max(VR_max_values))

    # Best corner frequency for the main event
    Corner_main_shock = float(vec_main[corner_index])

    # Variace reduction corresponding to the main event
    Best_fit = float(VR_max_values[corner_index])


    # Indexing for extracting spectral ratios in gridsearch
    VR_max_values_index = VR_array.argmax(axis=1)

    Synthetics = np.asarray(Synthetics)


    N_Synthetics = []
    rows, cols, lenn = Synthetics.shape

    temp = np.arange(0, rows, 1)

    for ii in temp:
        spec = Synthetics[ii, VR_max_values_index[ii]]
        N_Synthetics.append(spec)


    N_Synthetics = np.asarray(N_Synthetics)

    return N_Synthetics, VR_max_values, Corner_main_shock, Best_fit

但是,当我运行时:

pool = mp.Pool(processes=Ncores)

results = pool.apply_async(GridParallel, args=(vec_main, vec_egf, vec_lp, ))

pool.close()
results_ = results.get()
pool.join()

我得到下一个错误:

AttributeError: Can't pickle local object 'GridSearchCorner.<locals>.GridParallel'

输入变量:vec_* 都是 numpy ndarrays (1d)。

另外,如何从函数中恢复返回对象?

我正在尝试了解多处理,所以如果问题太简单,我提前道歉。任何帮助将不胜感激。为此,我正在研究 python 3.5。

谢谢!!

【问题讨论】:

标签: python python-3.x multiprocessing


【解决方案1】:

我已经使用 Numba 解决了这个难题。在我上面的脚本中,我调用函数 Synthetic 和 Variance_Reduction,这两个函数都是纯 numpy / math 函数。所以使用 @jit 装饰器可以让网格搜索变得非常快。例如,在@jit 之前,它需要大约 80 秒。为了完成任务,使用 @jit 将执行时间减少到 ~ 10 秒。

【讨论】:

    猜你喜欢
    • 2020-04-11
    • 1970-01-01
    • 1970-01-01
    • 2020-11-20
    • 1970-01-01
    • 2013-01-23
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多