You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多次训练Keras RNN后出现输入维度不匹配的ValueError求助

Keras LSTM时间序列训练重复执行后出现输入形状不兼容错误

在Google Colaboratory中用Keras实现LSTM进行时间序列预测,代码如下(除导入语句外,其余代码在单个单元格中):

from tensorflow import keras
mae = keras.losses.MeanAbsoluteError()
hidden_neurons = 50
output_neurons = 1
epoch_size = 50
batch_size = 72
# x_train has shape (500, 1, 23)
LSTM_layer = keras.layers.LSTM(hidden_neurons, input_shape = (x_train.shape[1], x_train.shape[2]), dropout = 0.05) 
output_layer = keras.layers.Dense(1)
test_model = keras.Sequential(layers = (LSTM_layer, output_layer))
test_model.reset_states()
test_model.compile(optimizer = 'adam', loss = mae)
test_model.summary()
history = test_model.fit(tf.expand_dims(x_train, axis=-1), y_train, epochs = epoch_size, batch_size = batch_size, validation_data=(x_test, y_test), shuffle = False)
# y_train has shape (500, 1)
# x_test has shape (500, 1, 23)
# y_test has shape (500, 1)

启动新运行时后首次训练正常,但重复执行该单元格3-4次后,抛出如下错误:

ValueError                                Traceback (most recent call last)
<ipython-input-23-3ac5cc808611> in <module>
     12 test_model.compile(optimizer = 'adam', loss = mae)
     13 test_model.summary()
---> 14 history = test_model.fit(tf.expand_dims(x_train, axis=-1), y_train, epochs = epoch_size, batch_size = batch_size, validation_data=(x_test, y_test), shuffle = False) 
...
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
   1145           except Exception as e:  # pylint:disable=broad-except
   1146             if hasattr(e, "ag_error_metadata"):
-> 1147               raise e.ag_error_metadata.to_exception(e)
   1148             else:
   1149               raise

    ValueError: Input 0 of layer "sequential_2" is incompatible with the layer: expected shape=(None, 1, 23), found shape=(None, 23)

即使在fit中省略tf.expand_dims(x_train, axis=-1),错误仍然存在。尝试过调用test_model.reset_states(),以及在单独单元格执行以下代码:

keras.backend.clear_session()
del test_model

但均无效,只有强制终止运行时才能恢复正常:

import os
os.kill(os.getpid(), 9)

问题:是什么原因导致程序运行中途层输入形状要求发生变化?

补充:在本地Jupyter Notebook运行该单元格时也出现了相同错误。

内容的提问来源于stack exchange,提问作者Kartik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 20:55:20