losses.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. # !/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # ==============================================================================
  4. #
  5. # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. #
  19. # ==============================================================================
  20. import tensorflow as tf
  21. __all__ = ["regularization_l2loss", "reconstruction_l2loss", "reconstruction_x_entropy", "adaptive_loss"]
  22. def regularization_l2loss(weight_decay):
  23. def loss_filter_fn(name):
  24. """we don't need to compute L2 loss for BN"""
  25. return all(
  26. [tensor_name not in name.lower() for tensor_name in ["batchnorm", "batch_norm", "batch_normalization"]]
  27. )
  28. filtered_params = [tf.cast(v, tf.float32) for v in tf.trainable_variables() if loss_filter_fn(v.name)]
  29. if len(filtered_params) != 0:
  30. l2_loss_per_vars = [tf.nn.l2_loss(v) for v in filtered_params]
  31. l2_loss = tf.multiply(tf.add_n(l2_loss_per_vars), weight_decay)
  32. else:
  33. l2_loss = tf.zeros(shape=(), dtype=tf.float32)
  34. return l2_loss
  35. def reconstruction_l2loss(y_pred, y_true):
  36. reconstruction_err = tf.subtract(y_pred, y_true)
  37. return tf.reduce_mean(tf.nn.l2_loss(reconstruction_err), name='reconstruction_loss_l2_loss')
  38. def reconstruction_x_entropy(y_pred, y_true, from_logits=False):
  39. return tf.reduce_mean(tf.keras.losses.binary_crossentropy(y_true=y_true, y_pred=y_pred, from_logits=from_logits))
  40. def dice_coe(y_pred, y_true, loss_type='jaccard', smooth=1.):
  41. """Soft dice (Sørensen or Jaccard) coefficient for comparing the similarity
  42. of two batch of data, usually be used for binary image segmentation
  43. i.e. labels are binary. The coefficient between 0 to 1, 1 means totally match.
  44. Parameters
  45. -----------
  46. y_true : Tensor
  47. A distribution with shape: [batch_size, ....], (any dimensions).
  48. y_pred : Tensor
  49. The target distribution, format the same with `output`.
  50. loss_type : str
  51. ``jaccard`` or ``sorensen``, default is ``jaccard``.
  52. smooth : float
  53. This small value will be added to the numerator and denominator.
  54. - If both output and target are empty, it makes sure dice is 1.
  55. - If either output or target are empty (all pixels are background),
  56. dice = ```smooth/(small_value + smooth)``,
  57. then if smooth is very small, dice close to 0 (even the image values lower than the threshold),
  58. so in this case, higher smooth can have a higher dice.
  59. References
  60. -----------
  61. - `Wiki-Dice <https://en.wikipedia.org/wiki/Sørensen–Dice_coefficient>`__
  62. """
  63. y_true_f = tf.layers.flatten(y_true)
  64. y_pred_f = tf.layers.flatten(y_pred)
  65. intersection = tf.reduce_sum(y_true_f * y_pred_f)
  66. if loss_type == 'jaccard':
  67. union = tf.reduce_sum(tf.square(y_pred_f)) + tf.reduce_sum(tf.square(y_true_f))
  68. elif loss_type == 'sorensen':
  69. union = tf.reduce_sum(y_pred_f) + tf.reduce_sum(y_true_f)
  70. else:
  71. raise ValueError("Unknown `loss_type`: %s" % loss_type)
  72. return (2. * intersection + smooth) / (union + smooth)
  73. def adaptive_loss(y_pred, y_pred_logits, y_true, switch_at_threshold=0.3, loss_type='jaccard'):
  74. dice_loss = 1 - dice_coe(y_pred=y_pred, y_true=y_true, loss_type=loss_type, smooth=1.)
  75. return tf.cond(
  76. dice_loss < switch_at_threshold,
  77. true_fn=lambda: dice_loss,
  78. false_fn=lambda: reconstruction_x_entropy(y_pred=y_pred_logits, y_true=y_true, from_logits=True)
  79. )