在预测多线程时的keras错误



我正在尝试创建四个线程(每个线程都有自己的图和模型(,这些线程将同意并以相同的方式发布预测。

我的线程代码类似:

        thread_locker.acquire()
        thread_graph = Graph()
        with thread_graph.as_default():
            thread_session = Session()
            with thread_session.as_default():
                #Model Training
                if (once_flag_raised == False):
                    try:
                        model = load_model('ten_step_forward_'+ timeframe +'.h5')
                    except OSError:
                        input_layer = Input(shape=(X_train.shape[1], 17,))
                        lstm = Bidirectional(
                            LSTM(250),
                            merge_mode='concat')(input_layer)
                        pred = Dense(10)(lstm)
                        model = Model(inputs=input_layer, outputs=pred)
                        model.compile(optimizer='adam', loss='mean_squared_error')
                    once_flag_raised = True
                model.fit(X_train, y_train, epochs=10, batch_size=128)
                thread_locker.acquire()
                nn_info_dict['model'] = model
                nn_info_dict['sc'] = sc
                model.save('ten_step_forward_'+ timeframe +'.h5')
                thread_locker.release()
        thread_locker.release()
        (....)
            thread_locker.acquire()
            thread_graph = Graph()
            with thread_graph.as_default():
                thread_session = Session()
                with thread_session.as_default():
                    pred_data= model.predict(X_pred)
            thread_locker.release()

在每个线程上。

当我阅读代码的预测部分时,我会继续遇到以下错误(线程-1次(:

ValueError: Tensor Tensor("dense_1/BiasAdd:0", shape=(?, 10), dtype=float32) is not an element of this graph.

我的理解是,其中一个线程"声明" TensorFlow后端及其默认图和会话。

有什么方法可以解决?

我弄清楚了我在做什么错。我的想法是对的,但我不应该重新创建下面的图表和会话。代码的底部应该简单地为:

    thread_locker.acquire()
    with thread_graph.as_default():
        with thread_session.as_default():
            pred_data= model.predict(X_pred)
    thread_locker.release()

最新更新