【发布时间】:2019-03-22 23:39:36
【问题描述】:
问题
如何在 Keras 中批量训练多步 LSTM 以实现单标签多类分类,每个时间步超过 2 个类?
当前错误
每个目标批次都是一个形状为 (batch_size, n_time_steps, n_classes) 的 3 维数组,但 Keras 需要一个 2 维数组。
示例/上下文
假设我们有 N 个股票的每日收盘价,以及每个股票的每日收盘价:m 个特征和“买入”、“持有”、“卖出”三个动作之一。 如果每只股票有 30 天的数据,我们可以训练 LSTM 来预测每个动作(每天,每只股票),如下所示。
对于大小为 n X_train 将具有(n, 30, m) 的形状,即n 样本、30 个时间步长和m 特征。在 one-hot 编码后,“购买”、“持有”和“出售”Y_train 将具有 (n, 30, 3) 的形状,这是一个 3 维数组。
问题是 Keras 由于期望 Y_train 是二维的而给出错误。
这是一个代码sn-p:
n_time_steps = 30
n_ftrs = 700
n_neurons = 100
n_classes = 3
batch_size = 256
n_epochs = 500
model = Sequential()
model.add(LSTM(n_neurons, input_shape=(n_time_steps, n_ftrs)))
model.add(Dense(n_classes, activation='sigmoid'))
model.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy'])
for e in range(n_epochs):
X_train, Y_train = BatchGenerator()
# Y_train.shape = (256, 30, 3)
model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=1)
错误
Error when checking target: expected dense_20 to have 2 dimensions,
but got array with shape (256, 30, 3)
【问题讨论】:
-
您可以尝试将输入形状设置为第一个 LSTM,例如
(None, n_time_steps, n_ftrs),而不将return_sequences设置为True?
标签: python keras time-series classification lstm