【问题标题】:Keras: Converting Seq model to Functional APIKeras:将 Seq 模型转换为函数式 API
【发布时间】:2017-10-06 13:09:24
【问题描述】:

我目前正在尝试扩大我在书中找到的时间序列示例。我一直在尝试将其移至功能 API,但我遇到了问题。我在功能模型中遇到的错误是:

Traceback(最近一次调用最后一次):文件“merge_n.py”,第 57 行,在 lstm = LSTM(4, batch_input_shape=(batch_size, look_back, 1), stateful=True)(inputs) 文件 “/Users/pjhampton/Desktop/MTL/lib/python3.5/site-packages/keras/layers/recurrent.py”, 第 243 行,在 调用 return super(Recurrent, self).call(inputs, **kwargs) File "/Users/pjhampton/Desktop/MTL/lib/python3.5/site-packages/keras/engine/topology. py", 第 541 行,在 调用 self.assert_input_compatibility(输入)文件“/Users/pjhampton/Desktop/MTL/lib/python3.5/site-packages/keras/engine/topology.py”, 第 440 行,在 assert_input_compatibility str(K.ndim(x))) ValueError: Input 0 is in compatible 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()

完整代码:https://friendpaste.com/3Zg3VKBs3qd7FNXubNONzN

【问题讨论】:

    标签: python machine-learning keras


    【解决方案1】:

    您已指定您的 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()
    

    似乎顺序模型正是您正在寻找的。​​p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多