Keras 中的自定义损失函数,Python?

Custom loss function in Keras, Python?

假设我们有预测的输出向量:

y_pred = [1, 0, 0, 1]

和实际输出值:

y_true = [0, 1, 0, 0]

我想构建以下差异向量y_pred-y_true:

y_diff = [1, -1, 0, 1]

统计其中1的个数,乘以一个常数。 这应该是我自定义损失函数的结果。 目标是更加重视某种错误(在这种情况下,如果预测值为 0 而真实值为 1,我希望损失更大)。

这是我的实现尝试:

def custom_loss_function(y_true, y_pred):
    # if it was 1 and you wrote 0, error is very very big
    y_diff = tf.math.subtract(y_true, y_pred)

    def fn(elem):
        if elem == 1:
            return 10
        elif elem == -1:
            return 1
        else:
            return 0

    return tf.reduce_sum(tf.map_fn(fn, y_diff))

问题是这样我的损失函数就不会"differentiable"了。我认为这就是我收到错误的原因:

ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.

关于如何根据某些条件(例如在当前任务中)实现更大(或更少)损失的自定义损失函数有什么想法吗?

你的问题自相矛盾。你说你想要 y_pred - y_true 但你在代码中计算 y_true - y_pred 。不过您可以使用以下内容。

def custom_loss_function(y_true, y_pred):
    # if it was 1 and you wrote 0, error is very very big
    y_diff = y_true - y_pred

    mul_mask = tf.cast(tf.math.equal(y_diff, 1.0), tf.float32)*9.0 + 1
    y_diff = tf.math.sqrt((y_diff * mul_mask)**2)

    return tf.reduce_sum(y_diff)

PS:我希望你有充分的理由使用这个自定义损失函数。因为您可以在执行 model.fit() 时简单地使用 class_weights 参数进行称重,因此,如果您只想按 class.

称重,则无需自己实现。