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

#378 Feature/sg 281 add kd notebook

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:feature/SG-281-add_kd_notebook
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
  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. - ((2. * 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,
  39. apply_sigmoid: bool = True,
  40. smooth: float = 1.,
  41. eps: float = 1e-5):
  42. """
  43. :param apply_sigmoid: Whether to apply sigmoid to the predictions.
  44. :param smooth: laplace smoothing, also known as additive smoothing. The larger smooth value is, closer the dice
  45. coefficient is to 1, which can be used as a regularization effect.
  46. As mentioned in: https://github.com/pytorch/pytorch/issues/1249#issuecomment-337999895
  47. :param eps: epsilon value to avoid inf.
  48. """
  49. super().__init__(apply_softmax=False, ignore_index=None, smooth=smooth, eps=eps, reduce_over_batches=False)
  50. self.apply_sigmoid = apply_sigmoid
  51. def forward(self, predict, target):
  52. if self.apply_sigmoid:
  53. predict = torch.sigmoid(predict)
  54. return super().forward(predict=predict, target=target)
  55. class GeneralizedDiceLoss(DiceLoss):
  56. """
  57. Compute the Generalised Dice loss, contribution of each label is normalized by the inverse of its volume, in order
  58. to deal with class imbalance.
  59. Defined in the paper: "Generalised Dice overlap as a deep learning loss function for highly unbalanced
  60. segmentations"
  61. Args:
  62. smooth (float): default value is 0, smooth laplacian is not recommended to be used with GeneralizedDiceLoss.
  63. because the weighted values to be added are very small.
  64. eps (float): default value is 1e-17, must be a very small value, because weighted `intersection` and
  65. `denominator` are very small after multiplication with `1 / counts ** 2`
  66. """
  67. def __init__(self,
  68. apply_softmax: bool = True,
  69. ignore_index: int = None,
  70. smooth: float = 0.0,
  71. eps: float = 1e-17,
  72. reduce_over_batches: bool = False,
  73. reduction: Union[LossReduction, str] = "mean"
  74. ):
  75. """
  76. :param apply_softmax: Whether to apply softmax to the predictions.
  77. :param smooth: laplace smoothing, also known as additive smoothing. The larger smooth value is, closer the dice
  78. coefficient is to 1, which can be used as a regularization effect.
  79. As mentioned in: https://github.com/pytorch/pytorch/issues/1249#issuecomment-337999895
  80. :param eps: epsilon value to avoid inf.
  81. :param reduce_over_batches: Whether to apply reduction over the batch axis if set True,
  82. default is `False` to average over the classes axis.
  83. :param reduction: Specifies the reduction to apply to the output: `none` | `mean` | `sum`.
  84. `none`: no reduction will be applied.
  85. `mean`: the sum of the output will be divided by the number of elements in the output.
  86. `sum`: the output will be summed.
  87. Default: `mean`
  88. """
  89. super().__init__(apply_softmax=apply_softmax, ignore_index=ignore_index, smooth=smooth, eps=eps,
  90. reduce_over_batches=reduce_over_batches, generalized_metric=True, weight=None,
  91. reduction=reduction)
Discard
Tip!

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