Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- Fixed `HausdorffDistance` raising a `RuntimeError` when a class is absent from both predictions and target, which now returns `nan` for that class in the functional and is skipped in the module's running mean ([#3682](https://github.com/Lightning-AI/torchmetrics/issues/3682))

- Fixed `BootStrapper` computing the `quantile` over all outputs at once instead of per output for metrics with non-scalar results ([#XXXX](https://github.com/Lightning-AI/torchmetrics/pull/XXXX))

- Fixed `Metric` syncing deadlocking for `dist_reduce_fx=None` list states when ranks hold a different number of entries, which now raises an error instead ([#3503](https://github.com/Lightning-AI/torchmetrics/pull/3503))
Expand Down
11 changes: 9 additions & 2 deletions src/torchmetrics/functional/segmentation/hausdorff_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ def hausdorff_distance(
or ``"mixed"`` for one one-hot encoded and one index tensor

Returns:
Hausdorff Distance for each class and batch element
Hausdorff Distance for each class and batch element. If a class is absent from both ``preds`` and ``target``
of a sample the distance is undefined and ``nan`` is returned for that entry (``inf`` is returned if the class
is only present in one of them).

Example:
>>> from torch import randint
Expand Down Expand Up @@ -103,5 +105,10 @@ def hausdorff_distance(
spacing=spacing,
symmetric=not directed,
)
distances[b, c] = torch.max(dist) if directed else torch.max(dist[0].max(), dist[1].max()) # type: ignore
edge_dists = (dist,) if directed else dist # type: ignore[assignment]
if all(d.numel() == 0 for d in edge_dists):
# class is absent from both preds and target, so the distance is undefined
distances[b, c] = torch.nan
else:
distances[b, c] = torch.stack([d.max() for d in edge_dists if d.numel() > 0]).max()
return distances
5 changes: 3 additions & 2 deletions src/torchmetrics/segmentation/hausdorff_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,8 +120,9 @@ def update(self, preds: Tensor, target: Tensor) -> None:
directed=self.directed,
input_format=self.input_format,
)
self.score += score.sum()
self.total += score.numel()
# classes absent from both preds and target give nan and are excluded from the running mean
self.score += score.nansum()
self.total += (~score.isnan()).sum()

def compute(self) -> Tensor:
"""Compute final Hausdorff distance over states."""
Expand Down
33 changes: 33 additions & 0 deletions tests/unittests/segmentation/test_hausdorff_distance.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,3 +152,36 @@ def test_hausdorff_distance_non_square_input():
reference = monai_hausdorff_distance(preds, target)

assert torch.allclose(result, reference.to(result))


def _absent_class_inputs():
"""Index masks with 3 classes where class 2 appears in neither preds nor target."""
target = torch.zeros(1, 8, 8, dtype=torch.long)
target[0, 2:5, 2:5] = 1
preds = torch.zeros(1, 8, 8, dtype=torch.long)
preds[0, 2:6, 2:5] = 1
return preds, target


@pytest.mark.parametrize("directed", [True, False])
def test_hausdorff_distance_class_absent_from_both(directed):
"""Test that a class absent from preds and target gives nan instead of raising an error (issue #3682)."""
preds, target = _absent_class_inputs()
res = hausdorff_distance(preds, target, num_classes=3, input_format="index", directed=directed)
assert res.shape == (1, 2)
assert res[0, 0] == 1.0
assert torch.isnan(res[0, 1])

# class present in only one of preds and target still gives inf
preds[0, 7, 7] = 2
res = hausdorff_distance(preds, target, num_classes=3, input_format="index", directed=directed)
assert res[0, 0] == 1.0
assert torch.isinf(res[0, 1])


def test_hausdorff_distance_module_skips_absent_class():
"""Test that the module ignores classes absent from both preds and target in the running mean."""
preds, target = _absent_class_inputs()
metric = HausdorffDistance(num_classes=3, input_format="index")
metric.update(preds, target)
assert metric.compute() == 1.0