python - LSTM 模型的时间序列数据输入抛出错误

标签 python machine-learning keras lstm

我正在尝试在时间序列数据上使用 LSTM 模型。我正在使用的数据的具体背景是对 future 价格预测的 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 张量的形状,因此我进行了一些操作来转换和 reshape 数据:

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)

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

我已经阅读了该社区上的许多相关问题以及文章/博客,但我仍然无法找到解决方案......感谢您的任何帮助,谢谢!

最佳答案

错误1:

x 的形状应为形状 (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)

关于python - LSTM 模型的时间序列数据输入抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55577053/

相关文章:

python - 如何在 scikit-learn 中获取 LDA 的组件?

python - 函数式 API 中的 Tensorflow Keras sigmoid 激活

python - 如何实现只保留前 n 个值并将其余所有值清零的自定义 keras 层?

matplotlib - 如何使用 matplotlib 绘制非线性模型?

python - 检查文件路径列表是否存在

python - 如何使用 scikit-learn 加载之前保存的模型并使用新的训练数据扩展模型

python - 使用 NumPy 时如何根据数据类型创建数据子集?

Azure ML Studio - 添加新列

python - 错误-使用Keras的多分类神经网络

python - Pythonic 是什么意思?