We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Weird behavior of `CosineSimilarityMetric` when used with tensors of shape [d]
## 🐛 Bug?

According to the documentation, `CosineSimilarityMetric` requires tensors of shape `[N, d]`, with `N` the batch size and `d` the dimension of the vectors.

Using it with vectors of shape `[d]` does not raise any error, and the call to `compute` behaves weirdly and gives confusing results. I'm not sure whether this is the expected behavior, a bug, or if this usage is simply unintended (and then maybe an error could have been raised).

### To Reproduce

```python
>>> from torchmetrics import CosineSimilarity
>>> from torch import tensor
>>> 
>>> cosine_similarity = CosineSimilarity(reduction="mean")
>>> a = tensor([1., 1., 1.])
>>> b = tensor([100., 100., 100.])
>>> cosine_similarity(a, b)
tensor(1.)  # a and b have the same direction, so this is normal.
>>> cosine_similarity(b, a)  
tensor(1.)  # same for b and a.
>>> cosine_similarity.compute()
tensor(0.0200)  # I would expect this to be 1 too (the average of the 2 previous calls).
```
The obtained result (0.02) is actually the cosine similarity between `[1, 1, 1, 100, 100, 100]` and `[100, 100, 100, 1, 1, 1]`. I would have expected to get instead the average between the cosine similarity of `[1, 1, 1]` and `[100, 100, 100]` and the cosine similarity of `[100, 100, 100]` and `[1, 1, 1]`, which is 1.

If instead we use it as the documentation says, with tensors of shape `[N, d]`, we get different results:
```python
>>> from torchmetrics import CosineSimilarity
>>> from torch import tensor
>>> 
>>> cosine_similarity = CosineSimilarity(reduction="mean")
>>> a = tensor([[1., 1., 1.]])  # tensor of shape [1, 3] instead of [3]
>>> b = tensor([[100., 100., 100.]])  # tensor of shape [1, 3] instead of [3]
>>> cosine_similarity(a, b)
tensor(1.)
>>> cosine_similarity(b, a)
tensor(1.)
>>> cosine_similarity.compute()
tensor(1.)  # 1 instead of 0.02
```

Environment:
- TorchMetrics 1.2.0
- Python 3.10.10
- torch 2.1.1
- Ubuntu 20.04.6 LTS

### Additional context

<!-- Add any other context about the problem here. -->


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `src/torchmetrics/functional/regression/cosine_similarity.py`
Content:
```
1 # Copyright The Lightning team.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 from typing import Optional, Tuple
15 
16 import torch
17 from torch import Tensor
18 
19 from torchmetrics.utilities.checks import _check_same_shape
20 
21 
22 def _cosine_similarity_update(
23     preds: Tensor,
24     target: Tensor,
25 ) -> Tuple[Tensor, Tensor]:
26     """Update and returns variables required to compute Cosine Similarity. Checks for same shape of input tensors.
27 
28     Args:
29         preds: Predicted tensor
30         target: Ground truth tensor
31 
32     """
33     _check_same_shape(preds, target)
34     preds = preds.float()
35     target = target.float()
36 
37     return preds, target
38 
39 
40 def _cosine_similarity_compute(preds: Tensor, target: Tensor, reduction: Optional[str] = "sum") -> Tensor:
41     """Compute Cosine Similarity.
42 
43     Args:
44         preds: Predicted tensor
45         target: Ground truth tensor
46         reduction:
47             The method of reducing along the batch dimension using sum, mean or taking the individual scores
48 
49     Example:
50         >>> target = torch.tensor([[1, 2, 3, 4], [1, 2, 3, 4]])
51         >>> preds = torch.tensor([[1, 2, 3, 4], [-1, -2, -3, -4]])
52         >>> preds, target = _cosine_similarity_update(preds, target)
53         >>> _cosine_similarity_compute(preds, target, 'none')
54         tensor([ 1.0000, -1.0000])
55 
56     """
57     dot_product = (preds * target).sum(dim=-1)
58     preds_norm = preds.norm(dim=-1)
59     target_norm = target.norm(dim=-1)
60     similarity = dot_product / (preds_norm * target_norm)
61     reduction_mapping = {
62         "sum": torch.sum,
63         "mean": torch.mean,
64         "none": lambda x: x,
65         None: lambda x: x,
66     }
67     return reduction_mapping[reduction](similarity)  # type: ignore[operator]
68 
69 
70 def cosine_similarity(preds: Tensor, target: Tensor, reduction: Optional[str] = "sum") -> Tensor:
71     r"""Compute the `Cosine Similarity`_.
72 
73     .. math::
74         cos_{sim}(x,y) = \frac{x \cdot y}{||x|| \cdot ||y||} =
75         \frac{\sum_{i=1}^n x_i y_i}{\sqrt{\sum_{i=1}^n x_i^2}\sqrt{\sum_{i=1}^n y_i^2}}
76 
77     where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.
78 
79     Args:
80         preds: Predicted tensor with shape ``(N,d)``
81         target: Ground truth tensor with shape ``(N,d)``
82         reduction:
83             The method of reducing along the batch dimension using sum, mean or taking the individual scores
84 
85     Example:
86         >>> from torchmetrics.functional.regression import cosine_similarity
87         >>> target = torch.tensor([[1, 2, 3, 4],
88         ...                        [1, 2, 3, 4]])
89         >>> preds = torch.tensor([[1, 2, 3, 4],
90         ...                       [-1, -2, -3, -4]])
91         >>> cosine_similarity(preds, target, 'none')
92         tensor([ 1.0000, -1.0000])
93 
94     """
95     preds, target = _cosine_similarity_update(preds, target)
96     return _cosine_similarity_compute(preds, target, reduction)
97
```

