btguijiyang 2019-05-05 14:51 采纳率: 100%
浏览 4368
已采纳

tensorflow自定义的损失函数 focal_loss出现inf,在训练过程中出现inf

图片说明

def focal_loss(alpha=0.25, gamma=2.):
    """ focal loss used for train positive/negative samples rate out 
    of balance, improve train performance
    """
    def focal_loss_calc(y_true, y_pred):
        positive = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
        negative = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
        return -(alpha*K.pow(1.-positive, gamma)*K.log(positive) +
                       (1-alpha)*K.pow(negative, gamma)*K.log(1.-negative))
    return focal_loss_calc
self.keras_model.compile(optimizer=optimizer, loss=dice_focal_loss, metrics=[ mean_iou, dice_loss, focal_loss()])

上面的focal loss 开始还是挺正常的,随着训练过程逐渐减小大0.025左右,然后就突然变成inf。何解

  • 写回答

1条回答 默认 最新

  • btguijiyang 2019-06-13 23:47
    关注

    解决方法

    def focal_loss_calc(alpha=0.25, gamma=2., epsilon=1e-6):
        """ focal loss used for train positive/negative samples rate out 
        of balance, improve train performance
        """
        def focal_loss(y_true, y_pred):
            positive = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
            negative = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
            return -alpha*K.pow(1.-positive, gamma)*K.log(positive+epsilon) - \
                (1-alpha)*K.pow(negative, gamma)*K.log(1.-negative+epsilon)
        return focal_loss
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料