如何计算tensorflow中的maskimage梯度一致性损失

2024-05-23 21:21:53 发布

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

我想创建本文描述的自定义损失函数Real-time deep hair matting on mobile devices。我已经在TF2.0(Google Colab)中实现了它,它工作时没有错误。但是,我没有看到文章中描述的准确性有任何提高(提高1%)。我不确定我计算掩模图像一致性损失(Lc)的实现是否正确。请看下面我的代码。我不得不加上1e-30来掩盖梯度大小,因为损失变成了nan。有人能看到实现此功能的问题吗

def custom_loss(input_img):

    def Loss(y_true, y_pred):

        L = tf.keras.losses.binary_crossentropy(y_true, y_pred, from_logits=False)

        input_img_gray = tf.image.rgb_to_grayscale(input_img)

        Iy, Ix = tf.image.image_gradients(input_img_gray)

        Mys, Mxs = tf.image.image_gradients(y_pred)


        Mx_pow = tf.math.square(Mxs)
        My_pow = tf.math.square(Mys)
          
        M_mag = tf.sqrt(tf.math.add(Mx_pow,My_pow) + 1e-30 ) 
    
        M_magsum = tf.math.reduce_sum(M_mag, axis=None) 

        inner_form = 1 - (tf.math.pow((Ix * Mxs + Iy * Mys),2))
  
        Lc = tf.math.reduce_sum(tf.math.multiply(M_mag,inner_form))
        Lc = tf.math.divide(Lc,M_magsum)
    
       loss =  tf.math.add(L, (0.5 * Lc))
    
    return loss

return Loss

enter image description here


Tags: imageimginputtfdefmathlc损失