无法为有状态LSTM keras提供价值

时间:2018-06-14 20:53:20

标签: python tensorflow keras lstm

代码的问题是什么?

它返回ValueError: Cannot feed value of shape (2, 5, 7) for Tensor u'lstm_1_input:0', which has shape '(5, 5, 7)'错误。

我的代码:

model = Sequential()
model.add(LSTM(128,batch_input_shape=(5,5,7),return_sequences=True,stateful=True))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(LSTM(32))
model.add(Activation('relu'))
model.add(Dense(2))
model.add(Activation('softmax'))
checkpoint = ModelCheckpoint('./model28-{epoch:02d}.h5')
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
print(model.summary())
model.fit(trainX,trainY,batch_size=5,epochs=20,validation_split=0.2,callbacks=[checkpoint],shuffle=False)

1 个答案:

答案 0 :(得分:0)

我的trainX形状是34365.我删除了最后一行5,形状为34360(形状应该由batch_size分隔)。 应该调用每个epochreset_states(),因此我将代码更改为:

epo_num= 20
model = Sequential()
model.add(LSTM(128,batch_input_shape=(2,5,7),return_sequences=False,stateful=True))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(LSTM(32))
model.add(Activation('relu'))
model.add(Dense(2))
model.add(Activation('softmax'))
#checkpoint = ModelCheckpoint('./model30-{epoch:02d}.h5')
model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])
print(model.summary())
for i in range(epo_num):
    print('Epochs {:d}/{:d}'.format(i+1,epo_num))
    model.fit(trainX,trainY,batch_size=2,epochs=1,validation_split=0.2,shuffle=False)
    model.reset_states()