Error in dice loss from torchgeometry

Hi there,

I am trying to implement a dice loss for multi-class segmentation using torchgeometry.losses.DiceLoss(), but I keep getting an error

"return one_hot.scatter_(1, labels.unsqueeze(1), 1.0) + eps RuntimeError: index -1 is out of bounds for dimension 1 with size 3"

I am passing to the dice loss object the network output (torch tensor shape [1,3,388,388] dtype float32) and label (torch tensor [1,388,388] dtype int64) as in documentation

I even did a test:

pred_mask = torch.rand(1, 3, 256, 256)
gt_mask = torch.rand(1, 256, 256).to(torch.int64)

print(pred_mask.shape, pred_mask.dtype)print(gt_mask.shape, gt_mask.dtype)

dice_loss = tgl.dice_loss(pred_mask, gt_mask)

print("Dice Loss: ", dice_loss.item())

and it works, it prints the dice loss for the similar shapes and datatypes

What am I doing wrong in the above case with that error ?

Thanks in advance

Your code works fine but based on the error message it seems your target contains a negative index:

gt_mask[0, 0, 0] = -1
dice_loss = tgl.dice_loss(pred_mask, gt_mask)
# RuntimeError: index -1 is out of bounds for dimension 1 with size 3

and thus fails.

Yes it has negative values. I need to check how label is read, must have some error when reading or converting to int64

Thank you very much for your help.