Segmentation Interpretation got an unexpected keyword argument 'reduction'

Hello, I’m trying to use SegmentationInterpretation module from fastai on my project. However, I get the following error:

dice_loss() got an unexpected keyword argument ‘reduction’

This dice_loss is a custom loss that I added to my model that is better for my problem

def dice_loss(input, target):
#     pdb.set_trace()
    smooth = 1.
    input = input[:,1,None].sigmoid()
    iflat = input.contiguous().view(-1).float()
    tflat = target.view(-1).float()
    intersection = (iflat * tflat).sum()
    return (1 - ((2. * intersection + smooth) / ((iflat + tflat).sum() +smooth)))

Is it possible to use SegmentationInterpretation with custom loss functions? If so, why is this error happening?

Kind regards

All basic losses have a reduction keyword argument. You can either add it and let it do nothing, or do something like:

def dice_loss(input, target, reduction='mean'):
#     pdb.set_trace()
    smooth = 1.
    n = input.size(0)
    input = input[:,1,None].sigmoid()
    iflat = input.contiguous().view(n, -1).float()
    tflat = target.view(n, -1).float()
    intersection = (iflat * tflat).sum(-1)
    dice =  (1 - ((2. * intersection + smooth) / ((iflat + tflat).sum(-1) +smooth)))
    if reduction == 'mean':
        return dice.mean()
    elif reduction=='sum':
        return dice.sum()
    else:
        return dice
5 Likes

Thank you. It worked :slight_smile:

1 Like

Do we have to implement a custom mean .mean() or .sum() method for a custom loss function?

No, tensor have those already implemented