繁体   English   中英

Python中的并行计算类似于MATLAB

[英]Parallel computing in Python Similar to MATLAB

很长一段时间以来,我一直在 MATLAB 中使用 parfor 来并行运行 for 循环。 我需要在 Python 中做类似的事情,但我找不到任何简单的解决方案。 这是我的代码:

t = list(range(1,3,1))
G = list(range(0,3,2))
results = pandas.DataFrame(columns = ['tau', 'p_value','G','t_i'],index=range(0,len(G)*len(t)))
counter = 0  
for iteration_G in list(range(0,len(G))):
    for iteration_t in list(range(0,len(t))):
        
        matrix_1,matrix_2 = bunch of code


        tau, p_value = scipy.stats.kendalltau(matrix_1, matrix_2)
        results['tau'][counter] = tau
        results['p_value'][counter] = p_value
        results['G'][counter] = G[iteration_G]
        results['t_i'][counter] = G[iteration_t]
        counter = counter + 1

我想在第一个循环中使用 parfor 等效项。

我不熟悉parfor ,但您可以使用 joblib 包并行运行函数。

在这个简单的示例中,有一个打印其参数的函数,我们使用Parallel与 for 循环并行执行它多次

import multiprocessing
from joblib import Parallel, delayed


# function that you want to run in parallel
def foo(i):
    print(i)


# define the number of cores (this is how many processes wil run)
num_cores = multiprocessing.cpu_count()

# execute the function in parallel - `return_list` is a list of the results of the function
# in this case it will just be a list of None's
return_list = Parallel(n_jobs=num_cores)(delayed(foo)(i) for i in range(20))

如果这不适合您想要做的事情,您可以尝试使用numba - 设置可能有点困难,但理论上使用 numba 您可以添加@njit(parallel=True)作为装饰器到您的功能和 numba 将尝试为您并行化它。

我找到了使用parfor的解决方案。 它仍然比 MATLAB 的 parfor 复杂一点,但它非常接近我的习惯。

t = list(range(1,16,1))
G = list(range(0,62,2))
for iteration_t in list(range(0,len(t))):
    @parfor(list(range(0,len(G))))
    def fun(iteration_G):
        result = pandas.DataFrame(columns = ['tau', 'p_value'],index=range(0,1))

        matrix_1,matrix_2 = bunch of code   



        tau, p_value = scipy.stats.kendalltau(matrix_1, matrix_2)     
        result['tau'] = tau
        result['p_value'] = p_value
        fun = numpy.array([tau,p_value])
        return fun

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM