如何解决'ValueError:无法为张量Y馈送形状X的值,而在Keras上具有形状Z

时间:2019-04-21 10:56:23

标签: python keras lstm shapes valueerror

模型架构

model = Sequential()
model.add(LSTM(50,batch_input_shape(50,10,9),return_sequences=True))
model.add(LSTM(30,return_sequences=True, activation='tanh'))
model.add(LSTM(20,return_sequences=False, activation='tanh'))
model.add(Dense(9, activation='tanh'))
model.compile(loss='mean_squared_logarithmic_error',
                   optimizer='adam',metrics=['accuracy'])

摘要如下所示

Layer (type)                 Output Shape              Param #   
=================================================================
lstm_1 (LSTM)                (50, 10, 50)              12000     
_________________________________________________________________
lstm_2 (LSTM)                (50, 10, 30)              9720      
_________________________________________________________________
lstm_3 (LSTM)                (50, 20)                  4080      
_________________________________________________________________
dense_1 (Dense)              (50, 9)                   189       
=================================================================
Total params: 25,989
Trainable params: 25,989
Non-trainable params: 0

我使用fit_generator训练模型。我打算使用预测而不是predict_generator。我使用yeild编码了一个自定义生成器。没有任何问题,因为predict_generator可以正常工作

model.fit_generator(generator=generator, 
                    steps_per_epoch=250, epochs=10, shuffle=True)

当我使用predict

model.predict(testX = np.zeros(50,10,9))

这让我跌破错误

ValueError: Cannot feed value of shape (32, 10, 9) for Tensor
          'lstm_1_input:0', which has shape '(50, 10, 9)'

现在我不知道这32个字符的来源,因为Input形状是(50,10,9)正是它所期望的形状。

1 个答案:

答案 0 :(得分:0)

使用

model.predict(np.random.randn(50,10,9), batch_size=50)

您正在通过50将批次大小固定为batch_input_shape(50,10,9)

但是,当您使用predict时,您并没有传递默认为32的batch_size。因此,它试图将(32, 10, 9)传递到(50, 10, 9)中,但失败

它不会在fit_generator中失败,因为您的generator应该返回一批50。

https://keras.io/models/model/#predict