由于形状不匹配,导致model.prediction()失败

时间:2020-03-22 20:30:21

标签: tensorflow keras deep-learning mlp

我使用新的tf.keras版本2.2.4-tf训练了一个简单的MLP模型。该模型如下所示:

input_layer = Input(batch_shape=(138, 28))
first_layer = Dense(30, activation=activation, name="first_dense_layer_1")(input_layer)
first_layer = Dropout(0.1)(first_layer, training=True)
second_layer = Dense(15, activation=activation, name="second_dense_layer")(first_layer)
out = Dense(1, name='output_layer')(second_layer)
model = Model(input_layer, out)

enter image description here

尝试进行预测prediction_result = model.predict(test_data, batch_size=138)时出现错误。 test_data的形状为(69, 28),因此比batch_size的138小。这是一个错误,看来问题出在第一个辍学层:

tensorflow.python.framework.errors_impl.InvalidArgumentError:  Incompatible shapes: [138,30] vs. [69,30]
     [[node model/dropout/dropout/mul_1 (defined at ./mlp_new_tf.py:471) ]] [Op:__inference_distributed_function_1700]

相同的解决方案在较旧版本的keras(2.2.4)和tensorflow(1.12.0)中没有问题。我该如何解决该问题?我没有更多要测试的数据,因此无法更改test_data设置以拥有更多数据点!

1 个答案:

答案 0 :(得分:1)

由于您是在预测时看到问题的,因此解决此问题的一种方法是将测试数据填充为批次大小的倍数。由于批次数量没有变化,因此不应减慢预测速度。 numpy.pad应该可以解决问题。

相关问题