无法从.keras文件加载双向LSTM模型

问题描述 投票:0回答:1

这是我第一次使用tensorflow和keras,并且在保存和加载模型时遇到问题。我发现它特别与双向 LSTM 层有关,但不知道从那里该做什么。

这是我的代码:

model = Sequential()

model.add(Bidirectional(LSTM(128, activation='tanh'))) ### problem line
model.add(Dropout(0.2))
model.add(BatchNormalization())

model.add(Flatten())
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))

model.add(Dense(1, activation='sigmoid'))


optimizer = Adam(learning_rate=0.001)
model.compile(loss='binary_crossentropy', optimizer=optimizer, metrics=['accuracy'])

early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=1)

model.fit(X_train_scaled, y_train, batch_size=32, epochs=3, validation_data=(X_test_scaled, y_test), callbacks=[early_stopping, reduce_lr])
model.summary()

model.save('models/sample_model.keras')
model = load_model('models/sample_model.keras')

加载模型会产生此错误:

ValueError: A total of 1 objects could not be loaded. Example error message for object <LSTMCell name=lstm_cell, built=True>:

Layer 'lstm_cell' expected 3 variables, but received 0 variables during loading. Expected: ['kernel', 'recurrent_kernel', 'bias']

List of objects that could not be loaded:
[<LSTMCell name=lstm_cell, built=True>]

我尝试将 input_shape 添加到双向参数中,但出现了相同的错误。我还尝试保存为 .h5 文件而不是 .keras,但没有成功。我查看了 keras 文档,我以为我是按照他们的建议做的,但我一定在某个地方搞砸了。

我什至一次评论一行,保存并加载模型。唯一发生错误的情况是当我将双向与 LSTM 层包含在一起时。单独拥有 LSTM 层不会导致错误。

有什么想法为什么会发生这种情况吗?

编辑:我正在使用tensorflow 2.16.1和keras 3.2.0

python tensorflow keras lstm bidirectional
1个回答
0
投票

这似乎是tensorflow 2.16.1版本的问题。我通过升级到当前的 tf 每晚版本自行解决了这个问题。

.keras 格式有点像 zip 文件,它在 config.json 文件中保存模型架构。尝试使用 tf.keras.models.model_from_json() 构建模型会导致此错误。

© www.soinside.com 2019 - 2024. All rights reserved.