Calculating dice coefficient

def dice_coeff(pred, target):
    smooth = 1.
    num = pred.size(0)
    m1 = pred.view(num, -1).float()  # Flatten
    m2 = target.view(num, -1).float()  # Flatten
    intersection = (m1 * m2).sum().float()

    return (2. * intersection + smooth) / (m1.sum() + m2.sum() + smooth)

in the code above i am trying to calculating dice coefficient for segmetnation task
but it resturn tensor value instead of the value of similrty
train dice tensor(3.2344e-05, device=‘cuda:0’)

1 Like

Use item() to get the value in a tensor.

thanks
i tried it works , but the value is 99 which impossible , do you have another function to measure dice similrty ?

What is num? I guess it is the size of mini-batch, the number of training examples, or the number of classes. If it is the size of mini-batch or the number of training examples, you can calculate per-example dice coefficients by using sum(dim=1) instead of sum().

still the same
@Tony-Y do you have any other functions to calculate the dice similarity

This issue thread might help you.

Thank you , actually it is an implementation of dice loss not dice similarity

Can I use the same dice coeff function in case of multiclass segmentation?

The linked GitHub issue provides a multi-class dice loss approach.
Would that work for you or are you running into issues with it?