[e9500f]: / pathflowai / __pycache__ / losses.cpython-36.pyc

Download this file

95 lines (93 with data), 11.0 kB

3

░ĚA],Ń@sVdZddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZddlm
Z
mZddljjZddlmZddlmZdefdd	äZGd
dädeâZdd
äZGddädejâZGddädejâZe
e	dťddäZe
eedťddäZ e
edťddäZ!d*e
edťddäZ"d+e
edťddäZ#e
e$e
d ťd!d"äZ%ej&ej&d#ťd$d%äZ'Gd&d'äd'âZ(Gd(d)äd)âZ)dS),zÉ
losses.py
=======================
Some additional loss functions that can be called using the pipeline, some of which still to be implemented.
ÚN)┌Any┌Callable┌Iterable┌List┌Set┌Tuple┌TypeVar┌Union)┌Tensor┌einsum)┌distance_transform_edt)┌nn┌cCs|s||âédS)z░https://raw.githubusercontent.com/inferno-pytorch/inferno/0561e8a95cde6bfc5e10a3609841b7b0ca5b03ca/inferno/utils/exceptions.py
	Like assert, but with arbitrary exception types.Nę)┌	condition┌message┌exception_typerr˙B/Users/joshualevy/Documents/GitHub/PathFlowAI/pathflowai/losses.py┌assert_src@seZdZdS)┌
ShapeErrorN)┌__name__┌
__module__┌__qualname__rrrrrsrcCspt|jâdkdj|jââtâ|jdâ}tt|jâââ}|d|d|d<|d<|j|Äjâ}|j	|dâ}|S)aŹ
	https://raw.githubusercontent.com/inferno-pytorch/inferno/0561e8a95cde6bfc5e10a3609841b7b0ca5b03ca/inferno/utils/torch_utils.py
	Flattens a tensor or a variable such that the channel axis is first and the sample axis
	is second. The shapes are transformed as follows:
		(N, C, H, W) --> (C, N * H * W)
		(N, C, D, H, W) --> (C, N * D * H * W)
		(N, C) --> (C, N)
	The input must be atleast 2d.
	Úz9Tensor or variable must be atleast 2D. Got one of dim {}.ÚrÚ    )
r┌dim┌formatr┌size┌list┌range┌permute┌
contiguous┌view)┌input_┌num_channels┌permute_axes┌permuted┌	flattenedrrr┌flatten_sampless

r)cs*eZdZdZd	çfddä	ZddäZçZS)
┌GeneralizedDiceLossaé
	https://raw.githubusercontent.com/inferno-pytorch/inferno/0561e8a95cde6bfc5e10a3609841b7b0ca5b03ca/inferno/extensions/criteria/set_similarity_measures.py
	Computes the scalar Generalized Dice Loss defined in https://arxiv.org/abs/1707.03237

	This version works for multiple classes and expects predictions for every class (e.g. softmax output) and
	one-hot targets for every class.
	NFšŹÝÁá¸Ă░>cs0tt|âjâ|jd|â||_||_||_dS)N┌weight)┌superr*┌__init__┌register_buffer┌channelwise┌eps┌add_softmax)┌selfr,r0r1r2)┌	__class__rrr.:s
zGeneralizedDiceLoss.__init__c
Csé|jâ|jâksté|jr(tj|ddŹ}|js¬t|â}t|âjâ}|jdâ}d||j	|j
dŹ}||jdâ|jâ}||jd
â|jâ}dd||j	|j
dŹ}nďddä}||â}||â}|jdâ}d||j	|j
dŹ}||jdâ|jdâ}||jdâ|jdâ}dd||j	|j
dŹ}	|jdk	Érv|	jâd	kÉrP|	j
dâ}	|jjâ|	jâkÉsltd
âé|j|	}	|	jâ}|S)a
		input: torch.FloatTensor or torch.cuda.FloatTensor
		target:     torch.FloatTensor or torch.cuda.FloatTensor

		Expected shape of the inputs:
			- if not channelwise: (batch_size, nb_classes, ...)
			- if channelwise:     (batch_size, nb_channels, nb_classes, ...)
		r)rg­?)┌ming@cSs||jâ}|dksté|jdâ}|jdâ}tt|ââ}|d|d|d|d<|d<|d<|j|Äjâ}|j||dâ}|S)NÚrrrr)r┌AssertionErrorrrr r!r"r#)┌tensorZ
tensor_dimr%┌num_classesr&r'r(rrr┌flatten_and_preserve_channels]s

(zBGeneralizedDiceLoss.forward.<locals>.flatten_and_preserve_channelsNrzy`weight` should have shape (nb_channels, ),
					   `target` should have shape (batch_size, nb_channels, nb_classes, ...)rrrrrrrr)rr7r2┌F┌softmaxr0r)┌float┌sum┌clampr1r,r┌squeeze)
r3┌input┌targetZsum_targetsZ
class_weigths┌numer┌denom┌lossr:Zchannelwise_lossrrr┌forwardAs6	




zGeneralizedDiceLoss.forward)NFr+F)rrr┌__doc__r.rF┌
__classcell__rr)r4rr*2sr*cs*eZdZdZdçfddä	Zdd	äZçZS)┌	FocalLossa8
	# https://raw.githubusercontent.com/Hsuxu/Loss_ToolBox-PyTorch/master/FocalLoss/FocalLoss.py
	This is a implementation of Focal Loss with smooth label cross entropy supported which is proposed in
	'Focal Loss for Dense Object Detection. (https://arxiv.org/abs/1708.02002)'
		Focal_Loss= -1*alpha*(1-pt)*log(pt)
	:param num_class:
	:param alpha: (tensor) 3D or 4D the scalar factor for this criterion
	:param gamma: (float,double) gamma > 0 reduces the relative loss for well-classified examples (p>0.5) putting more
					focus on hard misclassified example
	:param smooth: (float,double) smooth value when cross entropy
	:param balance_index: (int) balance class index, should be specific when alpha is float
	:param size_average: (bool, optional) By default, the losses are averaged over each loss element in the batch.
	NrrTcstt|âjâ||_||_||_||_||_|jdkrHtj	|jdâ|_nĺt
