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

Add None as reduction option in CosineSimilarity #400

Merged
merged 14 commits into from
Jul 29, 2021
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Added Symmetric Mean Absolute Percentage error (SMAPE) ([#375](https://github.com/PyTorchLightning/metrics/issues/375))


- Added `None` as reduction option in `CosineSimilarity` metric ([#400](https://github.com/PyTorchLightning/metrics/pull/400))


- Added Permutation Invariant Training metric (PIT) ([#294](https://github.com/PyTorchLightning/metrics/issues/294))


Expand Down
7 changes: 6 additions & 1 deletion torchmetrics/functional/regression/cosine_similarity.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ def _cosine_similarity_compute(preds: Tensor, target: Tensor, reduction: str = '
preds_norm = preds.norm(dim=-1)
target_norm = target.norm(dim=-1)
similarity = dot_product / (preds_norm * target_norm)
reduction_mapping = {"sum": torch.sum, "mean": torch.mean, "none": lambda x: x}
reduction_mapping = {
"sum": torch.sum,
"mean": torch.mean,
"none": lambda x: x,
None: lambda x: x,
}
return reduction_mapping[reduction](similarity)


Expand Down
5 changes: 4 additions & 1 deletion torchmetrics/regression/cosine_similarity.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,10 +77,13 @@ def __init__(
process_group=process_group,
dist_sync_fn=dist_sync_fn
)
allowed_reduction = ('sum', 'mean', 'none', None)
if reduction not in allowed_reduction:
raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction}" f" but got {reduction}")
Borda marked this conversation as resolved.
Show resolved Hide resolved
self.reduction = reduction

self.add_state("preds", [], dist_reduce_fx="cat")
self.add_state("target", [], dist_reduce_fx="cat")
self.reduction = reduction

def update(self, preds: Tensor, target: Tensor) -> None: # type: ignore
"""
Expand Down