首页 > 解决方案 > LSTM 模型的时间序列数据输入引发错误

问题描述

我正在尝试对时间序列数据使用 LSTM 模型。我正在使用的数据的具体背景是用于未来价格预测的 Twitter 情绪分析。我拥有的数据如下所示:

   date      mentions   likes  retweets  polarity  count   Volume   Close
2017-04-10     0.24     0.123    -0.58     0.211    0.58    0.98    0.87
2017-04-11    -0.56     0.532     0.77     0.231   -0.23    0.42    0.92
.
.
.
2019-01-10     0.23     0.356    -0.21    -0.682    0.23   -0.12   -0.23

数据是大小 (608, 8),我计划使用的特征是第 2 到 7 列,我预测的目标是Close(即第 8 列)。我知道 LSTM 模型需要输入为 3D 张量的形状,因此我进行了一些操作来转换和重塑数据:

x = np.asarray(data.iloc[:, 1:8])
y = np.asarray(data.iloc[:. 8])

x = x.reshape(x.shape[0], 1, x.shape[1])

之后我尝试这样训练 LSTM 模型:

batch_size = 200
model = Sequential()

model.add(LSTM(batch_size, input_dim=3, activation='relu', return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(128, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(32, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1))

model.compile(loss='mean_squared_error', 
              optimizer='rmsprop', 
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=15)

运行这个模型给了我一个:

ValueError: Error when checking input: expected lstm_10_input to have 
shape (None, 3) but got array with shape (1, 10)

有人知道我哪里出错了吗?是我准备数据的方式,还是我训练模型错误?

我一直在阅读这个社区的许多相关问题以及文章/博客,但我仍然无法找到解决方案......感谢任何帮助,谢谢!

标签: pythonmachine-learningkeraslstm

解决方案


错误一:

x 的形状应该是 shape(batch_size, timesteps, input_dim)

错误2:

LSTM 的第一个参数不是批量大小而是输出大小

例子:

df = pd.DataFrame(np.random.randn(100,9))

x_train = df.iloc[:,1:8].values
y_train = df.iloc[:,8].values

# No:of sample, times_steps, input_size (1 in your case)
x_train = x_train.reshape(x_train.shape[0],x_train.shape[1], 1)

model = Sequential()
# 16 outputs of first LSTM per time step
model.add(LSTM(16, input_dim=1, activation='relu', return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(8, activation='relu'))
model.add(Dropout(0.1))
model.add(Dense(4, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(1))

model.compile(loss='mean_squared_error', 
              optimizer='rmsprop', 
              metrics=['accuracy'])

model.fit(x_train, y_train, epochs=15, batch_size=32)

推荐阅读