68 lines (67 with data), 10.0 kB
B
A®eÃ. ã @ sø d dl Z d dlm mZ d dl mZ d dlmZ d dlmZm Z m
Z
dddZG dd d ejZ
G d
d dejZG dd
d
ejZG dd deZG dd deZG dd dejZG dd dejZG dd dej Zdd Zdd Zdd ZdS )é N)Únn)ÚVariable)ÚMSELossÚSmoothL1LossÚL1Lossçíµ ÷ư>c C s~ | ¡ | ¡ kstdt| } t|}| ¡ }| | d¡}|dk rN|| }| | d¡|| d¡ }d||j|d S )aÓ
Computes DiceCoefficient as defined in https://arxiv.org/abs/1606.04797 given a multi channel input and target.
Assumes the input is a normalized probability, e.g. a result of Sigmoid or Softmax function.
Args:
input (torch.Tensor): NxCxSpatial input tensor
target (torch.Tensor): NxCxSpatial target tensor
epsilon (float): prevents division by zero
weight (torch.Tensor): Cx1 tensor of weight per channel/class
z-'input' and 'target' must have the same shapeéÿÿÿÿNé )Úmin)ÚsizeÚAssertionErrorÚflattenÚfloatÚsumÚclamp)ÚinputÚtargetÚepsilonÚweightÚ intersectÚdenominator© r úC/Users/hanxuegu/Documents/Documents/bone/bone_paper_codes/losses.pyÚcompute_per_channel_dice s
r c s( e Zd ZdZ fddZdd Z ZS )Ú_MaskingLossWrapperzv
Loss wrapper which prevents the gradient of the loss to be computed where target is equal to `ignore_index`.
c s. t t| ¡ |d k std|| _|| _d S )Nzignore_index cannot be None)Úsuperr Ú__init__r ÚlossÚignore_index)Úselfr r )Ú __class__r r r ) s z_MaskingLossWrapper.__init__c C s2 | ¡ | j¡}d|_|| }|| }| ||¡S )NF)ÚcloneÚne_r Ú
requires_gradr )r r r Úmaskr r r Úforward/ s
z_MaskingLossWrapper.forward)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r r% Ú
__classcell__r r )r r r $ s r c s* e Zd ZdZd fdd Zdd Z ZS )ÚSkipLastTargetChannelWrapperz>
Loss wrapper which removes additional target channel
Fc s t t| ¡ || _|| _d S )N)r r+ r r Úsqueeze_channel)r r r, )r r r r A s z%SkipLastTargetChannelWrapper.__init__c C sL | d¡dkstd|d d
d d
df }| jr@tj|dd}| ||¡S )Né zFTarget tensor has a singleton channel dimension, cannot remove channelr .)Údim)r r r, ÚtorchÚsqueezer )r r r r r r r% F s
z$SkipLastTargetChannelWrapper.forward)F)r&