我试图在实时运行的应用程序中运行一个在Keras中受过训练的RNN。在递归网络中的“时间”(它是一个LSTM)这里是数据被接收时的实际时刻。
我想以一种在线的方式获得RNN的输出。对于非递归模型,我只是将我的输入输入到形状inputDatum=1,input_shape
中,并在其上运行Model.predict
。我不确定这是为应用程序在Keras中使用前向传递的预期方法,但它对我起了作用。
但对于递归模块,Model.predict
期望输入整个输入,包括时间维度。所以这不管用..。
在Keras中有什么方法可以这样做吗?还是我需要深入到Tensorflow并在那里实现操作?
发布于 2018-03-16 10:09:17
您可以将LSTM
层设置为有状态的。在手动调用model.reset_states()
之前,将保持LSTM的内部状态。
例如,假设我们已经训练了一个简单的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
是有状态的,对length-1子序列的连续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]]
https://stackoverflow.com/questions/49324093
复制