首页 > 解决方案 > 如何解决 keras 中的 lstm 尺寸错误?

问题描述

这是我的代码

model = Sequential()
model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(1, return_sequences=True))

我收到了这个错误

ValueError: Error when checking target: expected lstm_3 to have 3 dimensions, but got array with shape (62796, 1) 

如果我设置return_sequences=True然后输出形状是 3D 数组

那么,为什么会出现这个错误呢??

标签: pythonkeras

解决方案


keras LSTM层的输入输出应该是3维的,默认遵循shape,

(Batch_size、Time_steps、特征)。

您似乎只使用了错误消息中的两个维度 (62796, 1)。

以下是一个包​​含合成数据的最小工作示例,它说明了 LSTM 网络所需的输入和输出形状。

from keras.models import Sequential
from keras.layers import LSTM, Dropout
import numpy as np

numb_outputs = 1

batch_size = 10
timesteps = 5
features = 2

x_single_batch = np.random.rand(batch_size, timesteps, features)
y_single_batch = np.random.rand(batch_size, timesteps, numb_outputs)

model = Sequential()
model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))

model.add(LSTM(512,  return_sequences=True))
model.add(Dropout(0.3))
model.add(LSTM(numb_outputs, return_sequences=True))

model.compile(optimizer='adam',loss='mse')
model.fit(x= x_single_batch, y=y_single_batch)

推荐阅读