我试图使用多线程(和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