Skip to content

Commit 8526ca7

Browse files
committed
Validate calibration loss weights
Signed-off-by: Theo Barfoot <theo.barfoot@gmail.com>
1 parent 5384817 commit 8526ca7

2 files changed

Lines changed: 15 additions & 4 deletions

File tree

monai/losses/calibration.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,8 @@ def __init__(
109109
if class_weight is not None:
110110
if class_weight.ndim > 1:
111111
raise ValueError("weight must be a scalar or a one-dimensional sequence.")
112+
if not torch.all(torch.isfinite(class_weight)):
113+
raise ValueError("weight must contain only finite values.")
112114
if torch.any(class_weight < 0):
113115
raise ValueError("the value/values of the `weight` should be no less than 0.")
114116

@@ -353,8 +355,8 @@ def __init__(
353355
right: bool = False,
354356
ignore_empty_classes: bool = True,
355357
) -> None:
356-
if empty_weight < 0:
357-
raise ValueError(f"empty_weight must be >= 0, got {empty_weight}.")
358+
if not 0 <= empty_weight < float("inf"):
359+
raise ValueError(f"empty_weight must be finite and >= 0, got {empty_weight}.")
358360
super().__init__(
359361
num_bins,
360362
include_background,

tests/losses/test_calibration_loss.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,14 @@ def test_invalid_options_and_shapes(self):
159159
loss_type(other_act=1) # type: ignore[arg-type]
160160
with self.assertRaises(ValueError):
161161
loss_type(weight=[1.0, -1.0])
162+
for invalid_weight in (float("nan"), float("inf"), -float("inf")):
163+
with self.subTest(invalid_weight=invalid_weight):
164+
with self.assertRaises(ValueError):
165+
loss_type(weight=invalid_weight)
166+
with self.assertRaises(ValueError):
167+
loss_type(weight=[1.0, invalid_weight])
168+
with self.assertRaises(ValueError):
169+
loss_type(weight=torch.tensor([invalid_weight]))
162170
with self.assertRaises(ValueError):
163171
loss_type(weight=[[1.0]])
164172
with self.assertRaises(ValueError):
@@ -171,8 +179,9 @@ def test_invalid_options_and_shapes(self):
171179
loss_type()(torch.ones(1, 2), torch.ones(1, 2))
172180
with self.assertRaises(TypeError):
173181
loss_type()(torch.ones(1, 2, 2, dtype=torch.int64), torch.ones(1, 2, 2))
174-
with self.assertRaises(ValueError):
175-
SoftL1ACELoss(empty_weight=-1)
182+
for invalid_empty_weight in (-1.0, float("nan"), float("inf"), -float("inf")):
183+
with self.subTest(invalid_empty_weight=invalid_empty_weight), self.assertRaises(ValueError):
184+
SoftL1ACELoss(empty_weight=invalid_empty_weight)
176185

177186
def test_single_channel_warnings(self):
178187
prediction = torch.tensor([[[0.2, 0.8]]])

0 commit comments

Comments
 (0)