Kalpit
Kalpit

Reputation: 1101

Custom metric for Semantic segmentation

I am working on a multi-class semantic segmentation task, and would like to define a custom, weighted metric for calculating how well my NN is performing.

I am using U-net to segment my image into one of 8 classes, of which 1-7 are the particular classes and 0 is background. How do I use the standard custom metric template defined on the Keras metrics page, so that I only get the IoU of only channels 1-7, multiplied by a (1,7) weights array? I tried removing the background channel in the custom metric by using

y_true, y_pred = y_true[1:,:,:], y_pred[1:, :,:]

but it does not look like that's what I want. Any help will be appreciated.

Upvotes: 4

Views: 1111

Answers (1)

Kalpit
Kalpit

Reputation: 1101

The change that was necessary

def dice_coef_multilabel(y_true, y_pred, numLabels=CLASSES):
    dice=0
    for index in range(numLabels):
        dice -= dice_coef(y_true[:,:,index], y_pred[:,:,index])
    return dice

If needed, the dice coeff can be calcualted across channels by using two nested loops to loop over all the channel combinations. I'm also including the dice coefficient calculation.

def dice_coef(y_true, y_pred):
    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)

FWIW, this github link has various types of metrics were implemented in a channel-wise manner.

Upvotes: 2

Related Questions