LSTM神经网络模型张量与变量维度不匹配

设置LSTM模型

model=tf.keras.Sequential([
    LSTM(80,return_sequences=True),
    Dropout(0.2),
    LSTM(100),
    Dropout(0.2),
    Dense(1)
])
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),loss='mean_squared_error'

运行模型

checkpoint_save_path='./checkpoint/stock.ckpt'
if os.path.exists(checkpoint_save_path+'.index'):
    print('---------load the model---------')
    model.load_weights(checkpoint_save_path)
    
cp_callback=tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
                                               save_weights_only=True,
                                               save_best_only=True,
                                               monitor='val_loss')

history=model.fit(x_train,y_train,batch_size=64,
                  epochs=50,
                  validation_data=(x_test,y_test),
                  validation_freq=1,
                  callbacks=[cp_callback])

model.summary()    

报错
ValueError: Received incompatible tensor with shape (1, 80) when attempting to restore variable with shape (1, 320) and name layer_with_weights-0/cell/kernel/.OPTIMIZER_SLOT/optimizer/m/.ATTRIBUTES/VARIABLE_VALUE.

请问怎么改正?

与之前模型的checkpoint路径重合,新建一个路径保存即可

该回答引用GPT:
要解决这个问题,需要检查LSTM层的参数,确保它们的维度正确匹配。可以使用以下代码检查LSTM层的参数:

for layer in model.layers:
    if isinstance(layer, tf.keras.layers.LSTM):
        print(layer.kernel.shape)

如还有疑问,可留言帮助解决。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^