11.2. 如何平行化迴圈#
在影像處理中,我們經常對一大批影像應用相同的演算法。在這段文字中,我們建議使用 joblib 來平行化迴圈。以下是一個重複性任務的範例
import skimage as ski
def task(image):
"""
Apply some functions and return an image.
"""
image = ski.restoration.denoise_tv_chambolle(
image[0][0], weight=0.1, channel_axis=-1
)
fd, hog_image = ski.feature.hog(
ski.color.rgb2gray(image),
orientations=8,
pixels_per_cell=(16, 16),
cells_per_block=(1, 1),
visualize=True
)
return hog_image
# Prepare images
hubble = ski.data.hubble_deep_field()
width = 10
pics = ski.util.view_as_windows(
hubble, (width, hubble.shape[1], hubble.shape[2]), step=width
)
要對列表 pics
中的每個元素呼叫函式 task
,通常會寫一個 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()