簡體   English   中英

為什么keras model不能在python的多進程池中運行?

[英]why keras model can't run in multiprocess pool in python?

我想通過使用 model 來預測值我使用這個代碼

from keras.models import load_model
import multiprocessing
model = load_model('CNN_MODEL.hdf')
def Net(x):
    print("test")
    return model.predict(x)

X_test=.....(a list )
pool=multiprocessing.Pool(processes=12)
Y=pool.map(Net,X_test)

pool.close()
pool.join()

但是太慢了。 出處是

測試測試測試... 測試 12 次測試,然后卡住。 我的cpu是36核的。 如何解決?

環顧四周,我發現了這個可能相關的答案,表明 Keras 只能在一個過程中使用: 將多處理與 theano 一起使用

有沒有辦法實現我的目標? 非常感謝高級描述或簡短示例。

Note: I've attempted approaches along the lines of passing a graph to the process but failed since it seems tensorflow graphs aren't pickable (related SO post for that here: Tensorflow: Passing a session to a python multiproces s). 如果確實有辦法將 tensorflow 圖形/模型傳遞給子進程,那么我也對此持開放態度。

根據我的經驗 - 問題在於將 Keras 加載到一個進程,然后在 keras 加載到您的主環境時生成一個新進程。 但對於某些應用程序(例如訓練混合 Keras 模型),最好將所有這些東西放在一個進程中。 所以我建議的是以下(有點麻煩 - 但對我有用)方法:

不要將 KERAS 加載到您的主要環境中。 如果你想加載 Keras / Theano / TensorFlow 只能在 function 環境中進行。 例如,不要這樣做:

import keras

def training_function(...):
    ...

but do the following:

def training_function(...):
    import keras
    ...

在單獨的進程中運行與每個 model 相關的工作:我通常創建正在完成工作的工人(例如培訓、調整、評分),並且我在單獨的進程中運行它們。 當您的過程完成時,該過程使用的整個 memory 完全釋放,這有什么好處。 這可以幫助您解決在使用多處理甚至在一個進程中運行多個模型時通常會遇到的大量 memory 問題。 所以這看起來像這樣:

def _training_worker(train_params):
    import keras
    model = obtain_model(train_params)
    model.fit(train_params)
    send_message_to_main_process(...)

def train_new_model(train_params):
    training_process = multiprocessing.Process(target=_training_worker, args = train_params)
    training_process.start()
    get_message_from_training_process(...)
    training_process.join()

不同的方法只是為不同的 model 動作准備不同的腳本。 但這可能會導致 memory 錯誤,尤其是當您的模型正在消耗 memory 時。 請注意,由於這個原因,最好嚴格按順序執行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM