如何为多变量,多步骤LSTM配置密集输出层

时间:2019-05-02 23:30:18

标签: python tensorflow keras lstm

在给定时间序列测量的情况下,我试图在3个维度上预测到未来几步的物体轨迹。我从下面显示的三个序列的玩具问题开始。我的目标是对每个坐标进行一系列从1到n_steps_out的预测。但是,我无法配置输出密集层,并且我认为我在概念上缺少一些东西。

在这个玩具示例中,我最终得到了总共5个示例,具有3个功能的2个预测步骤,并且得出了值误差 “ ValueError:检查目标时出错:预期density_1具有2维,但数组的形状为(5,2,3)”

在此先感谢您提供的指导

'''

# multivariate multi-step stacked lstm example
from numpy import array
from numpy import hstack
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dense

# split a multivariate sequence into samples
def split_sequences(sequences, n_steps_in, n_steps_out):
    X, y = list(), list()
    for i in range(len(sequences)):
        # find the end of this pattern
        end_ix = i + n_steps_in
        out_end_ix = end_ix + n_steps_out
        # check if we are beyond the dataset
        if out_end_ix > len(sequences):
            break
        # gather input and output parts of the pattern
        seq_x, seq_y = sequences[i:end_ix, :], sequences[end_ix:out_end_ix,:]
        X.append(seq_x)
        y.append(seq_y)
    return array(X), array(y)

# define input sequence training data
in_seq1 = array([1, 2, 3, 4, 5, 6, 7, 8, 9])
in_seq2 = array([2, 4, 6, 8, 10, 12, 14, 16, 18])
in_seq3 = array([3, 6, 9, 12, 15, 18, 21, 24, 27])
# convert to [rows, columns] structure
in_seq1 = in_seq1.reshape((len(in_seq1), 1))
in_seq2 = in_seq2.reshape((len(in_seq2), 1))
in_seq3 = in_seq3.reshape((len(in_seq3), 1))
# horizontally stack columns
dataset = hstack((in_seq1, in_seq2, in_seq3))
# choose a number of time steps
n_steps_in, n_steps_out = 3, 2
# covert into input/output
X, y = split_sequences(dataset, n_steps_in, n_steps_out)
# the dataset knows the number of features, e.g. 2
print(X.shape, y.shape)
# summarize the data
for i in range(len(X)):
    print(X[i], y[i])
n_features = X.shape[2]

# define model
model = Sequential()
model.add(LSTM(100, activation='relu', return_sequences=True, input_shape=(n_steps_in, n_features)))
model.add(LSTM(100, activation='relu'))
model.add(Dense(n_steps_out))
model.compile(optimizer='adam', loss='mse')
# fit model
model.fit(X, y, epochs=10, verbose=1)
# demonstrate prediction
x_input = array([[10, 20, 30], [11, 22, 33 ], [12, 24, 36]])
x_input = x_input.reshape((1, n_steps_in, n_features))
yhat = model.predict(x_input, verbose=0)
print(yhat)

'''

1 个答案:

答案 0 :(得分:0)

所以,这就是我的看法。

model.fit(X,y...) 

您的y是轨迹坐标正确的向量吗? (长度3) 而在最后一层中,您的密集层如下所示:

Dense(2)

因为n_steps_out = 2

您将需要将其更改为3,因为您正在尝试预测三个值以进行构建。但是,在我看来,您误解了该LSTM模型的实现方式(或者您以一种我不知道的方式来实现它)