How to fix 'ValueError: Cannot feed value of shape X for Tensor Y, which has shape Z on Keras

How to fix 'ValueError: Cannot feed value of shape X for Tensor Y, which has shape Z on Keras

模型架构

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 是从哪里来的,因为输入形状是 (50,10,9),这正是它所期望的。

使用

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

您正在通过 batch_input_shape(50,10,9)

将批量大小固定为 50

但是,当您使用 predict 时,您不会传入默认为 32 的 batch_size。因此它会尝试将 (32, 10, 9) 传入 (50, 10, 9) 并且它失败了。

它在 fit_generator 中没有失败,因为您的 generator 应该返回一个大小为 50 的批次。

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