2017-03-09 136 views
1

我在一個虛擬的例子努力瞭解LSTM是如何工作的使用Keras。 我遇到了重塑數據輸入和輸出的方式問題。Keras重塑輸入LSTM

ValueError異常:輸入0與層經常不兼容:預計NDIM = 3,發現NDIM = 2

import random 
import numpy as np 

from keras.layers import Input, LSTM, Dense 
from keras.layers.wrappers import TimeDistributed 
from keras.models import Model 

def gen_number(): 
    return np.random.choice([random.random(), 1], p=[0.2, 0.8])  
truth_input = [gen_number() for i in range(0,2000)]  
# shift input by one 
truth_shifted = truth_input[1:] + [np.mean(truth_input)]  
truth = np.array(truth_input) 
test_ouput = np.array(truth_shifted)   
truth_reshaped = truth.reshape(1, len(truth), 1)  
shifted_truth_reshaped = test_ouput.reshape(1, len(test_ouput), 1) 
yes = Input(shape=(len(truth_reshaped),), name = 'truth_in')  
recurrent = LSTM(20, return_sequences=True, name='recurrent')(yes)  
TimeDistributed_output = TimeDistributed(Dense(1), name='test_pseudo')(recurrent)  
model_built = Model(input=yes, output=TimeDistributed_output)  
model_built.compile(loss='mse', optimizer='adam')  
model_built.fit(truth_reshaped, shifted_truth_reshaped, nb_epoch=100) 

如何,我需要做正確輸入的數據?

+0

的可能的複製[如何處理用於keras LSTM輸入和輸出形狀(http://stackoverflow.com/questions/39969717/how-to-process-input-and-output-shape-for-keras-lstm ) –

回答

1
yes = Input(shape=(len(truth_reshaped),), name = 'truth_in') 

Len(truth_reshaped)將返回1,因爲您將它形如(1,2000,1)。這裏第一個是序列號,2000是序列中的時間步數,第二個是序列中每個元素的值數。

所以,你的輸入應該是

yes = Input(shape=(len(truth),1), name = 'truth_in') 

它會告訴你網絡的投入將是長度LEN的序列(真理,1),並與元素的一維。