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 prefix/postfix interaction between MetricCollection and ClasswiseWrapper #1918

Merged
merged 8 commits into from
Jul 25, 2023
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Fixed bug related to expected input format of pycoco in `MeanAveragePrecision` ([#1913](https://github.com/Lightning-AI/torchmetrics/pull/1913))


- Fixed bug related to the `prefix/postfix` arguments in `MetricCollection` and `ClasswiseWrapper` being duplicated ([#1918](https://github.com/Lightning-AI/torchmetrics/pull/1918))

## [1.0.0] - 2022-07-04

### Added
Expand Down
10 changes: 5 additions & 5 deletions src/torchmetrics/wrappers/classwise.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,22 +130,22 @@ def __init__(

if prefix is not None and not isinstance(prefix, str):
raise ValueError(f"Expected argument `prefix` to either be `None` or a string but got {prefix}")
self.prefix = prefix
self._prefix = prefix

if postfix is not None and not isinstance(postfix, str):
raise ValueError(f"Expected argument `postfix` to either be `None` or a string but got {postfix}")
self.postfix = postfix
self._postfix = postfix

self._update_count = 1

def _convert(self, x: Tensor) -> Dict[str, Any]:
# Will set the class name as prefix if neither prefix nor postfix is given
if not self.prefix and not self.postfix:
if not self._prefix and not self._postfix:
prefix = f"{self.metric.__class__.__name__.lower()}_"
postfix = ""
else:
prefix = self.prefix or ""
postfix = self.postfix or ""
prefix = self._prefix or ""
postfix = self._postfix or ""
if self.labels is None:
return {f"{prefix}{i}{postfix}": val for i, val in enumerate(x)}
return {f"{prefix}{lab}{postfix}": val for lab, val in zip(self.labels, x)}
Expand Down
32 changes: 31 additions & 1 deletion tests/unittests/wrappers/test_classwise.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import pytest
import torch
from torchmetrics import MetricCollection
from torchmetrics.classification import MulticlassAccuracy, MulticlassRecall
from torchmetrics.classification import MulticlassAccuracy, MulticlassF1Score, MulticlassRecall
from torchmetrics.wrappers import ClasswiseWrapper


Expand Down Expand Up @@ -120,3 +120,33 @@ def _get_correct_name(base):
assert name in val
name = _get_correct_name(f"multiclassrecall_{lab}")
assert name in val


def test_double_use_of_prefix_with_metriccollection():
"""Test that the expected output is produced when using prefix/postfix with metric collection.

See issue: https://github.com/Lightning-AI/torchmetrics/issues/1915

"""
category_names = ["Tree", "Bush"]
num_classes = len(category_names)

input_ = torch.rand((5, 2, 3, 3))
target = torch.ones((5, 2, 3, 3)).long()

val_metrics = MetricCollection(
{
"accuracy": MulticlassAccuracy(num_classes=num_classes),
"f1": ClasswiseWrapper(
MulticlassF1Score(num_classes=num_classes, average="none"),
category_names,
prefix="f_score_",
),
},
prefix="val/",
)

res = val_metrics(input_, target)
assert "val/accuracy" in res
assert "val/f_score_Tree" in res
assert "val/f_score_Bush" in res
Loading