2017-05-08 60 views
0

我目前正在試圖擴大我在書中找到的時間序列示例。我一直在努力將其轉移到功能性API,但我遇到了問題。我在功能模型中所經歷的錯誤是:Keras:將Seq模型轉換爲功能API

Traceback (most recent call last): File "merge_n.py", line 57, in lstm = LSTM(4, batch_input_shape=(batch_size, look_back, 1), stateful=True)(inputs) File "/Users/pjhampton/Desktop/MTL/lib/python3.5/site-packages/keras/layers/recurrent.py", line 243, in call return super(Recurrent, self).call(inputs, **kwargs) File "/Users/pjhampton/Desktop/MTL/lib/python3.5/site-packages/keras/engine/topology.py", line 541, in call self.assert_input_compatibility(inputs) File "/Users/pjhampton/Desktop/MTL/lib/python3.5/site-packages/keras/engine/topology.py", line 440, in assert_input_compatibility str(K.ndim(x))) ValueError: Input 0 is incompatible with layer lstm_1: expected ndim=3, found ndim=4

順序模型(原件)

######################################################## 
# main input 
######################################################## 
look_back = 5 
trainX, trainY = create_dataset(train, look_back) 
testX, testY = create_dataset(test, look_back) 

# reshape input to be [samples, time steps, features] 
trainX = numpy.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1)) 
testX = numpy.reshape(testX, (testX.shape[0], testX.shape[1], 1)) 

batch_size = 1 

model = Sequential() 
model.add(LSTM(4, batch_input_shape=(batch_size, look_back, 1), stateful=True)) 
model.add(Dense(1)) 
model.compile(loss='mse', optimizer='adam') 

for i in range(100): 
    model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) 
    model.reset_states() 

功能API基於模型(我試過)

inputs = Input(shape=(batch_size, look_back, 1)) 

lstm = LSTM(4, batch_input_shape=(batch_size, look_back, 1), stateful=True)(inputs) 
dense = Dense(1)(lstm) 

model = Model(inputs=inputs, outputs=dense) 

model.compile(loss='mse', optimizer='adam') 
for i in range(100): 
    model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) 
    model.reset_states() 

Full code:https://friendpaste.com/3Zg3VKBs3qd7FNXubNONzN

回答

2

您已指定您的RNN是有狀態的,因此您需要在輸入中指定batch_shape

inputs = Input(batch_shape=(batch_size, look_back, 1)) 

lstm = LSTM(4, stateful=True)(inputs) 
dense = Dense(1)(lstm) 

model = Model(inputs=inputs, outputs=dense) 

model.compile(loss='mse', optimizer='adam') 
for i in range(100): 
    model.fit(trainX, trainY, epochs=1, batch_size=batch_size, verbose=2, shuffle=False) 
    model.reset_states() 

看來,順序模式是你在尋找什麼,但。

相關問題