我正在使用TensorFlow训练一个网络来预测数字列表中的第三个数字。
当我进行训练时,网络似乎训练得很好,并且在训练集和测试集上表现不错。然而,当我自己评估其性能时,它似乎表现得非常差。
例如,训练结束时,TensorFlow表示验证损失为2.1 x 10^(-5)
。然而,当我自己计算时,我得到的是0.17 x 10^0
。我做错了什么?
以下是可以在Google Colab上运行的代码:
回答:
你忽略了y_test
的形状问题。
y_test.numpy().shape(500,) <-- causing the behaviour
只需重新调整形状即可:
val_loss = tf.math.reduce_mean(tf.keras.losses.MSE(y_test.numpy().reshape(-1,1), model.predict(x_test))).numpy()print(val_loss) # 1.1548506e-05
另外:
history.history["val_loss"][-1] # 1.1548506336112041e-05
或者你可以在计算时对两组数据都使用flatten()
方法:
val_loss = tf.math.reduce_mean(tf.keras.losses.MSE(y_test.numpy().flatten(), model.predict(x_test).flatten())).numpy()print(val_loss) # 1.1548506e-05