Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix getitem for metric collection when prefix/postfix is set #2430

Merged
merged 17 commits into from
Apr 17, 2024
Merged
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- Fix getitem for metric collection when prefix/postfix is set ([#2430](https://github.com/Lightning-AI/torchmetrics/pull/2430))


- Fixed axis names with Precision-Recall curve ([#2462](https://github.com/Lightning-AI/torchmetrics/pull/2462))


Expand Down
4 changes: 4 additions & 0 deletions src/torchmetrics/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,10 @@ def __getitem__(self, key: str, copy_state: bool = True) -> Metric:

"""
self._compute_groups_create_state_ref(copy_state)
if self.prefix:
key = key.removeprefix(self.prefix)
if self.postfix:
key = key.removesuffix(self.postfix)
return self._modules[key]

@staticmethod
Expand Down
6 changes: 6 additions & 0 deletions tests/unittests/bases/test_collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
MultilabelAveragePrecision,
)
from torchmetrics.utilities.checks import _allclose_recursive
from torchmetrics.utilities.imports import _TORCH_GREATER_EQUAL_2_0

from unittests._helpers import seed_all
from unittests._helpers.testers import DummyMetricDiff, DummyMetricMultiOutputDict, DummyMetricSum
Expand Down Expand Up @@ -150,6 +151,7 @@ def test_metric_collection_args_kwargs(tmpdir):
assert metric_collection["DummyMetricDiff"].x == -20


@pytest.mark.skipif(not _TORCH_GREATER_EQUAL_2_0, reason="Test requires torch 2.0 or higher")
@pytest.mark.parametrize(
("prefix", "postfix"),
[
Expand Down Expand Up @@ -204,6 +206,10 @@ def test_metric_collection_prefix_postfix_args(prefix, postfix):
for name in names:
assert f"new_prefix_{name}_new_postfix" in out, "postfix argument not working as intended with clone method"

keys = list(new_metric_collection.keys())
for k in keys:
assert new_metric_collection[k] # check that the keys are valid even with prefix and postfix


def test_metric_collection_repr():
"""Test MetricCollection."""
Expand Down
Loading