Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

#609 Ci fix

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/infra-000_ci
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
  1. from typing import Union
  2. import torch
  3. from super_gradients.common.abstractions.abstract_logger import get_logger
  4. from super_gradients.training.losses.loss_utils import LossReduction
  5. from super_gradients.training.losses.structure_loss import AbstarctSegmentationStructureLoss
  6. logger = get_logger(__name__)
  7. class DiceLoss(AbstarctSegmentationStructureLoss):
  8. """
  9. Compute average Dice loss between two tensors, It can support both multi-classes and binary tasks.
  10. Defined in the paper: "V-Net: Fully Convolutional Neural Networks for Volumetric Medical Image Segmentation"
  11. """
  12. def _calc_numerator_denominator(self, labels_one_hot, predict):
  13. """
  14. Calculate dice metric's numerator and denominator.
  15. :param labels_one_hot: target in one hot format. shape: [BS, num_classes, img_width, img_height]
  16. :param predict: predictions tensor. shape: [BS, num_classes, img_width, img_height]
  17. :return:
  18. numerator = intersection between predictions and target. shape: [BS, num_classes, img_width, img_height]
  19. denominator = sum of predictions and target areas. shape: [BS, num_classes, img_width, img_height]
  20. """
  21. numerator = labels_one_hot * predict
  22. denominator = labels_one_hot + predict
  23. return numerator, denominator
  24. def _calc_loss(self, numerator, denominator):
  25. """
  26. Calculate dice loss.
  27. All tensors are of shape [BS] if self.reduce_over_batches else [num_classes].
  28. :param numerator: intersection between predictions and target.
  29. :param denominator: total number of pixels of prediction and target.
  30. """
  31. loss = 1.0 - ((2.0 * numerator + self.smooth) / (denominator + self.eps + self.smooth))
  32. return loss
  33. class BinaryDiceLoss(DiceLoss):
  34. """
  35. Compute Dice Loss for binary class tasks (1 class only).
  36. Except target to be a binary map with 0 and 1 values.
  37. """
  38. def __init__(self, apply_sigmoid: bool = True, smooth: float = 1.0, eps: float = 1e-5):
  39. """
  40. :param apply_sigmoid: Whether to apply sigmoid to the predictions.
  41. :param smooth: laplace smoothing, also known as additive smoothing. The larger smooth value is, closer the dice
  42. coefficient is to 1, which can be used as a regularization effect.
  43. As mentioned in: https://github.com/pytorch/pytorch/issues/1249#issuecomment-337999895
  44. :param eps: epsilon value to avoid inf.
  45. """
  46. super().__init__(apply_softmax=False, ignore_index=None, smooth=smooth, eps=eps, reduce_over_batches=False)
  47. self.apply_sigmoid = apply_sigmoid
  48. def forward(self, predict, target):
  49. if self.apply_sigmoid:
  50. predict = torch.sigmoid(predict)
  51. return super().forward(predict=predict, target=target)
  52. class GeneralizedDiceLoss(DiceLoss):
  53. """
  54. Compute the Generalised Dice loss, contribution of each label is normalized by the inverse of its volume, in order
  55. to deal with class imbalance.
  56. Defined in the paper: "Generalised Dice overlap as a deep learning loss function for highly unbalanced
  57. segmentations"
  58. Args:
  59. smooth (float): default value is 0, smooth laplacian is not recommended to be used with GeneralizedDiceLoss.
  60. because the weighted values to be added are very small.
  61. eps (float): default value is 1e-17, must be a very small value, because weighted `intersection` and
  62. `denominator` are very small after multiplication with `1 / counts ** 2`
  63. """
  64. def __init__(
  65. self,
  66. apply_softmax: bool = True,
  67. ignore_index: int = None,
  68. smooth: float = 0.0,
  69. eps: float = 1e-17,
  70. reduce_over_batches: bool = False,
  71. reduction: Union[LossReduction, str] = "mean",
  72. ):
  73. """
  74. :param apply_softmax: Whether to apply softmax to the predictions.
  75. :param smooth: laplace smoothing, also known as additive smoothing. The larger smooth value is, closer the dice
  76. coefficient is to 1, which can be used as a regularization effect.
  77. As mentioned in: https://github.com/pytorch/pytorch/issues/1249#issuecomment-337999895
  78. :param eps: epsilon value to avoid inf.
  79. :param reduce_over_batches: Whether to apply reduction over the batch axis if set True,
  80. default is `False` to average over the classes axis.
  81. :param reduction: Specifies the reduction to apply to the output: `none` | `mean` | `sum`.
  82. `none`: no reduction will be applied.
  83. `mean`: the sum of the output will be divided by the number of elements in the output.
  84. `sum`: the output will be summed.
  85. Default: `mean`
  86. """
  87. super().__init__(
  88. apply_softmax=apply_softmax,
  89. ignore_index=ignore_index,
  90. smooth=smooth,
  91. eps=eps,
  92. reduce_over_batches=reduce_over_batches,
  93. generalized_metric=True,
  94. weight=None,
  95. reduction=reduction,
  96. )
Discard
Tip!

Press p or to see the previous file or, n or to see the next file