|jttj
fârśt|jâ|jksntétj|âj|jdâ|_|j|jjâ|_nBt
|jtârĎtj	|jdâ}|d|j}|j||<||_ntdâé|jdk	Ér|jdksŘ|jdkÉrtdâédS)NrzNot support alpha typerg­?zsmooth value should be in [0,1])r-rIr.┌	num_class┌alpha┌gamma┌smooth┌size_average┌torch┌ones┌
isinstancer┌np┌ndarray┌lenr7┌FloatTensorr#r>r=┌	TypeError┌
ValueError)r3rJrKrLZ
balance_indexrMrN)r4rrr.ôs*

zFocalLoss.__init__cCsJ|jâdkrJ|j|jdâ|jdâdâ}|jdddâjâ}|jd|jdââ}|jd	dâ}d}|j}|jtjkrx|jtjâ}|j	âj
â}tj|jdâ|j
âjâ}|jd|dâ}|j|jkr┬|j|jâ}|jrŔtj||j|j
dd|jâ}||jdâ|}|jâ}|j}	||}d
|tjd||	â|}
|jÉr>|
jâ}
n|
jâ}
|
S)Nrrrg╗ŻÎ┘▀|█=g­?rrrrr)rr#rr!r"rK┌devicerA┌to┌cpu┌longrOrUrJ┌zero_┌scatter_rMr?r>┌logrL┌powrN┌mean)r3┌logitrB┌epsilonrK┌idxZone_hot_key┌ptZlogptrLrErrrrFşs4
zFocalLoss.forwardr)NrrNT)rrrrGr.rFrHrr)r4rrIäs
rI)┌a┌returncCsttj|jââjââS)zGhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/utils.py)┌setrO┌uniquerZ┌numpy)rerrr┌uniq┌srj)re┌subrfcCst|âj|âS)zGhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/utils.py)rj┌issubset)rerkrrr┌ssetŮsrmcCstj||âjâS)zGhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/utils.py)rO┌eq┌all)re┌brrrrnŃsrnr)┌trfcCs.|j|âjtjâ}tj|tjdŹ}tj||âS)zGhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/utils.py)┌dtype)r>┌typerO┌float32┌	ones_like┌allclose)rq┌axis┌_sumZ_onesrrr┌simplexŔsrycCst||âot|ddgâS)zGhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/utils.pyrr)ryrm)rqrwrrr┌one_hotţsrz)┌seg┌CrfcsŐtłjâdkrłjddŹëtłtt|âââs0téłj\}}}tjçfddät|âDâddŹj	tj
â}|j||||fksztét|âsćté|S)zGhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/utils.pyrr)rcsg|]}ł|kĹqSrr)┌.0┌c)r{rr˙
<listcomp>˙sz!class2one_hot.<locals>.<listcomp>r)rT┌shape┌	unsqueezermrr r7rO┌stackrs┌int32rz)r{r|rp┌w┌h┌resr)r{r┌
class2one_hot˛s(rç)r{rfcCs|ttj|âddŹstét|â}tj|â}xNt|âD]B}||jtj	â}|j
âr2|}t|â|t|âd|||<q2W|S)zGhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/utils.pyr)rwr)rzrOr
r7rTrR┌
zeros_liker ┌astype┌bool┌any┌distance)r{r|rćr~ZposmaskZnegmaskrrr┌one_hot2dists
$rŹc@s,eZdZdZddäZeeeedťddäZdS)┌SurfaceLosszHhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/losses.pycKs&|d|_td|jjŤd|ŤŁâdS)N┌idczInitialized z with )rĆ┌printr4r)r3┌kwargsrrrr.s
zSurfaceLoss.__init__)┌probs┌	dist_maps┌_rfcCsjt|âstét|âsté|ddů|jdfjtjâ}|ddů|jdfjtjâ}td||â}|jâ}|S)N.zbcwh,bcwh->bcwh)	ryr7rzrĆrsrOrtrr`)r3rĺrôrö┌pc┌dcZ	multipledrErrr┌__call__szSurfaceLoss.__call__N)rrrrGr.r
rŚrrrrrÄsrÄc@s,eZdZdZddäZeeeedťddäZdS)┌GeneralizedDicezHhttps://raw.githubusercontent.com/LIVIAETS/surface-loss/master/losses.pycKs&|d|_td|jjŤd|ŤŁâdS)NrĆzInitialized z with )rĆrÉr4r)r3rĹrrrr.$s
zGeneralizedDice.__init__)rĺrBrörfcCs┬t|ârt|âsté|ddů|jdfjtjâ}|ddů|jdfjtjâ}dtd|âjtjâdd}|td||â}|td|âtd|â}ddtd|âdtd|âd}	|	jâ}
|
S)N.rzbcwh->bcg╗ŻÎ┘▀|█=rz
bcwh,bcwh->bczbc->b)ryr7rĆrsrOrtrr`)r3rĺrBrörĽ┌tcrä┌intersection┌unionZdividedrErrrrŚ)s$zGeneralizedDice.__call__N)rrrrGr.r
rŚrrrrrś"srś)r)r)*rGrOrirR┌typingrrrrrrrr	r
rZtorch.nn.functionalr
┌
functionalr;Z
scipy.ndimagerrîr7rrWrr)┌Moduler*rIrjrŐrmrnryrz┌intrçrSrŹrÄrśrrrr┌<module>s((RV