Path: `src/torchmetrics/regression/cosine_similarity.py`
Content:
```
1 # Copyright The Lightning team.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14 from typing import Any, List, Optional, Sequence, Union
15 
16 from torch import Tensor
17 from typing_extensions import Literal
18 
19 from torchmetrics.functional.regression.cosine_similarity import _cosine_similarity_compute, _cosine_similarity_update
20 from torchmetrics.metric import Metric
21 from torchmetrics.utilities.data import dim_zero_cat
22 from torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE
23 from torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE
24 
25 if not _MATPLOTLIB_AVAILABLE:
26     __doctest_skip__ = ["CosineSimilarity.plot"]
27 
28 
29 class CosineSimilarity(Metric):
30     r"""Compute the `Cosine Similarity`_.
31 
32     .. math::
33         cos_{sim}(x,y) = \frac{x \cdot y}{||x|| \cdot ||y||} =
34         \frac{\sum_{i=1}^n x_i y_i}{\sqrt{\sum_{i=1}^n x_i^2}\sqrt{\sum_{i=1}^n y_i^2}}
35 
36     where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.
37 
38     As input to ``forward`` and ``update`` the metric accepts the following input:
39 
40     - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,d)``
41     - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)``
42 
43     As output of ``forward`` and ``compute`` the metric returns the following output:
44 
45     - ``cosine_similarity`` (:class:`~torch.Tensor`): A float tensor with the cosine similarity
46 
47     Args:
48         reduction: how to reduce over the batch dimension using 'sum', 'mean' or 'none' (taking the individual scores)
49         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
50 
51     Example:
52         >>> from torch import tensor
53         >>> from torchmetrics.regression import CosineSimilarity
54         >>> target = tensor([[0, 1], [1, 1]])
55         >>> preds = tensor([[0, 1], [0, 1]])
56         >>> cosine_similarity = CosineSimilarity(reduction = 'mean')
57         >>> cosine_similarity(preds, target)
58         tensor(0.8536)
59 
60     """
61     is_differentiable: bool = True
62     higher_is_better: bool = True
63     full_state_update: bool = False
64     plot_lower_bound: float = 0.0
65     plot_upper_bound: float = 1.0
66 
67     preds: List[Tensor]
68     target: List[Tensor]
69 
70     def __init__(
71         self,
72         reduction: Literal["mean", "sum", "none", None] = "sum",
73         **kwargs: Any,
74     ) -> None:
75         super().__init__(**kwargs)
76         allowed_reduction = ("sum", "mean", "none", None)
77         if reduction not in allowed_reduction:
78             raise ValueError(f"Expected argument `reduction` to be one of {allowed_reduction} but got {reduction}")
79         self.reduction = reduction
80 
81         self.add_state("preds", [], dist_reduce_fx="cat")
82         self.add_state("target", [], dist_reduce_fx="cat")
83 
84     def update(self, preds: Tensor, target: Tensor) -> None:
85         """Update metric states with predictions and targets."""
86         preds, target = _cosine_similarity_update(preds, target)
87 
88         self.preds.append(preds)
89         self.target.append(target)
90 
91     def compute(self) -> Tensor:
92         """Compute metric."""
93         preds = dim_zero_cat(self.preds)
94         target = dim_zero_cat(self.target)
95         return _cosine_similarity_compute(preds, target, self.reduction)
96 
97     def plot(
98         self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None
99     ) -> _PLOT_OUT_TYPE:
100         """Plot a single or multiple values from the metric.
101 
102         Args:
103             val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.
104                 If no value is provided, will automatically call `metric.compute` and plot that result.
105             ax: An matplotlib axis object. If provided will add plot to that axis
106 
107         Returns:
108             Figure and Axes object
109 
110         Raises:
111             ModuleNotFoundError:
112                 If `matplotlib` is not installed
113 
114         .. plot::
115             :scale: 75
116 
117             >>> from torch import randn
118             >>> # Example plotting a single value
119             >>> from torchmetrics.regression import CosineSimilarity
120             >>> metric = CosineSimilarity()
121             >>> metric.update(randn(10,), randn(10,))
122             >>> fig_, ax_ = metric.plot()
123 
124         .. plot::
125             :scale: 75
126 
127             >>> from torch import randn
128             >>> # Example plotting multiple values
129             >>> from torchmetrics.regression import CosineSimilarity
130             >>> metric = CosineSimilarity()
131             >>> values = []
132             >>> for _ in range(10):
133             ...     values.append(metric(randn(10,), randn(10,)))
134             >>> fig, ax = metric.plot(values)
135 
136         """
137         return self._plot(val, ax)
138
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/src/torchmetrics/functional/regression/cosine_similarity.py b/src/torchmetrics/functional/regression/cosine_similarity.py
--- a/src/torchmetrics/functional/regression/cosine_similarity.py
+++ b/src/torchmetrics/functional/regression/cosine_similarity.py
@@ -31,6 +31,11 @@
 
     """
     _check_same_shape(preds, target)
+    if preds.ndim != 2:
+        raise ValueError(
+            "Expected input to cosine similarity to be 2D tensors of shape `[N,D]` where `N` is the number of samples"
+            f" and `D` is the number of dimensions, but got tensor of shape {preds.shape}"
+        )
     preds = preds.float()
     target = target.float()
 
diff --git a/src/torchmetrics/regression/cosine_similarity.py b/src/torchmetrics/regression/cosine_similarity.py
--- a/src/torchmetrics/regression/cosine_similarity.py
+++ b/src/torchmetrics/regression/cosine_similarity.py
@@ -118,7 +118,7 @@
             >>> # Example plotting a single value
             >>> from torchmetrics.regression import CosineSimilarity
             >>> metric = CosineSimilarity()
-            >>> metric.update(randn(10,), randn(10,))
+            >>> metric.update(randn(10,2), randn(10,2))
             >>> fig_, ax_ = metric.plot()
 
         .. plot::
@@ -130,7 +130,7 @@
             >>> metric = CosineSimilarity()
             >>> values = []
             >>> for _ in range(10):
-            ...     values.append(metric(randn(10,), randn(10,)))
+            ...     values.append(metric(randn(10,2), randn(10,2)))
             >>> fig, ax = metric.plot(values)
 
         """

{"golden_diff": "diff --git a/src/torchmetrics/functional/regression/cosine_similarity.py b/src/torchmetrics/functional/regression/cosine_similarity.py\n--- a/src/torchmetrics/functional/regression/cosine_similarity.py\n+++ b/src/torchmetrics/functional/regression/cosine_similarity.py\n@@ -31,6 +31,11 @@\n \n     \"\"\"\n     _check_same_shape(preds, target)\n+    if preds.ndim != 2:\n+        raise ValueError(\n+            \"Expected input to cosine similarity to be 2D tensors of shape `[N,D]` where `N` is the number of samples\"\n+            f\" and `D` is the number of dimensions, but got tensor of shape {preds.shape}\"\n+        )\n     preds = preds.float()\n     target = target.float()\n \ndiff --git a/src/torchmetrics/regression/cosine_similarity.py b/src/torchmetrics/regression/cosine_similarity.py\n--- a/src/torchmetrics/regression/cosine_similarity.py\n+++ b/src/torchmetrics/regression/cosine_similarity.py\n@@ -118,7 +118,7 @@\n             >>> # Example plotting a single value\n             >>> from torchmetrics.regression import CosineSimilarity\n             >>> metric = CosineSimilarity()\n-            >>> metric.update(randn(10,), randn(10,))\n+            >>> metric.update(randn(10,2), randn(10,2))\n             >>> fig_, ax_ = metric.plot()\n \n         .. plot::\n@@ -130,7 +130,7 @@\n             >>> metric = CosineSimilarity()\n             >>> values = []\n             >>> for _ in range(10):\n-            ...     values.append(metric(randn(10,), randn(10,)))\n+            ...     values.append(metric(randn(10,2), randn(10,2)))\n             >>> fig, ax = metric.plot(values)\n \n         \"\"\"\n", "issue": "Weird behavior of `CosineSimilarityMetric` when used with tensors of shape [d]\n## \ud83d\udc1b Bug?\r\n\r\nAccording to the documentation, `CosineSimilarityMetric` requires tensors of shape `[N, d]`, with `N` the batch size and `d` the dimension of the vectors.\r\n\r\nUsing it with vectors of shape `[d]` does not raise any error, and the call to `compute` behaves weirdly and gives confusing results. I'm not sure whether this is the expected behavior, a bug, or if this usage is simply unintended (and then maybe an error could have been raised).\r\n\r\n### To Reproduce\r\n\r\n```python\r\n>>> from torchmetrics import CosineSimilarity\r\n>>> from torch import tensor\r\n>>> \r\n>>> cosine_similarity = CosineSimilarity(reduction=\"mean\")\r\n>>> a = tensor([1., 1., 1.])\r\n>>> b = tensor([100., 100., 100.])\r\n>>> cosine_similarity(a, b)\r\ntensor(1.)  # a and b have the same direction, so this is normal.\r\n>>> cosine_similarity(b, a)  \r\ntensor(1.)  # same for b and a.\r\n>>> cosine_similarity.compute()\r\ntensor(0.0200)  # I would expect this to be 1 too (the average of the 2 previous calls).\r\n```\r\nThe obtained result (0.02) is actually the cosine similarity between `[1, 1, 1, 100, 100, 100]` and `[100, 100, 100, 1, 1, 1]`. I would have expected to get instead the average between the cosine similarity of `[1, 1, 1]` and `[100, 100, 100]` and the cosine similarity of `[100, 100, 100]` and `[1, 1, 1]`, which is 1.\r\n\r\nIf instead we use it as the documentation says, with tensors of shape `[N, d]`, we get different results:\r\n```python\r\n>>> from torchmetrics import CosineSimilarity\r\n>>> from torch import tensor\r\n>>> \r\n>>> cosine_similarity = CosineSimilarity(reduction=\"mean\")\r\n>>> a = tensor([[1., 1., 1.]])  # tensor of shape [1, 3] instead of [3]\r\n>>> b = tensor([[100., 100., 100.]])  # tensor of shape [1, 3] instead of [3]\r\n>>> cosine_similarity(a, b)\r\ntensor(1.)\r\n>>> cosine_similarity(b, a)\r\ntensor(1.)\r\n>>> cosine_similarity.compute()\r\ntensor(1.)  # 1 instead of 0.02\r\n```\r\n\r\nEnvironment:\r\n- TorchMetrics 1.2.0\r\n- Python 3.10.10\r\n- torch 2.1.1\r\n- Ubuntu 20.04.6 LTS\r\n\r\n### Additional context\r\n\r\n<!-- Add any other context about the problem here. -->\r\n\n", "before_files": [{"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Optional, Tuple\n\nimport torch\nfrom torch import Tensor\n\nfrom torchmetrics.utilities.checks import _check_same_shape\n\n\ndef _cosine_similarity_update(\n    preds: Tensor,\n    target: Tensor,\n) -> Tuple[Tensor, Tensor]:\n    \"\"\"Update and returns variables required to compute Cosine Similarity. Checks for same shape of input tensors.\n\n    Args:\n        preds: Predicted tensor\n        target: Ground truth tensor\n\n    \"\"\"\n    _check_same_shape(preds, target)\n    preds = preds.float()\n    target = target.float()\n\n    return preds, target\n\n\ndef _cosine_similarity_compute(preds: Tensor, target: Tensor, reduction: Optional[str] = \"sum\") -> Tensor:\n    \"\"\"Compute Cosine Similarity.\n\n    Args:\n        preds: Predicted tensor\n        target: Ground truth tensor\n        reduction:\n            The method of reducing along the batch dimension using sum, mean or taking the individual scores\n\n    Example:\n        >>> target = torch.tensor([[1, 2, 3, 4], [1, 2, 3, 4]])\n        >>> preds = torch.tensor([[1, 2, 3, 4], [-1, -2, -3, -4]])\n        >>> preds, target = _cosine_similarity_update(preds, target)\n        >>> _cosine_similarity_compute(preds, target, 'none')\n        tensor([ 1.0000, -1.0000])\n\n    \"\"\"\n    dot_product = (preds * target).sum(dim=-1)\n    preds_norm = preds.norm(dim=-1)\n    target_norm = target.norm(dim=-1)\n    similarity = dot_product / (preds_norm * target_norm)\n    reduction_mapping = {\n        \"sum\": torch.sum,\n        \"mean\": torch.mean,\n        \"none\": lambda x: x,\n        None: lambda x: x,\n    }\n    return reduction_mapping[reduction](similarity)  # type: ignore[operator]\n\n\ndef cosine_similarity(preds: Tensor, target: Tensor, reduction: Optional[str] = \"sum\") -> Tensor:\n    r\"\"\"Compute the `Cosine Similarity`_.\n\n    .. math::\n        cos_{sim}(x,y) = \\frac{x \\cdot y}{||x|| \\cdot ||y||} =\n        \\frac{\\sum_{i=1}^n x_i y_i}{\\sqrt{\\sum_{i=1}^n x_i^2}\\sqrt{\\sum_{i=1}^n y_i^2}}\n\n    where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.\n\n    Args:\n        preds: Predicted tensor with shape ``(N,d)``\n        target: Ground truth tensor with shape ``(N,d)``\n        reduction:\n            The method of reducing along the batch dimension using sum, mean or taking the individual scores\n\n    Example:\n        >>> from torchmetrics.functional.regression import cosine_similarity\n        >>> target = torch.tensor([[1, 2, 3, 4],\n        ...                        [1, 2, 3, 4]])\n        >>> preds = torch.tensor([[1, 2, 3, 4],\n        ...                       [-1, -2, -3, -4]])\n        >>> cosine_similarity(preds, target, 'none')\n        tensor([ 1.0000, -1.0000])\n\n    \"\"\"\n    preds, target = _cosine_similarity_update(preds, target)\n    return _cosine_similarity_compute(preds, target, reduction)\n", "path": "src/torchmetrics/functional/regression/cosine_similarity.py"}, {"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Any, List, Optional, Sequence, Union\n\nfrom torch import Tensor\nfrom typing_extensions import Literal\n\nfrom torchmetrics.functional.regression.cosine_similarity import _cosine_similarity_compute, _cosine_similarity_update\nfrom torchmetrics.metric import Metric\nfrom torchmetrics.utilities.data import dim_zero_cat\nfrom torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE\nfrom torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE\n\nif not _MATPLOTLIB_AVAILABLE:\n    __doctest_skip__ = [\"CosineSimilarity.plot\"]\n\n\nclass CosineSimilarity(Metric):\n    r\"\"\"Compute the `Cosine Similarity`_.\n\n    .. math::\n        cos_{sim}(x,y) = \\frac{x \\cdot y}{||x|| \\cdot ||y||} =\n        \\frac{\\sum_{i=1}^n x_i y_i}{\\sqrt{\\sum_{i=1}^n x_i^2}\\sqrt{\\sum_{i=1}^n y_i^2}}\n\n    where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.\n\n    As input to ``forward`` and ``update`` the metric accepts the following input:\n\n    - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,d)``\n    - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)``\n\n    As output of ``forward`` and ``compute`` the metric returns the following output:\n\n    - ``cosine_similarity`` (:class:`~torch.Tensor`): A float tensor with the cosine similarity\n\n    Args:\n        reduction: how to reduce over the batch dimension using 'sum', 'mean' or 'none' (taking the individual scores)\n        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.\n\n    Example:\n        >>> from torch import tensor\n        >>> from torchmetrics.regression import CosineSimilarity\n        >>> target = tensor([[0, 1], [1, 1]])\n        >>> preds = tensor([[0, 1], [0, 1]])\n        >>> cosine_similarity = CosineSimilarity(reduction = 'mean')\n        >>> cosine_similarity(preds, target)\n        tensor(0.8536)\n\n    \"\"\"\n    is_differentiable: bool = True\n    higher_is_better: bool = True\n    full_state_update: bool = False\n    plot_lower_bound: float = 0.0\n    plot_upper_bound: float = 1.0\n\n    preds: List[Tensor]\n    target: List[Tensor]\n\n    def __init__(\n        self,\n        reduction: Literal[\"mean\", \"sum\", \"none\", None] = \"sum\",\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        allowed_reduction = (\"sum\", \"mean\", \"none\", None)\n        if reduction not in allowed_reduction:\n            raise ValueError(f\"Expected argument `reduction` to be one of {allowed_reduction} but got {reduction}\")\n        self.reduction = reduction\n\n        self.add_state(\"preds\", [], dist_reduce_fx=\"cat\")\n        self.add_state(\"target\", [], dist_reduce_fx=\"cat\")\n\n    def update(self, preds: Tensor, target: Tensor) -> None:\n        \"\"\"Update metric states with predictions and targets.\"\"\"\n        preds, target = _cosine_similarity_update(preds, target)\n\n        self.preds.append(preds)\n        self.target.append(target)\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute metric.\"\"\"\n        preds = dim_zero_cat(self.preds)\n        target = dim_zero_cat(self.target)\n        return _cosine_similarity_compute(preds, target, self.reduction)\n\n    def plot(\n        self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None\n    ) -> _PLOT_OUT_TYPE:\n        \"\"\"Plot a single or multiple values from the metric.\n\n        Args:\n            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.\n                If no value is provided, will automatically call `metric.compute` and plot that result.\n            ax: An matplotlib axis object. If provided will add plot to that axis\n\n        Returns:\n            Figure and Axes object\n\n        Raises:\n            ModuleNotFoundError:\n                If `matplotlib` is not installed\n\n        .. plot::\n            :scale: 75\n\n            >>> from torch import randn\n            >>> # Example plotting a single value\n            >>> from torchmetrics.regression import CosineSimilarity\n            >>> metric = CosineSimilarity()\n            >>> metric.update(randn(10,), randn(10,))\n            >>> fig_, ax_ = metric.plot()\n\n        .. plot::\n            :scale: 75\n\n            >>> from torch import randn\n            >>> # Example plotting multiple values\n            >>> from torchmetrics.regression import CosineSimilarity\n            >>> metric = CosineSimilarity()\n            >>> values = []\n            >>> for _ in range(10):\n            ...     values.append(metric(randn(10,), randn(10,)))\n            >>> fig, ax = metric.plot(values)\n\n        \"\"\"\n        return self._plot(val, ax)\n", "path": "src/torchmetrics/regression/cosine_similarity.py"}], "after_files": [{"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Optional, Tuple\n\nimport torch\nfrom torch import Tensor\n\nfrom torchmetrics.utilities.checks import _check_same_shape\n\n\ndef _cosine_similarity_update(\n    preds: Tensor,\n    target: Tensor,\n) -> Tuple[Tensor, Tensor]:\n    \"\"\"Update and returns variables required to compute Cosine Similarity. Checks for same shape of input tensors.\n\n    Args:\n        preds: Predicted tensor\n        target: Ground truth tensor\n\n    \"\"\"\n    _check_same_shape(preds, target)\n    if preds.ndim != 2:\n        raise ValueError(\n            \"Expected input to cosine similarity to be 2D tensors of shape `[N,D]` where `N` is the number of samples\"\n            f\" and `D` is the number of dimensions, but got tensor of shape {preds.shape}\"\n        )\n    preds = preds.float()\n    target = target.float()\n\n    return preds, target\n\n\ndef _cosine_similarity_compute(preds: Tensor, target: Tensor, reduction: Optional[str] = \"sum\") -> Tensor:\n    \"\"\"Compute Cosine Similarity.\n\n    Args:\n        preds: Predicted tensor\n        target: Ground truth tensor\n        reduction:\n            The method of reducing along the batch dimension using sum, mean or taking the individual scores\n\n    Example:\n        >>> target = torch.tensor([[1, 2, 3, 4], [1, 2, 3, 4]])\n        >>> preds = torch.tensor([[1, 2, 3, 4], [-1, -2, -3, -4]])\n        >>> preds, target = _cosine_similarity_update(preds, target)\n        >>> _cosine_similarity_compute(preds, target, 'none')\n        tensor([ 1.0000, -1.0000])\n\n    \"\"\"\n    dot_product = (preds * target).sum(dim=-1)\n    preds_norm = preds.norm(dim=-1)\n    target_norm = target.norm(dim=-1)\n    similarity = dot_product / (preds_norm * target_norm)\n    reduction_mapping = {\n        \"sum\": torch.sum,\n        \"mean\": torch.mean,\n        \"none\": lambda x: x,\n        None: lambda x: x,\n    }\n    return reduction_mapping[reduction](similarity)  # type: ignore[operator]\n\n\ndef cosine_similarity(preds: Tensor, target: Tensor, reduction: Optional[str] = \"sum\") -> Tensor:\n    r\"\"\"Compute the `Cosine Similarity`_.\n\n    .. math::\n        cos_{sim}(x,y) = \\frac{x \\cdot y}{||x|| \\cdot ||y||} =\n        \\frac{\\sum_{i=1}^n x_i y_i}{\\sqrt{\\sum_{i=1}^n x_i^2}\\sqrt{\\sum_{i=1}^n y_i^2}}\n\n    where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.\n\n    Args:\n        preds: Predicted tensor with shape ``(N,d)``\n        target: Ground truth tensor with shape ``(N,d)``\n        reduction:\n            The method of reducing along the batch dimension using sum, mean or taking the individual scores\n\n    Example:\n        >>> from torchmetrics.functional.regression import cosine_similarity\n        >>> target = torch.tensor([[1, 2, 3, 4],\n        ...                        [1, 2, 3, 4]])\n        >>> preds = torch.tensor([[1, 2, 3, 4],\n        ...                       [-1, -2, -3, -4]])\n        >>> cosine_similarity(preds, target, 'none')\n        tensor([ 1.0000, -1.0000])\n\n    \"\"\"\n    preds, target = _cosine_similarity_update(preds, target)\n    return _cosine_similarity_compute(preds, target, reduction)\n", "path": "src/torchmetrics/functional/regression/cosine_similarity.py"}, {"content": "# Copyright The Lightning team.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#     http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\nfrom typing import Any, List, Optional, Sequence, Union\n\nfrom torch import Tensor\nfrom typing_extensions import Literal\n\nfrom torchmetrics.functional.regression.cosine_similarity import _cosine_similarity_compute, _cosine_similarity_update\nfrom torchmetrics.metric import Metric\nfrom torchmetrics.utilities.data import dim_zero_cat\nfrom torchmetrics.utilities.imports import _MATPLOTLIB_AVAILABLE\nfrom torchmetrics.utilities.plot import _AX_TYPE, _PLOT_OUT_TYPE\n\nif not _MATPLOTLIB_AVAILABLE:\n    __doctest_skip__ = [\"CosineSimilarity.plot\"]\n\n\nclass CosineSimilarity(Metric):\n    r\"\"\"Compute the `Cosine Similarity`_.\n\n    .. math::\n        cos_{sim}(x,y) = \\frac{x \\cdot y}{||x|| \\cdot ||y||} =\n        \\frac{\\sum_{i=1}^n x_i y_i}{\\sqrt{\\sum_{i=1}^n x_i^2}\\sqrt{\\sum_{i=1}^n y_i^2}}\n\n    where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.\n\n    As input to ``forward`` and ``update`` the metric accepts the following input:\n\n    - ``preds`` (:class:`~torch.Tensor`): Predicted float tensor with shape ``(N,d)``\n    - ``target`` (:class:`~torch.Tensor`): Ground truth float tensor with shape ``(N,d)``\n\n    As output of ``forward`` and ``compute`` the metric returns the following output:\n\n    - ``cosine_similarity`` (:class:`~torch.Tensor`): A float tensor with the cosine similarity\n\n    Args:\n        reduction: how to reduce over the batch dimension using 'sum', 'mean' or 'none' (taking the individual scores)\n        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.\n\n    Example:\n        >>> from torch import tensor\n        >>> from torchmetrics.regression import CosineSimilarity\n        >>> target = tensor([[0, 1], [1, 1]])\n        >>> preds = tensor([[0, 1], [0, 1]])\n        >>> cosine_similarity = CosineSimilarity(reduction = 'mean')\n        >>> cosine_similarity(preds, target)\n        tensor(0.8536)\n\n    \"\"\"\n    is_differentiable: bool = True\n    higher_is_better: bool = True\n    full_state_update: bool = False\n    plot_lower_bound: float = 0.0\n    plot_upper_bound: float = 1.0\n\n    preds: List[Tensor]\n    target: List[Tensor]\n\n    def __init__(\n        self,\n        reduction: Literal[\"mean\", \"sum\", \"none\", None] = \"sum\",\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        allowed_reduction = (\"sum\", \"mean\", \"none\", None)\n        if reduction not in allowed_reduction:\n            raise ValueError(f\"Expected argument `reduction` to be one of {allowed_reduction} but got {reduction}\")\n        self.reduction = reduction\n\n        self.add_state(\"preds\", [], dist_reduce_fx=\"cat\")\n        self.add_state(\"target\", [], dist_reduce_fx=\"cat\")\n\n    def update(self, preds: Tensor, target: Tensor) -> None:\n        \"\"\"Update metric states with predictions and targets.\"\"\"\n        preds, target = _cosine_similarity_update(preds, target)\n\n        self.preds.append(preds)\n        self.target.append(target)\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute metric.\"\"\"\n        preds = dim_zero_cat(self.preds)\n        target = dim_zero_cat(self.target)\n        return _cosine_similarity_compute(preds, target, self.reduction)\n\n    def plot(\n        self, val: Optional[Union[Tensor, Sequence[Tensor]]] = None, ax: Optional[_AX_TYPE] = None\n    ) -> _PLOT_OUT_TYPE:\n        \"\"\"Plot a single or multiple values from the metric.\n\n        Args:\n            val: Either a single result from calling `metric.forward` or `metric.compute` or a list of these results.\n                If no value is provided, will automatically call `metric.compute` and plot that result.\n            ax: An matplotlib axis object. If provided will add plot to that axis\n\n        Returns:\n            Figure and Axes object\n\n        Raises:\n            ModuleNotFoundError:\n                If `matplotlib` is not installed\n\n        .. plot::\n            :scale: 75\n\n            >>> from torch import randn\n            >>> # Example plotting a single value\n            >>> from torchmetrics.regression import CosineSimilarity\n            >>> metric = CosineSimilarity()\n            >>> metric.update(randn(10,2), randn(10,2))\n            >>> fig_, ax_ = metric.plot()\n\n        .. plot::\n            :scale: 75\n\n            >>> from torch import randn\n            >>> # Example plotting multiple values\n            >>> from torchmetrics.regression import CosineSimilarity\n            >>> metric = CosineSimilarity()\n            >>> values = []\n            >>> for _ in range(10):\n            ...     values.append(metric(randn(10,2), randn(10,2)))\n            >>> fig, ax = metric.plot(values)\n\n        \"\"\"\n        return self._plot(val, ax)\n", "path": "src/torchmetrics/regression/cosine_similarity.py"}]}