我正在尝试对时间序列数据使用LSTM模型。我处理的数据的具体背景是用于未来价格预测的Twitter情感分析。我的数据看起来像这样:
date mentions likes retweets polarity count Volume Close2017-04-10 0.24 0.123 -0.58 0.211 0.58 0.98 0.872017-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 = 200model = 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].valuesy_train = df.iloc[:,8].values# 样本数,时间步长,输入大小(在你的情况下是1)x_train = x_train.reshape(x_train.shape[0],x_train.shape[1], 1)model = Sequential()# 每个时间步的第一个LSTM的16个输出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)