Make custom keras loss function

Hey. I am trying to create a custom loss function in keras for dice_error_coefficient. It has its implementations in the strain gage , and I tried to use the same function in keras with tensor flow, but it keeps returning NoneType when I used model.train_on_batch or model.fit , where it gives the correct values ​​when used in metrics in the model. Can someone help me with what I should do? I tried the following libraries, such as Keras-FCN by ahundt, where it used custom loss functions, but none of them work. The target and output in the code are y_true and y_pred respectively, as used in the loss.py file in 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 
0
source share
1 answer

There are two steps to implementing a parameterized user loss function in Keras. Firstly, writing a method for coefficient / metric. Secondly, writing a wrapper function to format things the way Keras needs them.

  • Actually, it’s pretty cleaner to use the Keras backend instead of the tensor flow directly for simple custom loss functions like DICE. Here is an example of such a coefficient:

     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) 
  • Now for the tricky part. Keras loss functions should only accept (y_true, y_pred) as parameters. Therefore, we need a separate function that returns another function.

     def dice_loss(smooth, thresh): def dice(y_true, y_pred) return -dice_coef(y_true, y_pred, smooth, thresh) return dice 

Finally, you can use it as follows in Keras compilation.

 # 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) 
+9
source

All Articles