【问题标题】:Regression custom loss return value in Keras with and without custom loop带有和不带有自定义循环的 Keras 中的回归自定义损失返回值
【发布时间】:2020-11-11 19:07:32
【问题描述】:

当在 Keras 模型中定义自定义损失时,在线资源似乎表明该损失应该返回一个值数组(批次中每个样本的损失)。像这样的

def custom_loss_function(y_true, y_pred):
   squared_difference = tf.square(y_true - y_pred)
   return tf.reduce_mean(squared_difference, axis=-1)

model.compile(optimizer='adam', loss=custom_loss_function)

在上面的示例中,我不知道模型何时或是否使用tf.reduce_sum()tf.reduce_mean() 获取批量总和或平均值

在另一种情况下,当我们想要使用自定义函数实现自定义训练循环时,根据 Keras 文档要遵循的模板是这样的

for epoch in range(epochs):
    for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):

        with tf.GradientTape() as tape:
            y_batch_pred = model(x_batch_train, training=True)  
            loss_value = custom_loss_function(y_batch_train, y_batch_pred)

        grads = tape.gradient(loss_value, model.trainable_weights)
        optimizer.apply_gradients(zip(grads, model.trainable_weights))

所以按照书本,如果我理解正确,我们应该采用批次梯度的平均值。因此,上面的损失值应该是每批次一个值。

但是,该示例适用于以下两种变体:

  • tf.reduce_mean(squared_difference, axis=-1) # array of loss for each sample
  • tf.reduce_mean(squared_difference) # mean loss for batch

那么,为什么上面的第一个选项(数组丢失)仍然有效? apply_gradients 是否按顺序对每个值应用小的更改?虽然有效,但这是错误的吗?

没有自定义循环使用自定义循环的正确方法是什么?

【问题讨论】:

  • y_batch_train 和 y_batch_pred 有哪些维度?是 numpy 数组吗?
  • 这可能是 stackoverflow.com/questions/63390725 的副本;那里的答案对你有帮助吗?
  • @today 它帮助了一点 - 肯定是重叠的问题

标签: tensorflow machine-learning keras neural-network


【解决方案1】:

好问题。在我看来,这在 TensorFlow/Keras API 中没有很好的记录。默认情况下,如果您不提供标量 loss_value,TensorFlow 将提供 add them up(并且更新不是连续的)。本质上,这相当于沿批处理轴对损失求和。

目前,TensorFlow API 中的损失包括一个 reduction 参数(例如,tf.losses.MeanSquaredError),它允许指定如何沿批处理轴聚合损失。

【讨论】:

    猜你喜欢
    • 2017-10-14
    • 2019-08-22
    • 1970-01-01
    • 2020-10-05
    • 2020-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多