如何在 Keras RNN 中实时实现前向传播?

psa*_*awa 5 keras tensorflow recurrent-neural-network

我正在尝试在实时运行的应用程序中运行在 Keras 中训练的 RNN。这里循环网络(LSTM)中的“时间”是接收数据时的实际时刻。

我想以在线方式获取 RNN 的输出。对于非循环模型,我只是将输入塑造成形状inputDatum=1,input_shapeModel.predict在其上运行。我不确定这是否是在 Keras 中为应用程序使用前向传递的预期方法,但它对我有用。

但对于循环模块,Model.predict期望整个输入作为输入,包括时间维度。所以它不起作用...

有没有办法在 Keras 中执行此操作,或者我是否需要转到 Tensorflow 并在那里实现操作?

Yu-*_*ang 5

您可以将LSTM图层设置为有状态。LSTM 的内部状态将一直保留,直到您model.reset_states()手动调用。

例如,假设我们训练了一个简单的 LSTM 模型。

x = Input(shape=(None, 10))
h = LSTM(8)(x)
out = Dense(4)(h)
model = Model(x, out)
model.compile(loss='mse', optimizer='adam')

X_train = np.random.rand(100, 5, 10)
y_train = np.random.rand(100, 4)
model.fit(X_train, y_train)
Run Code Online (Sandbox Code Playgroud)

然后,可以将权重加载到另一个模型上进行预测(记住要在层中stateful=True设置)。batch_shapeInput

x = Input(batch_shape=(1, None, 10))
h = LSTM(8, stateful=True)(x)
out = Dense(4)(h)
predict_model = Model(x, out)

# copy the weights from `model` to this model
predict_model.set_weights(model.get_weights())
Run Code Online (Sandbox Code Playgroud)

对于您的用例,由于predict_model是有状态的,因此predict对长度为 1 的子序列的连续调用将给出与预测整个序列相同的结果。reset_states()只需记住在预测新序列之前调用即可。

X = np.random.rand(1, 3, 10)
print(model.predict(X))
# [[-0.09485822,  0.03324107,  0.243945  , -0.20729265]]

predict_model.reset_states()
for t in range(3):
    print(predict_model.predict(X[:, t:(t + 1), :]))
# [[-0.04117237 -0.06340873  0.10212967 -0.06400848]]
# [[-0.12808001  0.0039286   0.23223262 -0.23842749]]
# [[-0.09485822  0.03324107  0.243945   -0.20729265]]
Run Code Online (Sandbox Code Playgroud)