如何在 Keras RNN 中实时实现前向传递?
How to implement a forward pass in a Keras RNN in real-time?
我正在尝试 运行 在 运行 的实时应用程序中使用 Keras 训练的 RNN。循环网络(它是一个 LSTM)中的 "time" 是接收数据的实际时刻。
我想以在线方式获取 RNN 的输出。对于非循环模型,我只是将我的输入整形为 inputDatum=1,input_shape
和 运行 Model.predict
的形状。我不确定这是在 Keras 中为应用程序使用前向传递的预期方法,但它对我有用。
但对于循环模块,Model.predict
期望将整个输入作为输入,包括时间维度。所以它不起作用...
有没有办法在 Keras 中执行此操作,还是我需要转到 Tensorflow 并在那里执行操作?
您可以将 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)
然后,可以将权重加载到另一个具有stateful=True
的模型上进行预测(记得在Input
层中设置batch_shape
)。
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())
对于您的用例,由于 predict_model
是有状态的,因此对长度为 1 sub-sequences 的连续 predict
调用将给出与预测整个序列相同的结果。请记住在预测新序列之前调用 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]]
我正在尝试 运行 在 运行 的实时应用程序中使用 Keras 训练的 RNN。循环网络(它是一个 LSTM)中的 "time" 是接收数据的实际时刻。
我想以在线方式获取 RNN 的输出。对于非循环模型,我只是将我的输入整形为 inputDatum=1,input_shape
和 运行 Model.predict
的形状。我不确定这是在 Keras 中为应用程序使用前向传递的预期方法,但它对我有用。
但对于循环模块,Model.predict
期望将整个输入作为输入,包括时间维度。所以它不起作用...
有没有办法在 Keras 中执行此操作,还是我需要转到 Tensorflow 并在那里执行操作?
您可以将 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)
然后,可以将权重加载到另一个具有stateful=True
的模型上进行预测(记得在Input
层中设置batch_shape
)。
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())
对于您的用例,由于 predict_model
是有状态的,因此对长度为 1 sub-sequences 的连续 predict
调用将给出与预测整个序列相同的结果。请记住在预测新序列之前调用 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]]