【665】构建多损失函数

  所谓多损失函数,就是将多个损失函数混合在一起进行使用,具体实现就可以新建一个函数,包含多个损失函数的加和即可,实质上与单损失函数是一致的。

  参考:【632】keras 自定义损失函数

  举例:Dice loss + BEC loss

# 定义Dice损失函数
def dice_coef_loss(y_true, y_pred):
    # 防止分母为0
    smooth = 1e-5
    y_truef = K.flatten(y_true)  # 将 y_true 拉为一维
    y_predf = K.flatten(y_pred)
    intersection = K.sum(y_truef * y_predf)
    dice_coef = (2 * intersection + smooth) / (K.sum(y_truef) + K.sum(y_predf) + smooth)
 
    return 1 - dice_coef

def binary_crossentropy(y_true, y_pred):
    return keras.losses.binary_crossentropy(y_true, y_pred)

def DICE_BEC(y_true, y_pred):
    return dice_coef_loss(y_true, y_pred) + binary_crossentropy(y_true, y_pred)
原文地址:https://www.cnblogs.com/alex-bn-lee/p/15403049.html