【发布时间】:2021-02-26 19:32:00
【问题描述】:
我正在研究如何使用 tensorflow 2.0 自定义 fit 方法中发生的事情,我正在关注此链接:https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit,但我注意到上一个链接的代码有所不同;特别是它首先以这种方式训练模型:
with tf.GradientTape() as tape:
y_pred = self(x, training=True) # Forward pass
# Compute the loss value
# (the loss function is configured in `compile()`)
loss = self.compiled_loss(y, y_pred, regularization_losses=self.losses)
print(loss)
在这之后:
with tf.GradientTape() as tape:
y_pred = self(x, training=True) # Forward pass
# Compute our own loss
loss = keras.losses.mean_squared_error(y, y_pred)
print(loss.shape)
如您所见,不同之处在于损失函数的计算:在第一个块中,他们使用编译的损失函数,而在第二个块中,损失是使用mean_squared_error 函数计算的。
当我检查损失的形状时,我产生了疑问:在第一种情况下,它是一个像这样的标量:(tf.Tensor(0.21193008, shape=(), dtype=float32),而在第二种情况下,打印语句给了我一个形状为(32,) 的张量。
我的想法是,在第二种情况下,不计算批次的平均值,我不知道为什么。
我使用tf.reduce_mean 解决了,但我不确定它是否正确。但是损失应该是一个标量,因此我不明白没有tf.reduce_mean 的第二种模式如何工作,以及该语句的使用是否正确。
【问题讨论】:
标签: python tensorflow keras deep-learning tensorflow2.0