LSTM模型的时间序列数据输入会引发错误

问题描述 投票:0回答:1

我正在尝试在时间序列数据上使用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)

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

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

python machine-learning keras lstm
1个回答
1
投票

Mistake 1:

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

Mistake 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)
© www.soinside.com 2019 - 2024. All rights reserved.