image-segmentation-keras icon indicating copy to clipboard operation
image-segmentation-keras copied to clipboard

Defining custom loss

Open varungupta31 opened this issue 3 years ago • 0 comments
trafficstars

I wish to define a custom binary crossentropy loss, in which I plan to apply the binary crossentropy loss on the foreground (1), and on the background(0), and then train the model using a combination of these two losses -> 0.8 emphasis on the foreground, and 0.2 on the background.

I attempted the following: (taking some inspiration from this code in the train.py file.

def custom_binary_crossentropy(gt, pr):
    from tensorflow.keras.losses import BinaryCrossentropy

    gt_fg = 1-gt[:,:,0]
    gt_bg = gt[:, :, 0]

    pr_fg = 1-pr[:,:,0]
    pr_bg = pr[:,:,0]

    bg_loss = BinaryCrossentropy(gt_bg, pr_bg)*gt_bg
    fg_loss = BinaryCrossentropy(gt_fg, pr_fg)*gt_fg
    net_loss = (0.8*fg_loss)+(0.2*bg_loss)

    return net_loss

My idea was to first separate the background and foreground in the predicted and ground-truth images, compute the losses and merge them in a weighted manner in the end. However, this approach leads to an typeError: Expected float32, got <tensorflow.pytho.keras.losses.BinaryCrossentropy object at 0x14ace4041040> of type 'BinaryCrossentropy' instead. traceback.

(The pr and gt in the code seems to be probability values, and not logits, since an activation is already applied)

Kindly help me out with the following, Thanks.

varungupta31 avatar Apr 16 '22 18:04 varungupta31