U fb@spddlZddlmZddlmZmZddlm Z ddl m Z dddZ dd d Z dd d ZGd dde jZdS)N)backend) keras_losses k_focal_loss) torch_losses)nncCst|tstdt|dkr|dkr:dd|D}n|}t|t|krftd|dkrzt|||S|dkrt |||Sn"t| d \}}t ||||SdS) aRLoad a loss function based on a config file for the specified framework. Arguments --------- framework : string Which neural network framework to use. loss : dict Dictionary of loss functions to use. Each key is a loss function name, and each entry is a (possibly-empty) dictionary of hyperparameter-value pairs. loss_weights : dict, optional Optional dictionary of weights for loss functions. Each key is a loss function name (same as in the ``loss`` argument), and the corresponding entry is its weight. custom_losses : dict, optional Optional dictionary of Pytorch classes or Keras functions of any user-defined loss functions. Each key is a loss function name, and the corresponding entry is the Python object implementing that loss. zGThe loss description is formatted improperly. See the docs for details.rNcSsi|] }|dqS)r).0krri/home/ec2-user/SageMaker/vegetation-management-remars2022/remars2022-workshop/libs/solaris/nets/losses.py %szget_loss..z4The losses and weights must have the same name keys.keras)pytorchtorchr) isinstancedict TypeErrorlenkeyslistsort ValueErrorkeras_composite_lossTorchCompositeLossitemsget_single_loss) frameworkloss loss_weights custom_lossesweights loss_name loss_dictrrr get_losss     r#cCs|dkrH|dkrtf|S|dk r8||kr8||St|Snr|dkr|dkr|dk rt||krt||St|Sn4|dk r||kr||f|St|f|SdS)Nr focal)rr)lowerrgetrr)rr! params_dictrrrr r8s    rcsfdd}|S)zEWrapper to other loss functions to create keras-compatible composite.c s6tttjfddDdd}|S)Ncs,g|]$\}}|td||qS)r rr r!Z loss_params)r weight_dicty_predy_truerr Vsz;keras_composite_loss..composite..)axis)Ksumflattenstackr)r,r+rrr"r*)r+r,r compositeUs  z'keras_composite_loss..compositer)r"r*rr5rr4r rRsrcs*eZdZdZdfdd ZddZZS)rzComposite loss function.Ncs2t||_fdd|D|_i|_dS)z>Create a composite loss function from a set of pytorch losses.cs i|]\}}|td||qS)rr(r)rrr r esz/TorchCompositeLoss.__init__..N)super__init__r rlossesvalues)selfr"r*r __class__r6r r8as   zTorchCompositeLoss.__init__cCsDd}|jD]0\}}|j||||j|<|||j|7}q|S)Nr)r rr9r:)r;outputstargetsr func_nameweightrrr forwardls zTorchCompositeLoss.forward)NN)__name__ __module__ __qualname____doc__r8rB __classcell__rrr<r r^s r)NN)N)N)numpynpZtensorflow.kerasrr0Z _keras_lossesrrZ _torch_lossesrrrr#rrModulerrrrr s    0