[英]Loading saved model (Bidirectional LSTM) in Keras
I trained and saved a Bidirectional LSTM model in Keras successfully with: 我成功通过以下方法在Keras中训练并保存了双向LSTM模型:
model = Sequential()
model.add(Bidirectional(LSTM(N_HIDDEN_NEURONS,
return_sequences=True,
activation="tanh",
input_shape=(SEGMENT_TIME_SIZE, N_FEATURES))))
model.add(Bidirectional(LSTM(N_HIDDEN_NEURONS)))
model.add(Dropout(0.5))
model.add(Dense(N_CLASSES, activation='sigmoid'))
model.compile('adam', 'binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train,
batch_size=BATCH_SIZE,
epochs=N_EPOCHS,
validation_data=[X_test, y_test])
model.save('model_keras/model.h5')
However, when I want to load it with: 但是,当我要加载它时:
model = load_model('model_keras/model.h5')
I get an error: 我收到一个错误:
ValueError: You are trying to load a weight file containing 3 layers into a model with 0 layers. ValueError:您正在尝试将包含3层的权重文件加载到具有0层的模型中。
I also tried different methods like saving and loading model architecture and weights separately but none of them worked for me. 我还尝试了不同的方法,例如分别保存和加载模型体系结构和权重,但是没有一个对我有用。 Also, previously, when I was using normal (unidirectional) LSTMs, loading the model worked fine. 另外,以前,当我使用普通的(单向)LSTM时,加载模型可以正常工作。
As mentioned by @mpariente and @today , the input_shape
is an argument of Bidirectional, not LSTM, see Keras documentation . 如@mpariente和@today所述, input_shape
是双向的参数,不是LSTM,请参阅Keras文档 。 My solution: 我的解决方案:
# Model
model = Sequential()
model.add(Bidirectional(LSTM(N_HIDDEN_NEURONS,
return_sequences=True,
activation="tanh"),
input_shape=(SEGMENT_TIME_SIZE, N_FEATURES)))
model.add(Bidirectional(LSTM(N_HIDDEN_NEURONS)))
model.add(Dropout(0.5))
model.add(Dense(N_CLASSES, activation='sigmoid'))
model.compile('adam', 'binary_crossentropy', metrics=['accuracy'])
model.fit(X_train, y_train,
batch_size=BATCH_SIZE,
epochs=N_EPOCHS,
validation_data=[X_test, y_test])
model.save('model_keras/model.h5')
and then, to load, simply do: 然后,要加载,只需执行以下操作:
model = load_model('model_keras/model.h5')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.