我想使用带有 keras 的 LSTM 神经网络来预测时间序列组,但在使模型与我想要的匹配时遇到了麻烦。我的数据维度是:
输入张量:(data length, number of series to train, time steps to look back)
输出张量:(data length, number of series to forecast, time steps to look ahead)
注意:我想保持尺寸完全一样,没有转置。
重现问题的虚拟数据代码是:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, TimeDistributed, LSTM
epoch_number = 100
batch_size = 20
input_dim = 4
output_dim = 3
look_back = 24
look_ahead = 24
n = 100
trainX = np.random.rand(n, input_dim, look_back)
trainY = np.random.rand(n, output_dim, look_ahead)
print('test X:', trainX.shape)
print('test Y:', trainY.shape)
model = Sequential()
# Add the first LSTM layer (The intermediate layers need to pass the sequences to the next layer)
model.add(LSTM(10, batch_input_shape=(None, input_dim, look_back), return_sequences=True))
# add the first LSTM layer (the dimensions are only needed in the first layer)
model.add(LSTM(10, return_sequences=True))
# the TimeDistributed object allows a 3D output
model.add(TimeDistributed(Dense(look_ahead)))
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
model.fit(trainX, trainY, nb_epoch=epoch_number, batch_size=batch_size, verbose=1)
这导致:
异常:检查模型目标时出错:预期 timedistributed_1 的形状为 (None, 4, 24) 但得到的数组的形状为 (100, 3, 24)
问题似乎出在定义TimeDistributed
图层时。
如何定义TimeDistributed
层以便编译和训练?