我試圖使用多線程(和tensorflow
後端)來訓練多個具有不同參數值的keras
模型。我已經看到了在多個線程中使用相同模型的幾個例子,但在這種特殊情況下,我遇到了有關圖形衝突的各種錯誤等。下面是我想要做的一個簡單示例:TensorFlow/Keras多線程模型擬合
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import tensorflow as tf
from keras import backend as K
from keras.layers import Dense
from keras.models import Sequential
sess = tf.Session()
def example_model(size):
model = Sequential()
model.add(Dense(size, input_shape=(5,)))
model.add(Dense(1))
model.compile(optimizer='sgd', loss='mse')
return model
if __name__ == '__main__':
K.set_session(sess)
X = np.random.random((10, 5))
y = np.random.random((10, 1))
models = [example_model(i) for i in range(5, 10)]
e = ThreadPoolExecutor(4)
res_list = [e.submit(model.fit, X, y) for model in models]
for res in res_list:
print(res.result())
由此產生的錯誤是ValueError: Tensor("Variable:0", shape=(5, 5), dtype=float32_ref) must be from the same graph as Tensor("Variable_2/read:0", shape=(), dtype=float32).
。我也嘗試在線程內初始化模型,這給出了類似的失敗。
對此有何想法?我完全沒有關注這個確切的結構,但我更喜歡能夠使用多個線程而不是進程,因此所有模型都在相同的GPU內存分配內進行訓練。
這解決了我的問題,我有兩個模型在一個進程中運行,它總是給我ValueError異常:取參數不能被解釋爲張量。 (張量張量(「輸入:0」,shape =(2,2),dtype = float32_ref)不是該圖的元素。) – forqzy