多线程预测时的Keras错误

2024-05-23 20:13:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试创建四个线程(每个线程都有自己的图和模型),它们将同时运行并以相同的方式发布预测。在

我的线程代码类似于:

        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次):

^{pr2}$

我的理解是其中一个线程“声明”了Tensorflow后端及其默认的图形和会话。在

有没有办法解决这个问题?在


Tags: layerdefaultinputreleasemodelsessionaswith
1条回答
网友
1楼 · 发布于 2024-05-23 20:13:19

我已经知道我做错了什么。 我的想法是正确的,但我不应该重新创建下面的图表和会话。 代码的底部应该是:

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

相关问题 更多 >