2016-08-05 84 views
1

我有一個長度爲1000的數字序列,我把它分成100個長度的序列。所以我最終得到901個長度爲100的序列。讓第一個900爲trainXtrainY是這些序列的第2到901個。一對一LSTM

在keras中,我希望構建以下圖片模型:enter image description here重要的功能是$ X_1 $映射到$ X_2 $,$ X_2 $映射到$ X_3 $等等。忽略我沒有繪製100個單位的事實。

在keras中,我知道如何構建$ X_1 $到$ X_ {100} $映射到$ X_ {101} $(多對一)的模型。這是由以下完成:

batch_size = 1 
time_steps = 100 
model = Sequential() 
model.add(LSTM(32, batch_input_shape=(batch_size, time_steps, 1), stateful=True)) 
model.add(Dense(1)) 

但是,在多對多的情況下,以下夾頭的錯誤:

model = Sequential() 
model.add(LSTM(32, batch_input_shape=(batch_size, time_steps, 1), stateful=True, return_sequences=True)) 
model.add(Dense(1)) 

我試着說return_sequences=True保持一個事實,即100個輸出給。我得到錯誤Input 0 is incompatible with layer dense_6: expected ndim=2, found ndim=3,我想這是可以理解的,因爲Dense只能預測batch_size x hidden_nodes尺寸矩陣作爲輸入,而在我的情況下,它輸出batch_size x time_steps x hidden_nodes

所以我的問題是如何得到一個LSTM的行爲如圖所示。在密集層中,我不會無意中引用當前時間步的前面(或後面)的隱藏層。

回答

1

您不需要多個輸出。訓練您的模型以預測序列中的下一個數字。然後,使用預測的數字並將其送入訓練好的模型並預測下一個並重復此任務。換句話說:

訓練準備數據:

X_train = np.zeros((901, 100)) 
y_train = np.zeros((901, 1)) 
for i in range(901) 
    x_train[i,:] = x[i:i+100] 
    y_train[i,0] = x[i+101] 

火車模型:

for iteration in range(10000): 
    model.fit(x_train, y_train, batch_size = 40, nb_epoch = 2) 

現在,如果你想預測未來10個號碼開頭:X [T: T + 101]

所有你需要做的是:

x_input = np.zeros((1, 100)) 
    x_input[0, :] = x[t+i: t+i+101] 
    for i in range(10) 
     y_output = model.predict(x_input) 
     print(y_output) 
     x_input[0, 0:100] = x[t+i+1: t+i+100] 
     x_input[100] = y_output 

本例中我使用了batch_size = 40。但是,你可以使用任何東西(但我不推薦1!;))

+0

注意:我沒有執行代碼。我只是寫了它。 – Nejla

+0

就這樣你知道我已經知道如何做這個版本的預測。我想要的模型與你所提到的稍有不同。 「在keras中,我知道如何建立$ X_1 $到$ X_ {100} $映射到$ X_ {101} $(多對一)的模型」 –