python | concurrent.futures模塊提升數據處理速度
阿新 • • 發佈:2018-10-08
希望 數據預處理 exec resize 參考 margin 情況 neu folder
在默認情況下,Python 程序是單個進程,使用單 CPU 核心執行。致使多核設備無法利用而算力浪費。通過使用 Python 的 concurrent.futures 模塊,可以讓一個普通的程序轉換成適用於多核處理器並行處理的程序,進而提升數據預處理的效率。
簡單例子,在單個文件夾中有一個圖片數據集,其中有數萬張圖片。在這裏,我們決定使用 1000 張。我們希望在所有圖片被傳遞到深度神經網絡之前將其調整為 600×600 像素分辨率的形式。
案例:
標準方法
import glob import os import cv2 ### Loop through all jpg files in the current folder ### Resize each one to size 600x600 for image_filename in glob.glob("*.jpg"): ### Read in the image data流程: 1. 首先從需要處理內容的文件(或其他數據)列表開始。 2. 使用 for 循環逐個處理每個數據,然後在每個循環叠代上運行預處理。
img = cv2.imread(image_filename)### Resize the image img = cv2.resize(img, (600, 600))
更快的方法
流程: 1.將 jpeg 文件列表分成 4 個小組; 2.運行 Python 解釋器中的 4 個獨立實例; 3.讓 Python 的每個實例處理 4 個數據小組中的一個; 4.結合四個處理過程得到的結果得出最終結果列表。import glob import os import cv2 import concurrent.futuresdef load_and_resize(image_filename): ### Read in the image data img = cv2.imread(image_filename) ### Resize the image img = cv2.resize(img, (600, 600)) ### Create a pool of processes. By default, one is created for each CPU in your machine. with concurrent.futures.ProcessPoolExecutor() as executor: ### Get a list of files to process image_files = glob.glob("*.jpg") ### Process the list of files, but split the work across the process pool to use all CPUs ### Loop through all jpg files in the current folder ### Resize each one to size 600x600 executor.map(load_and_resize, image_files)
「executor.map()」將你想要運行的函數和列表作為輸入,列表中的每個元素都是我們函數的單個輸入。
但是該方法並不適用於對處理後的結果有特殊順序要求。 參考: https://towardsdatascience.com/heres-how-you-can-get-a-2-6x-speed-up-on-your-data-pre-processing-with-python-847887e63be5python | concurrent.futures模塊提升數據處理速度