LSTM时间序列预测报错expected ndim=3 found ndim=2求助
报错原因与解决方案
核心报错原因
- LSTM层要求输入为3维张量,格式为
(样本数, 时间步长, 特征数),你当前的训练集X_train_seasonal形状为(893, 93),只有2维,缺少特征维度。 - 模型定义中
input_shape参数填写错误:input_shape仅需描述单个样本的形状,不需要包含样本数维度,你错误传入了样本总数X_train_seasonal.shape[0],同时还漏写了.shape,X_train_seasonal[1]实际取的是训练集的第二个样本,而非第二维的大小。
修复步骤
- 给训练集增加特征维度:如果你的数据是单特征时序数据,直接在最后加一维即可,调整后形状变为
(893, 93, 1)
import numpy as np X_train_seasonal = np.expand_dims(X_train_seasonal, axis=-1)
- 修正模型的
input_shape参数
def getModel(): model = tf.keras.Sequential() # input_shape格式为(时间步长, 特征数),不需要传入样本数 model.add(tf.keras.layers.LSTM(100, activation='relu', input_shape=(X_train_seasonal.shape[1], X_train_seasonal.shape[2]))) model.add(tf.keras.layers.Dense(units=1)) return model
修改完成后再运行编译和训练代码即可正常执行。
内容的提问来源于stack exchange,提问作者João David de Freitas
相关产品推荐
相关产品推荐

