在keras中创建自定义丢失函数

2024-05-16 11:39:45 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我一直试图在keras中为骰子误差系数定制一个损失函数。它的实现在tensorboard中,我尝试在keras中使用与tensorflow相同的函数,但当我使用模型时,它一直返回一个NoneType。在批处理或模型上训练。在模型的度量中使用时,它会给出适当的值。能不能请人帮我做点什么?我试过使用像ahundt的Keras FCN这样的库,在那里他使用了定制的丢失函数,但似乎都不起作用。代码中的目标和输出分别是yútrue和yúpred,如keras中loss.py文件中所用。

def dice_hard_coe(target, output, threshold=0.5, axis=[1,2], smooth=1e-5):
    """References
    -----------
    - `Wiki-Dice <https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient>`_
    """

    output = tf.cast(output > threshold, dtype=tf.float32)
    target = tf.cast(target > threshold, dtype=tf.float32)
    inse = tf.reduce_sum(tf.multiply(output, target), axis=axis)
    l = tf.reduce_sum(output, axis=axis)
    r = tf.reduce_sum(target, axis=axis)
    hard_dice = (2. * inse + smooth) / (l + r + smooth)
    hard_dice = tf.reduce_mean(hard_dice)
    return hard_dice

Tags: 函数模型reducetargetoutputthresholdtfdice
1条回答
网友
1楼 · 发布于 2024-05-16 11:39:45

在Keras中实现参数化的自定义丢失函数有两个步骤。首先,编写系数/度量的方法。第二,编写一个包装函数,按照Keras需要的方式对内容进行格式化。

  1. 实际上,使用Keras后端而不是tensorflow直接用于像DICE这样的简单的自定义丢失函数要干净得多。下面是这样实现的系数示例:

    import keras.backend as K
    def dice_coef(y_true, y_pred, smooth, thresh):
        y_pred = y_pred > thresh
        y_true_f = K.flatten(y_true)
        y_pred_f = K.flatten(y_pred)
        intersection = K.sum(y_true_f * y_pred_f)
    
        return (2. * intersection + smooth) / (K.sum(y_true_f) + K.sum(y_pred_f) + smooth)
    
  2. 现在是棘手的部分。Keras损失函数只能以(y_true,y_pred)作为参数。所以我们需要一个单独的函数来返回另一个函数。

    def dice_loss(smooth, thresh):
      def dice(y_true, y_pred)
        return -dice_coef(y_true, y_pred, smooth, thresh)
      return dice
    

最后,您可以在Keras compile中按如下方式使用它。

# build model 
model = my_model()
# get the loss function
model_dice = dice_loss(smooth=1e-5, thresh=0.5)
# compile model
model.compile(loss=model_dice)

相关问题 更多 >