keras 如何通过 y_pred 到 loss object/function via model.compile
How does keras pass y_pred to loss object/function via model.compile
如果我有一个定义三重损失的函数(需要 y_true 和 y_pred 作为输入参数),并且我通过以下 "reference or call it":
model.compile(optimizer="rmsprop", loss=triplet_loss, metrics=[accuracy])
如何将 y_pred 传递给 triplet_loss 函数?
例如 triplet_loss 函数可能是:
def triplet_loss(y_true, y_pred, alpha = 0.2):
"""
Implementation of the triplet loss function
Arguments:
y_true -- true labels, required when you define a loss in Keras,
y_pred -- python list containing three objects:
"""
anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
# distance between the anchor and the positive
pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor,positive)))
# distance between the anchor and the negative
neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor,negative)))
# compute loss
basic_loss = pos_dist-neg_dist+alpha
loss = tf.maximum(basic_loss,0.0)
return loss
谢谢乔恩
我浏览了一些 keras 源代码。在 Model()
class:
首先他们稍微修改了函数以考虑权重:
self.loss_functions = loss_functions
weighted_losses = [_weighted_masked_objective(fn) for fn in loss_functions]
稍后在训练期间,他们将输出(预测)映射到目标(标签)并调用损失函数以获得 output_loss。这里 y_true 和 y_pred 被传递给你的函数。
y_true = self.targets[i]
y_pred = self.outputs[i]
weighted_loss = weighted_losses[i]
sample_weight = sample_weights[i]
mask = masks[i]
loss_weight = loss_weights_list[i]
with K.name_scope(self.output_names[i] + '_loss'):
output_loss = weighted_loss(y_true, y_pred,
sample_weight, mask)
如果我有一个定义三重损失的函数(需要 y_true 和 y_pred 作为输入参数),并且我通过以下 "reference or call it":
model.compile(optimizer="rmsprop", loss=triplet_loss, metrics=[accuracy])
如何将 y_pred 传递给 triplet_loss 函数?
例如 triplet_loss 函数可能是:
def triplet_loss(y_true, y_pred, alpha = 0.2):
"""
Implementation of the triplet loss function
Arguments:
y_true -- true labels, required when you define a loss in Keras,
y_pred -- python list containing three objects:
"""
anchor, positive, negative = y_pred[0], y_pred[1], y_pred[2]
# distance between the anchor and the positive
pos_dist = tf.reduce_sum(tf.square(tf.subtract(anchor,positive)))
# distance between the anchor and the negative
neg_dist = tf.reduce_sum(tf.square(tf.subtract(anchor,negative)))
# compute loss
basic_loss = pos_dist-neg_dist+alpha
loss = tf.maximum(basic_loss,0.0)
return loss
谢谢乔恩
我浏览了一些 keras 源代码。在 Model()
class:
首先他们稍微修改了函数以考虑权重:
self.loss_functions = loss_functions
weighted_losses = [_weighted_masked_objective(fn) for fn in loss_functions]
稍后在训练期间,他们将输出(预测)映射到目标(标签)并调用损失函数以获得 output_loss。这里 y_true 和 y_pred 被传递给你的函数。
y_true = self.targets[i]
y_pred = self.outputs[i]
weighted_loss = weighted_losses[i]
sample_weight = sample_weights[i]
mask = masks[i]
loss_weight = loss_weights_list[i]
with K.name_scope(self.output_names[i] + '_loss'):
output_loss = weighted_loss(y_true, y_pred,
sample_weight, mask)