-
Notifications
You must be signed in to change notification settings - Fork 472
Add MetricInputTransformer
#2392
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
Merged
Merged
Changes from all commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
556c625
Add MetricInputTransformer, LambdaInputTransformer, and BinaryTargetT…
lgienapp f818db9
Add tests for MetricInputTransformer, LambdaInputTransformer, and Bin…
lgienapp 4e0c6f4
Add docs for transformations
lgienapp d673585
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 1d6f834
Fix failing pipelines
lgienapp bbdd66e
Fix failing type annotations
lgienapp 92e364c
Merge remote-tracking branch 'origin/master'
lgienapp cf633d1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] ac63c50
Fix failing ruff tests
lgienapp f7778f1
Merge remote-tracking branch 'origin/master'
lgienapp 07f452e
Merge branch 'master' into master
lgienapp 6c4cb58
Merge branch 'master' into master
Borda a504769
Merge branch 'master' into master
Borda b554e11
RST
Borda 1de774e
Merge branch 'master' into master
Borda c228f77
Merge branch 'master' into master
Borda 348c6f4
Merge branch 'master' into master
Borda 64abd5f
Merge branch 'master' into master
Borda 7e8eada
Merge branch 'master' into master
Borda 01c7e23
Merge branch 'master' into master
Borda a52f1a7
Update tests/unittests/wrappers/test_transformations.py
lgienapp 68cd9a9
Update tests/unittests/wrappers/test_transformations.py
lgienapp 41b3882
Merge branch 'master' into master
Borda b54c861
mypy
Borda f182646
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 2fda8b6
Fix failing test regexes
lgienapp 2154264
Merge branch 'master' into master
Borda 0716cf4
chlog
Borda 07c6f84
Apply suggestions from code review
Borda 50a4f99
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 9c90ade
lint
Borda File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,23 @@ | ||
| .. customcarditem:: | ||
| :header: Transformations | ||
| :image: https://pl-flash-data.s3.amazonaws.com/assets/thumbnails/graph_classification.svg | ||
| :tags: Wrappers | ||
|
|
||
| .. include:: ../links.rst | ||
|
|
||
| ############### | ||
| Transformations | ||
| ############### | ||
|
|
||
| Transformations allow for modifications to the input a metric receives by wrapping its `pred` and `target` arguments. | ||
| Transformations can be implemented by either subclassing the ``MetricInputTransformer`` base class and overriding the ``.transform_pred()`` and/or ``transform_target()`` functions, or by supplying a lambda function via the ``LambdaInputTransformer``. | ||
| A ``BinaryTargetTransformer`` which casts target labels to 0/1 given a threshold is provided for convenience. | ||
|
|
||
| Module Interface | ||
| ________________ | ||
|
|
||
| .. autoclass:: torchmetrics.wrappers.MetricInputTransformer | ||
|
|
||
| .. autoclass:: torchmetrics.wrappers.LambdaInputTransformer | ||
|
|
||
| .. autoclass:: torchmetrics.wrappers.BinaryTargetTransformer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,175 @@ | ||
| # Copyright The Lightning team. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| from typing import Any, Callable, Dict, Optional, Tuple, Union | ||
|
|
||
| import torch | ||
|
|
||
| from torchmetrics.collections import MetricCollection | ||
| from torchmetrics.metric import Metric | ||
| from torchmetrics.wrappers.abstract import WrapperMetric | ||
|
|
||
|
|
||
| class MetricInputTransformer(WrapperMetric): | ||
| """Abstract base class for metric input transformations. | ||
|
|
||
| Input transformations are characterized by them applying a transformation to the input data of a metric, and then | ||
| forwarding all calls to the wrapped metric with modifications applied. | ||
|
|
||
| """ | ||
|
|
||
| def __init__(self, wrapped_metric: Union[Metric, MetricCollection], **kwargs: Dict[str, Any]) -> None: | ||
| super().__init__(**kwargs) | ||
| if not isinstance(wrapped_metric, (Metric, MetricCollection)): | ||
| raise TypeError( | ||
| f"Expected wrapped metric to be an instance of `torchmetrics.Metric` or " | ||
| f"`torchmetrics.MetricsCollection`but received {wrapped_metric}" | ||
| ) | ||
| self.wrapped_metric = wrapped_metric | ||
|
|
||
| def transform_pred(self, pred: torch.Tensor) -> torch.Tensor: | ||
| """Define transform operations on the prediction data. | ||
|
|
||
| Overridden by subclasses. Identity by default. | ||
|
|
||
| """ | ||
| return pred | ||
|
|
||
| def transform_target(self, target: torch.Tensor) -> torch.Tensor: | ||
| """Define transform operations on the target data. | ||
|
|
||
| Overridden by subclasses. Identity by default. | ||
|
|
||
| """ | ||
| return target | ||
|
|
||
| def _wrap_transform(self, *args: torch.Tensor) -> Tuple[torch.Tensor, ...]: | ||
| """Wrap transformation functions to dispatch args to their individual transform functions.""" | ||
| if len(args) == 1: | ||
| return (self.transform_pred(args[0]),) | ||
| if len(args) == 2: | ||
| return self.transform_pred(args[0]), self.transform_target(args[1]) | ||
| return self.transform_pred(args[0]), self.transform_target(args[1]), *args[2:] | ||
|
|
||
| def update(self, *args: torch.Tensor, **kwargs: Dict[str, Any]) -> None: | ||
| """Wrap the update call of the underlying metric.""" | ||
| args = self._wrap_transform(*args) | ||
| self.wrapped_metric.update(*args, **kwargs) | ||
|
|
||
| def compute(self) -> Any: | ||
| """Wrap the compute call of the underlying metric.""" | ||
| return self.wrapped_metric.compute() | ||
|
|
||
| def forward(self, *args: torch.Tensor, **kwargs: Dict[str, Any]) -> Any: | ||
| """Wrap the forward call of the underlying metric.""" | ||
| args = self._wrap_transform(*args) | ||
| return self.wrapped_metric.forward(*args, **kwargs) | ||
|
|
||
|
|
||
| class LambdaInputTransformer(MetricInputTransformer): | ||
| """Wrapper class for transforming a metrics' inputs given a user-defined lambda function. | ||
|
|
||
| Args: | ||
| wrapped_metric: | ||
| The underlying `Metric` or `MetricCollection`. | ||
| transform_pred: | ||
| The function to apply to the predictions before computing the metric. | ||
| transform_target: | ||
| The function to apply to the target before computing the metric. | ||
|
|
||
| Raises: | ||
| TypeError: | ||
| If `transform_pred` is not a Callable. | ||
| TypeError: | ||
| If `transform_target` is not a Callable. | ||
|
|
||
| Example: | ||
| >>> import torch | ||
| >>> from torchmetrics.classification import BinaryAccuracy | ||
| >>> from torchmetrics.wrappers import LambdaInputTransformer | ||
| >>> | ||
| >>> preds = torch.tensor([0.9, 0.8, 0.7, 0.6, 0.5, 0.6, 0.7, 0.8, 0.5, 0.4]) | ||
| >>> targets = torch.tensor([1,0,0,0,0,1,1,0,0,0]) | ||
| >>> | ||
| >>> metric = LambdaInputTransformer(BinaryAccuracy(), lambda preds: 1 - preds) | ||
| >>> metric.update(preds, targets) | ||
| >>> metric.compute() | ||
| tensor(0.6000) | ||
|
|
||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| wrapped_metric: Metric, | ||
| transform_pred: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, | ||
| transform_target: Optional[Callable[[torch.Tensor], torch.Tensor]] = None, | ||
| **kwargs: Any, | ||
| ) -> None: | ||
| super().__init__(wrapped_metric, **kwargs) | ||
| if transform_pred is not None: | ||
| if not callable(transform_pred): | ||
| raise TypeError(f"Expected `transform_pred` to be of type `Callable` but received `{transform_pred}`") | ||
| self.transform_pred = transform_pred # type: ignore[assignment,method-assign] | ||
|
|
||
| if transform_target is not None: | ||
| if not callable(transform_target): | ||
| raise TypeError( | ||
| f"Expected `transform_target` to be of type `Callable` but received `{transform_target}`" | ||
| ) | ||
| self.transform_target = transform_target # type: ignore[assignment,method-assign] | ||
|
|
||
|
|
||
| class BinaryTargetTransformer(MetricInputTransformer): | ||
| """Wrapper class for computing a metric on binarized targets. | ||
|
|
||
| Useful when the given ground-truth targets are continuous, but the metric requires binary targets. | ||
|
|
||
| Args: | ||
| wrapped_metric: | ||
| The underlying `Metric` or `MetricCollection`. | ||
| threshold: | ||
| The binarization threshold for the targets. Targets values `t` are cast to binary with `t > threshold`. | ||
|
|
||
| Raises: | ||
| TypeError: | ||
| If `threshold` is not an `int` or `float`. | ||
|
|
||
| Example: | ||
| >>> import torch | ||
| >>> from torchmetrics.retrieval import RetrievalMRR | ||
| >>> from torchmetrics.wrappers import BinaryTargetTransformer | ||
| >>> | ||
| >>> preds = torch.tensor([0.9, 0.8, 0.7, 0.6, 0.5, 0.6, 0.7, 0.8, 0.5, 0.4]) | ||
| >>> targets = torch.tensor([1,0,0,0,0,2,1,0,0,0]) | ||
| >>> topics = torch.tensor([0,0,0,0,0,1,1,1,1,1]) | ||
| >>> | ||
| >>> metric = BinaryTargetTransformer(RetrievalMRR()) | ||
| >>> metric.update(preds, targets, indexes=topics) | ||
| >>> metric.compute() | ||
| tensor(0.7500) | ||
|
|
||
| """ | ||
|
|
||
| def __init__(self, wrapped_metric: Union[Metric, MetricCollection], threshold: float = 0, **kwargs: Any) -> None: | ||
| super().__init__(wrapped_metric, **kwargs) | ||
| if not isinstance(threshold, (int, float)): | ||
| raise TypeError(f"Expected `threshold` to be of type `int` or `float` but received `{threshold}`") | ||
| self.threshold = threshold | ||
|
|
||
| def transform_target(self, target: torch.Tensor) -> torch.Tensor: | ||
| """Cast the target tensor to binary values according to the threshold. | ||
|
|
||
| Output assumes same type as input. | ||
|
|
||
| """ | ||
| return target.gt(self.threshold).to(target.dtype) | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.