Skip to content

Commit e9dba63

Browse files
committed
fix: remove redundant mask, move shape check, restore per_component guard
Signed-off-by: Rusheel Sharma <rusheelhere@gmail.com>
1 parent 54d417c commit e9dba63

2 files changed

Lines changed: 6 additions & 10 deletions

File tree

monai/losses/unified_focal_loss.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,11 @@ def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
258258
if orig_pred_ch == 1 and self.ignore_index is not None:
259259
warnings.warn("single channel prediction, `ignore_index` is applied to label-encoded targets.")
260260

261+
if not (self.to_onehot_y and orig_pred_ch != 1):
262+
if not (orig_pred_ch == 1 and y_true.shape[1] == 1):
263+
if y_true.shape != y_pred.shape:
264+
raise ValueError(f"ground truth has different shape ({y_true.shape}) from input ({y_pred.shape})")
265+
261266
# Preserve original target before any channel conversions so sentinel ignore
262267
# values (e.g., 255) are detected correctly on label-encoded inputs.
263268
original_y_true = y_true
@@ -266,15 +271,6 @@ def forward(self, y_pred: torch.Tensor, y_true: torch.Tensor) -> torch.Tensor:
266271
if y_pred.shape[1] == 1:
267272
y_pred = torch.cat([1 - y_pred, y_pred], dim=1)
268273

269-
# Early shape validation: if we are not about to convert `y_true` to one-hot,
270-
# ensure shapes already match before any further tensor value operations.
271-
# Allow the common binary case where `y_pred` is single-channel (expanded later)
272-
# and `y_true` is label-encoded single-channel.
273-
if not (self.to_onehot_y and orig_pred_ch != 1):
274-
if not (orig_pred_ch == 1 and y_true.shape[1] == 1):
275-
if y_true.shape != y_pred.shape:
276-
raise ValueError(f"ground truth has different shape ({y_true.shape}) from input ({y_pred.shape})")
277-
278274
if self.to_onehot_y and orig_pred_ch != 1:
279275
if self.ignore_index is not None and (self.ignore_index < 0 or self.ignore_index >= self.num_classes):
280276
# Replace sentinel ignore_index with a valid class before one_hot

monai/metrics/meandice.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -441,7 +441,7 @@ def __call__(self, y_pred: torch.Tensor, y: torch.Tensor) -> torch.Tensor | tupl
441441
# Create global mask for ignored voxels if ignore_index is set
442442
mask = create_ignore_mask(y, self.ignore_index)
443443

444-
first_ch = 0 if self.include_background else 1
444+
first_ch = 0 if self.include_background and not self.per_component else 1
445445
data = []
446446
for b in range(y_pred.shape[0]):
447447
if self.per_component:

0 commit comments

Comments
 (0)