Skip to content

Commit e8a2579

Browse files
committed
address coderabbit comment
Signed-off-by: Soumya Snigdha Kundu <soumya_snigdha.kundu@kcl.ac.uk>
1 parent 0fc51ea commit e8a2579

1 file changed

Lines changed: 7 additions & 3 deletions

File tree

monai/losses/cldice.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ def __init__(
130130
"""
131131
Args:
132132
iter_: Number of iterations for skeletonization.
133-
smooth: Smoothing parameter.
133+
smooth: Smoothing parameter to avoid division by zero. Defaults to 1.0.
134134
include_background: if False, channel index 0 (background category) is excluded from the calculation.
135135
if the non-background segmentations are small compared to the total image size they can get overwhelmed
136136
by the signal from the background so excluding it in such cases helps convergence.
@@ -158,6 +158,8 @@ def __init__(
158158
raise TypeError(f"other_act must be None or callable but is {type(other_act).__name__}.")
159159
if int(sigmoid) + int(softmax) + int(other_act is not None) > 1:
160160
raise ValueError("Incompatible values: more than 1 of [sigmoid=True, softmax=True, other_act is not None].")
161+
if smooth <= 0:
162+
raise ValueError(f"smooth must be a positive value but got {smooth}.")
161163
self.iter = iter_
162164
self.smooth = smooth
163165
self.include_background = include_background
@@ -220,7 +222,7 @@ def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
220222
tsens = (torch.sum(torch.multiply(skel_true, input), dim=reduce_axis) + self.smooth) / (
221223
torch.sum(skel_true, dim=reduce_axis) + self.smooth
222224
)
223-
cl_dice: torch.Tensor = 1.0 - 2.0 * (tprec * tsens) / (tprec + tsens)
225+
cl_dice: torch.Tensor = 1.0 - 2.0 * (tprec * tsens) / (tprec + tsens + 1e-8)
224226

225227
# Apply reduction
226228
if self.reduction == LossReduction.MEAN.value:
@@ -264,7 +266,7 @@ def __init__(
264266
iter_: Number of iterations for skeletonization, used by clDice.
265267
alpha: Weighing factor for cldice component. Total loss = (1 - alpha) * dice + alpha * cldice.
266268
Defaults to 0.5.
267-
smooth: Smoothing parameter, used by both Dice and clDice.
269+
smooth: Smoothing parameter to avoid division by zero, used by both Dice and clDice. Defaults to 1.0.
268270
include_background: if False, channel index 0 (background category) is excluded from the calculation.
269271
if the non-background segmentations are small compared to the total image size they can get overwhelmed
270272
by the signal from the background so excluding it in such cases helps convergence.
@@ -288,6 +290,8 @@ def __init__(
288290
289291
"""
290292
super().__init__()
293+
if smooth <= 0:
294+
raise ValueError(f"smooth must be a positive value but got {smooth}.")
291295
self.dice = DiceLoss(
292296
include_background=include_background,
293297
to_onehot_y=False,

0 commit comments

Comments
 (0)