我知道这是一个老问题,但希望这个答案可以帮助像我这样的其他 Keras 初学者。
我在我的机器上运行这个例子,观察到 LSTM 的隐藏状态和单元状态确实随着调用而改变model.predict
.
import numpy as np
import keras.backend as K
from keras.models import Model
from keras.layers import LSTM
batch_size = 1
timestep_size = 2
num_features = 4
inputs = Input(batch_shape=(batch_size, timestep_size, num_features)
x = LSTM(num_features, stateful=True)(inputs)
model = Model(inputs=inputs, outputs=x)
model.compile(loss="mse",
optimizer="rmsprop",
metrics=["accuracy"])
x = np.random.randint((10,2,4))
y = np.ones((10,4))
model.fit(x,y, epochs=100, batch_size=1)
def get_internal_state(model):
# get the internal state of the LSTM
# see https://github.com/fchollet/keras/issues/218
h, c = [K.get_value(s) for s, _ in model.state_updates]
return h, c
print "After fitting:", get_internal_state(model)
for i in range(3):
x = np.random.randint((10,2,4))
model.predict(x)
print "After predict:", get_internal_state(model)
以下是调用的输出示例get_internal_state
训练结束后:
After_fitting: (array([[ 1., 1., 1., 1.]], dtype=float32), array([[ 11.33725166, 11.8036108 , 181.75688171, 25.50110626]], dtype=float32))
After predict (array([[ 1. , 0.99999994, 1. , 1. ]], dtype=float32), array([[ 9.26870918, 8.83847237, 179.92633057, 28.89341927]], dtype=float32))
After predict (array([[ 0.99999571, 0.9992013 , 1. , 0.9915328 ]], dtype=float32), array([[ 6.5174489 , 8.55165958, 171.42166138, 25.49199104]], dtype=float32))
After predict (array([[ 1., 1., 1., 1.]], dtype=float32), array([[ 9.78496075, 9.27927303, 169.95401001, 28.74017715]], dtype=float32))