在Keras中实现参数化的自定义损失函数有两个步骤。首先,编写系数/度量的方法。其次,编写包装函数以按Keras要求的方式格式化事物。
实际上,使用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)
现在开始棘手的部分。 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编译中如下使用它。
# 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)
0
嗨,我一直在尝试为dice_error_coefficient在keras中创建自定义损失函数。它有它的tensorboard实现,我尝试使用相同的功能与tensorflow keras但它一直返回NoneType当我用model.train_on_batch或model.fit其中作为模型指标使用时,它提供正确的价值观。可以请别人帮我做什么吗?我尝试过使用ahundt编写的Keras-FCN之类的库,其中他使用了自定义损失函数,但似乎都不起作用。代码中的目标和输出分别为y_true和y_pred,如keras中的loss.py文件中所使用。