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: 1 addition & 1 deletion src/torchmetrics/aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def _cast_and_nan_check_input(
raise ValueError(f"`nan_strategy` shall be float but you pass {self.nan_strategy}")
x[nans | nans_weight] = self.nan_strategy
weight[nans | nans_weight] = 1
else:
elif weight is None:
weight = torch.ones_like(x)
return x.to(self.dtype), weight.to(self.dtype)

Expand Down
8 changes: 8 additions & 0 deletions tests/unittests/bases/test_aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,14 @@ def test_error_on_wrong_nan_strategy(metric_class):
metric_class(nan_strategy=[])


def test_disable_preserves_weight():
"""`nan_strategy="disable"` should only skip nan checks, not also discarding `weight`."""
metric = MeanMetric(nan_strategy="disable")
metric.update(torch.tensor(1.0), weight=torch.tensor(3.0))
metric.update(torch.tensor(0.0), weight=torch.tensor(1.0))
assert torch.allclose(metric.compute(), torch.tensor(0.75))


@pytest.mark.skipif(not hasattr(torch, "broadcast_to"), reason="PyTorch <1.8 does not have broadcast_to")
@pytest.mark.parametrize(
("weights", "expected"), [(1, 11.5), (torch.ones(2, 1, 1), 11.5), (torch.tensor([1, 2]).reshape(2, 1, 1), 13.5)]
Expand Down