2017-08-30 48 views
0

您好我一直在嘗試在keras中爲dice_error_coefficient創建自定義丟失函數。它在tensorboard它的實現,我嘗試使用相同的功能與tensorflow keras但它一直返回NoneType當我用model.train_on_batchmodel.fit,其中在使用時,它提供正確的價值觀指標在模型中。可以請別人幫我解決我該怎麼做?我已經嘗試過下面的庫,比如Keras-FCN,他使用了自定義丟失函數,但似乎沒有任何效果。代碼中的目標和輸出分別是y_true和y_pred,分別在keras的losses.py文件中使用。在keras中創建自定義丟失函數

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 

回答

8

在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編譯如下使用它。

# 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

非常感謝您的回答。我必將實現這個和檢查 –

+0

「骰子變形點焊(y_true,y_pred): \t返回-dice_coef(y_true,y_pred,1E-5,0.5) DEF dice_coef(y_true,y_pred,光滑,脫粒): \t y_pred = K.cast(y_pred> THRESH,D型細胞= tf.float32) \t y_true = K.cast(y_true> THRESH,D型細胞= tf.float32) \t y_true_f = K.flatten(y_true) \t y_pred_f = K.flatten( y_pred) \t路口= K.sum(y_true_f * y_pred_f) \t回報(2. *相交+平滑)/(K.sum(y_true_f)+ K.sum(y_pred_f)+光滑) Final_Model.compile(優化=選擇,損失=骰子,metrics = ['acc'])' 這給了我一個錯誤 '試圖將'x'轉換爲張量並失敗。錯誤:沒有值不受支持。' –

+0

在將模型傳遞給模型之前是否調用了骰子的實例? 'dice_fn = dice(smooth = 1e-5,thresh = 0.5)' 'Final_Model.compile(optimizer = opt,loss = dice_fn)' –

相關問題