(output, target, smooth=0, activation='softmax')
return loss / num_classes
Calculate Dice Loss for multiple class output.

    Args:
        output (torch.Tensor): Model output of shape (N x C x H x W).
        target (torch.Tensor): Target of shape (N x H x W).
        smooth (float, optional): Smoothing factor. Defaults to 0.
        activation (string, optional): Name of the activation function, softmax or sigmoid. Defaults to 'softmax'.

    Returns:
        torch.Tensor: Loss value.
Calculate Dice Loss for multiple class output.
Calculate Dice Loss for multiple class output .
def multiclass_dice_loss(output, target, smooth=0, activation='softmax'):
    """Calculate Dice Loss for multiple class output.

    Args:
        output (torch.Tensor): Model output of shape (N x C x H x W).
        target (torch.Tensor): Target of shape (N x H x W).
        smooth (float, optional): Smoothing factor. Defaults to 0.
        activation (string, optional): Name of the activation function, softmax or sigmoid. Defaults to 'softmax'.

    Returns:
        torch.Tensor: Loss value.

    """
    if activation == 'softmax':
        activation_nn = torch.nn.Softmax2d()
    elif activation == 'sigmoid':
        activation_nn = torch.nn.Sigmoid()
    else:
        raise NotImplementedError('only sigmoid and softmax are implemented')

    loss = 0
    dice = DiceLoss(smooth=smooth)
    output = activation_nn(output)
    num_classes = output.size(1)
    target.data = target.data.float()
    for class_nr in range(num_classes):
        loss += dice(output[:, class_nr, :, :], target[:, class_nr, :, :])
    return loss / num_classes
def multiclass_dice_loss ( output , target , smooth = 0 , activation = 'softmax' ) : if activation == 'softmax' : activation_nn = torch . nn . Softmax2d ( ) elif activation == 'sigmoid' : activation_nn = torch . nn . Sigmoid ( ) else : raise NotImplementedError ( 'only sigmoid and softmax are implemented' ) loss = 0 dice = DiceLoss ( smooth = smooth ) output = activation_nn ( output ) num_classes = output . size ( 1 ) target . data = target . data . float ( ) for class_nr in range ( num_classes ) : loss += dice ( output [ : , class_nr , : , : ] , target [ : , class_nr , : , : ] ) return loss / num_classes