lidaryani:

class DiceCoffLoss(nn.Module): def init(self, label_of_interest=1): super(DiceCoffLoss, self).init() self.labelInterest = label_of_interest def forward(self,prediction, segmentation ): “”" inputs are 2d arrays “”" segmentation=torch.autograd.Variable(segmentation) prediction=torch.autograd.Variable(prediction) if prediction.shape != segmentation.shape: raise ValueError(“Shape mismatch between given arrays. prediction %s vs segmentation %s” \ % (str(prediction.shape), str(segmentation.shape))) n_organ_seg = (segmentation==self.labelInterest).sum() n_organ_pred= (prediction == self.labelInterest).sum() denominator = n_organ_pred + n_organ_seg if denominator == 0: return torch.tensor(1.0,requires_grad=True) #mask or predected is empty of interested label iflat = prediction.contiguous().view(-1) tflat = segmentation.contiguous().view(-1) organ_intersection=(iflat==self.labelInterest)(tflat==self.labelInterest) #Subscription operator n_organ_intersection = organ_intersection.sum() dice = ((2.0n_organ_intersection / denominator) ) return torch.tensor(1-dice ,requires_grad=True)


thank for your reply,yes you are right, I did a non-useful work on these two lines.I changed my code as below:
class DiceCoffLoss(nn.Module):

    def __init__(self, label_of_interest=1):
        super(DiceCoffLoss, self).__init__()
        self.labelInterest = label_of_interest

    def forward(self,prediction, segmentation ):
        
        """ inputs are 2d arrays """
    
        if prediction.shape != segmentation.shape:
            raise ValueError("Shape mismatch between given arrays. prediction %s vs segmentation %s" \
                         % (str(prediction.shape), str(segmentation.shape)))

        n_organ_seg =  (segmentation==self.labelInterest).sum()
        n_organ_pred= (prediction == self.labelInterest).sum()
        denominator = n_organ_pred + n_organ_seg
        if denominator == 0:
            return torch.tensor(1.0,requires_grad=True) #mask or predected is empty of interested label
        
        iflat = prediction.contiguous().view(-1)
        tflat = segmentation.contiguous().view(-1)
        organ_intersection=(iflat==self.labelInterest)*(tflat==self.labelInterest) #Subscription operator
        n_organ_intersection = organ_intersection.sum()
        dice = ((2.0*n_organ_intersection / denominator) ) 
        return torch.tensor(1-dice ,requires_grad=True)

I’ve restarted the program so far, nearly 30 epoches have been completed, but the amount of loss has not changed, even in the amount of Epsilon.
Are there any other wrong things?