在R中用Keras构建LSTM遇输入维度不匹配错误求助
问题背景
你正在用R语言的Keras构建无状态LSTM模型,数据集前3列是输入特征,最后1列是输出标签。模型结构定义如下:
model %>% layer_lstm(units = 1024, input_shape = c(1, 3), return_sequences = T ) %>% layer_lstm(units = 1024, return_sequences = F) %>% layer_dense(units = 1, activation = "linear") model %>% compile(loss = 'mse', optimizer = 'rmsprop')
模型结构输出正常:
Layer (type) Output Shape Param #lstm_1 (LSTM) (None, 1, 1024) 4210688
lstm_2 (LSTM) (None, 1024) 8392704
dense_3 (Dense) (None, 1) 1025Total params: 12,604,417
Trainable params: 12,604,417
Non-trainable params: 0
但执行训练代码时出现错误:
history <- model %>% fit(dt[,1:3], dt[,4], epochs=50, shuffle=F)
错误信息:
Error in py_call_impl(callable, dots$args, dots$keywords) :
ValueError: Error when checking input: expected lstm_1_input to have 3 dimensions, but got array with shape (3653, 3)
错误原因
Keras的LSTM层要求输入必须是三维张量,格式为(batch_size, timesteps, features),其中:
batch_size:每次训练的样本数(Keras会自动处理,不需要手动指定)timesteps:每个样本包含的时间步数features:每个时间步的特征数
你的输入dt[,1:3]是二维数组(3653, 3),缺少了时间步这个维度——即使你用的是无状态LSTM且每个样本只有1个时间步,也必须显式转换成三维格式。
解决方法
你已经找对了方向:通过重塑数据为三维数组来解决。这里可以把自定义的reshapeDt函数写得更明确:
reshapeDt <- function(data) { # 将二维特征数据转换为三维:(样本数, 时间步数=1, 特征数) array(data, dim = c(nrow(data), 1, ncol(data))) }
然后修改训练代码,传入重塑后的输入数据:
history <- model %>% fit(reshapeDt(dt[,1:3]), dt[,4], epochs=50, shuffle=F)
此时dim(reshapeDt(dt[,1:3]))会返回(3653, 1, 3),完全匹配LSTM层input_shape = c(1, 3)的要求(input_shape指定的是(timesteps, features),batch_size由Keras自动管理)。
补充说明
- 无状态LSTM的
input_shape不需要包含batch_size,因为Keras会根据训练时的输入自动推断 - 如果你后续需要调整时间步数(比如用滑动窗口生成多时间步样本),只需要修改
reshapeDt中的时间步维度,同时对应调整LSTM层的input_shape即可
内容的提问来源于stack exchange,提问作者Sayan Pal

