如何并行化循环

在图像处理中,我们经常将相同的算法应用于大批量的图像。在本段中,我们建议使用 joblib 使循环并行化。以下是此类重复性任务的一个例子:

from skimage import data, color, util
from skimage.restoration import denoise_tv_chambolle
from skimage.feature import hog

def task(image):
    """
    Apply some functions and return an image.
    """
    image = denoise_tv_chambolle(image[0][0], weight=0.1, multichannel=True)
    fd, hog_image = hog(color.rgb2gray(image), orientations=8,
                        pixels_per_cell=(16, 16), cells_per_block=(1, 1),
                        visualize=True)
    return hog_image


# Prepare images
hubble = data.hubble_deep_field()
width = 10
pics = util.view_as_windows(hubble, (width, hubble.shape[1], hubble.shape[2]), step=width)

调用该函数 task 在列表的每个元素上 pics ,通常会编写一个for循环。要测量此循环的执行时间,可以使用IPython,并使用 %timeit

def classic_loop():
    for image in pics:
        task(image)


%timeit classic_loop()

编写此循环的另一种等价方法是使用具有相同效率的理解列表。

def comprehension_loop():
    [task(image) for image in pics]

%timeit comprehension_loop()

joblib 是一个库,一旦我们有了理解列表,它就提供了一种简单的方法来并行化for循环。可以指定作业数。

from joblib import Parallel, delayed
def joblib_loop():
    Parallel(n_jobs=4)(delayed(task)(i) for i in pics)

%timeit joblib_loop()