torchmetrics icon indicating copy to clipboard operation
torchmetrics copied to clipboard

Fix `MetricCollection` dict keys when used with `ClasswiseWrapper`

Open sup3rgiu opened this issue 1 year ago • 3 comments

What does this PR do?

When a ClasswiseWrapper is inserted into a MetricCollection, the resulting output dictionary does not take into account the specified name.

import torch
from torchmetrics import MetricCollection
from torchmetrics.wrappers import ClasswiseWrapper
from torchmetrics.classification import MulticlassAccuracy, MulticlassRecall
labels = ["horse", "fish", "dog"]
metric = MetricCollection(
    {'my/name/': ClasswiseWrapper(MulticlassAccuracy(num_classes=3, average=None), labels, prefix='accuracy_'),
    'my/other_name/': ClasswiseWrapper(MulticlassRecall(num_classes=3, average=None), labels, prefix='recall_')}
)
preds = torch.randn(10, 3).softmax(dim=-1)
target = torch.randint(3, (10,))
metric(preds, target)  

The previous code produces the following output:

{'accuracy_horse': tensor(0.5000),
 'accuracy_fish': tensor(0.2500),
 'accuracy_dog': tensor(0.5000),
 'recall_horse': tensor(0.5000),
 'recall_fish': tensor(0.2500),
 'recall_dog': tensor(0.5000)}

While with proposed fix, the output is the following:

{'my/name/accuracy_horse': tensor(0.5000),
 'my/name/accuracy_fish': tensor(0.2500),
 'my/name/accuracy_dog': tensor(0.5000),
 'my/other_name/recall_horse': tensor(0.5000),
 'my/other_name/recall_fish': tensor(0.2500),
 'my/other_name/recall_dog': tensor(0.5000)}
Before submitting
  • [ ] Was this discussed/agreed via a Github issue? (no need for typos and docs improvements)
  • [x] Did you read the contributor guideline, Pull Request section?
  • [x] Did you make sure to update the docs?
  • [x] Did you write any new necessary tests?
PR review

Anyone in the community is free to review the PR once the tests have passed. If we didn't discuss your PR in Github issues there's a high chance it will not be merged.

Did you have fun?

Make sure you had fun coding 🙃


📚 Documentation preview 📚: https://torchmetrics--2361.org.readthedocs.build/en/2361/

sup3rgiu avatar Feb 07 '24 14:02 sup3rgiu

@sup3rgiu please see the failing doctest, seems that chnege does not work as intended yet...

Borda avatar Feb 07 '24 23:02 Borda

@sup3rgiu let's turn it to draft until failing tests are addressed 🦩

Borda avatar Feb 27 '24 08:02 Borda