Keras LSTM金融时序模型报错:期望3维数组却得到2维数组
解决Keras LSTM金融时间序列模型维度不匹配问题
嘿,我来帮你搞定这个维度不匹配的坑!先直接说核心问题:你的LSTM层参数设置和目标数据的形状不匹配,再加上生成器里有个逻辑小bug,咱们一步一步来修复。
问题根源拆解
先看报错信息:expected lstm_1 to have 3 dimensions, but got array with shape (500, 8640)
- 你给LSTM层加了
return_sequences=True,这个参数会让LSTM返回每个时间步的输出,输出形状是(batch_size, timesteps, units)也就是(500, 8640, 1),是三维数组。 - 但你的y_batch是
(500, 8640)的二维数组,而且从代码逻辑看,你其实是想给每一段8640步的输入序列,对应一个单一目标值(取的是j+periods位置的target_buy),这就完全不匹配了。
另外你的生成器还有个隐藏bug:while len(x_batch) < batch_size: 这里x_batch初始化时就是(500, 8640, 13),len(x_batch)等于你设置的batch_size,所以这个循环根本不会执行,生成的x和y都是全0的数组,这也是个大坑!
修复步骤
1. 修正数据生成器的逻辑和y_batch形状
把生成器里的y_batch改成每个样本对应一个目标值,同时修正循环条件:
def gen(batch_size, periods): j = 0 features = ['ask_close', 'ask_open', 'ask_high', 'ask_low', 'bid_close', 'bid_open', 'bid_high', 'bid_low', 'open', 'high', 'low', 'close', 'price'] with pd.HDFStore('datasets/eurusd.h5') as store: df = store['train_buy'] x_shape = (batch_size, periods, len(features)) x_batch = np.zeros(shape=x_shape, dtype=np.float16) # 修改y_shape为每个样本对应一个目标值 y_shape = (batch_size, 1) y_batch = np.zeros(shape=y_shape, dtype=np.float16) while True: i = 0 # 循环条件改为i < batch_size,按索引填充样本 while i < batch_size: if df.iloc[j+periods]['direction'].values == 1: x_batch[i] = df.iloc[j:j+periods][features].values # 直接赋值标量到y_batch的对应位置 y_batch[i, 0] = df.iloc[j+periods]['target_buy'][0].round(4) i += 1 j += 1 if j == 56241737 - periods: j = 0 yield x_batch, y_batch
2. 调整LSTM层的参数
因为你的任务是序列到单个输出(一段时间序列对应一个预测值),所以要去掉return_sequences=True(默认值是False),这样LSTM只会返回最后一个时间步的输出,形状是(batch_size, 1),和修正后的y_batch完美匹配:
model = Sequential() # 移除return_sequences=True,让LSTM返回单个时间步的输出 model.add(LSTM(units=1, input_shape=(None, feature_no))) optimizer = RMSprop(lr=1e-3) model.compile(loss='mse', optimizer=optimizer) model.fit_generator(generator=generator, epochs=10, steps_per_epoch=112483)
补充:如果是序列到序列任务
要是你实际需要模型预测每个时间步的目标值,那需要把y_batch改成三维数组:
- 将y_shape改为
(batch_size, periods, 1) - 赋值时对应每个时间步的目标数据(不过从你的代码逻辑看,你当前的需求不是这个,所以大概率不需要这个方案)
这样改完之后,维度匹配的问题就解决了,生成器也能正确填充训练数据啦!
内容的提问来源于stack exchange,提问作者Joseph Choi
相关产品推荐
相关产品推荐

