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

#970 Update YoloNASQuickstart.md

Merged
Ghost merged 1 commits into Deci-AI:master from deci-ai:bugfix/SG-000_fix_readme_yolonas_snippets
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, Tuple
  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: torch.tensor, predict: torch.tensor) -> Tuple[torch.tensor, torch.tensor]:
  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: torch.tensor, denominator: torch.tensor) -> torch.tensor:
  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: torch.tensor, target: torch.tensor) -> torch.tensor:
  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. :param smooth: default value is 0, smooth laplacian is not recommended to be used with GeneralizedDiceLoss.
  59. because the weighted values to be added are very small.
  60. :param eps: default value is 1e-17, must be a very small value, because weighted `intersection` and
  61. `denominator` are very small after multiplication with `1 / counts ** 2`
  62. """
  63. def __init__(
  64. self,
  65. apply_softmax: bool = True,
  66. ignore_index: int = None,
  67. smooth: float = 0.0,
  68. eps: float = 1e-17,
  69. reduce_over_batches: bool = False,
  70. reduction: Union[LossReduction, str] = "mean",
  71. ):
  72. """
  73. :param apply_softmax: Whether to apply softmax to the predictions.
  74. :param smooth: laplace smoothing, also known as additive smoothing. The larger smooth value is, closer the dice
  75. coefficient is to 1, which can be used as a regularization effect.
  76. As mentioned in: https://github.com/pytorch/pytorch/issues/1249#issuecomment-337999895
  77. :param eps: epsilon value to avoid inf.
  78. :param reduce_over_batches: Whether to apply reduction over the batch axis if set True,
  79. default is `False` to average over the classes axis.
  80. :param reduction: Specifies the reduction to apply to the output: `none` | `mean` | `sum`.
  81. `none`: no reduction will be applied.
  82. `mean`: the sum of the output will be divided by the number of elements in the output.
  83. `sum`: the output will be summed.
  84. Default: `mean`
  85. """
  86. super().__init__(
  87. apply_softmax=apply_softmax,
  88. ignore_index=ignore_index,
  89. smooth=smooth,
  90. eps=eps,
  91. reduce_over_batches=reduce_over_batches,
  92. generalized_metric=True,
  93. weight=None,
  94. reduction=reduction,
  95. )
Discard
Tip!

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