We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
PearsonCorrCoef UnboundLocalError using ddp
I want to use PearsonCorrCoef in my pytorch lightning code with ddp strategy.
My num_outputs > 1
In x_step_end, I use CorrCoef.update(preds, targets)
In x_epoch_end, I use CorrCoef.compute().mean()
Always received

```
  File "/home/xx/Documents/anconda3/envs/xx/lib/python3.8/site-packages/torchmetrics/metric.py", line 531, in wrapped_func
    value = compute(*args, **kwargs)
  File "/home/xx/Documents/anconda3/envs/xx/lib/python3.8/site-packages/torchmetrics/regression/pearson.py", line 152, in compute
    _, _, var_x, var_y, corr_xy, n_total = _final_aggregation(
  File "/home/xx/Documents/anconda3/envs/xx/lib/python3.8/site-packages/torchmetrics/regression/pearson.py", line 63, in _final_aggregation
    return mean_x, mean_y, var_x, var_y, corr_xy, nb
UnboundLocalError: local variable 'mean_x' referenced before assignment
```

But when I change to dp strategy, it's fine.


--- 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/regression/pearson.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, Tuple
15 
16 import torch
17 from torch import Tensor
18 
19 from torchmetrics.functional.regression.pearson import _pearson_corrcoef_compute, _pearson_corrcoef_update
20 from torchmetrics.metric import Metric
21 
22 
23 def _final_aggregation(
24     means_x: Tensor,
25     means_y: Tensor,
26     vars_x: Tensor,
27     vars_y: Tensor,
28     corrs_xy: Tensor,
29     nbs: Tensor,
30 ) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:
31     """Aggregate the statistics from multiple devices.
32 
33     Formula taken from here: `Aggregate the statistics from multiple devices`_
34     """
35     # assert len(means_x) > 1 and len(means_y) > 1 and len(vars_x) > 1 and len(vars_y) > 1 and len(corrs_xy) > 1
36     mx1, my1, vx1, vy1, cxy1, n1 = means_x[0], means_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0]
37     for i in range(1, len(means_x)):
38         mx2, my2, vx2, vy2, cxy2, n2 = means_x[i], means_y[i], vars_x[i], vars_y[i], corrs_xy[i], nbs[i]
39         nb = n1 + n2
40         mean_x = (n1 * mx1 + n2 * mx2) / nb
41         mean_y = (n1 * my1 + n2 * my2) / nb
42 
43         # var_x
44         element_x1 = (n1 + 1) * mean_x - n1 * mx1
45         vx1 += (element_x1 - mx1) * (element_x1 - mean_x) - (element_x1 - mean_x) ** 2
46         element_x2 = (n2 + 1) * mean_x - n2 * mx2
47         vx2 += (element_x2 - mx2) * (element_x2 - mean_x) - (element_x2 - mean_x) ** 2
48         var_x = vx1 + vx2
49 
50         # var_y
51         element_y1 = (n1 + 1) * mean_y - n1 * my1
52         vy1 += (element_y1 - my1) * (element_y1 - mean_y) - (element_y1 - mean_y) ** 2
53         element_y2 = (n2 + 1) * mean_y - n2 * my2
54         vy2 += (element_y2 - my2) * (element_y2 - mean_y) - (element_y2 - mean_y) ** 2
55         var_y = vy1 + vy2
56 
57         # corr
58         cxy1 += (element_x1 - mx1) * (element_y1 - mean_y) - (element_x1 - mean_x) * (element_y1 - mean_y)
59         cxy2 += (element_x2 - mx2) * (element_y2 - mean_y) - (element_x2 - mean_x) * (element_y2 - mean_y)
60         corr_xy = cxy1 + cxy2
61 
62         mx1, my1, vx1, vy1, cxy1, n1 = mean_x, mean_y, var_x, var_y, corr_xy, nb
63     return mean_x, mean_y, var_x, var_y, corr_xy, nb
64 
65 
66 class PearsonCorrCoef(Metric):
67     r"""Compute `Pearson Correlation Coefficient`_.
68 
69     .. math::
70         P_{corr}(x,y) = \frac{cov(x,y)}{\sigma_x \sigma_y}
71 
72     Where :math:`y` is a tensor of target values, and :math:`x` is a tensor of predictions.
73 
74     As input to ``forward`` and ``update`` the metric accepts the following input:
75 
76     - ``preds`` (:class:`~torch.Tensor`): either single output float tensor with shape ``(N,)``
77       or multioutput float tensor of shape ``(N,d)``
78     - ``target`` (:class:`~torch.Tensor`): either single output tensor with shape ``(N,)``
79       or multioutput tensor of shape ``(N,d)``
80 
81     As output of ``forward`` and ``compute`` the metric returns the following output:
82 
83     - ``pearson`` (:class:`~torch.Tensor`): A tensor with the Pearson Correlation Coefficient
84 
85     Args:
86         num_outputs: Number of outputs in multioutput setting
87         kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.
88 
89     Example (single output regression):
90         >>> from torchmetrics import PearsonCorrCoef
91         >>> target = torch.tensor([3, -0.5, 2, 7])
92         >>> preds = torch.tensor([2.5, 0.0, 2, 8])
93         >>> pearson = PearsonCorrCoef()
94         >>> pearson(preds, target)
95         tensor(0.9849)
96 
97     Example (multi output regression):
98         >>> from torchmetrics import PearsonCorrCoef
99         >>> target = torch.tensor([[3, -0.5], [2, 7]])
100         >>> preds = torch.tensor([[2.5, 0.0], [2, 8]])
101         >>> pearson = PearsonCorrCoef(num_outputs=2)
102         >>> pearson(preds, target)
103         tensor([1., 1.])
104     """
105     is_differentiable = True
106     higher_is_better = None  # both -1 and 1 are optimal
107     full_state_update: bool = True
108     preds: List[Tensor]
109     target: List[Tensor]
110     mean_x: Tensor
111     mean_y: Tensor
112     var_x: Tensor
113     var_y: Tensor
114     corr_xy: Tensor
115     n_total: Tensor
116 
117     def __init__(
118         self,
119         num_outputs: int = 1,
120         **kwargs: Any,
121     ) -> None:
122         super().__init__(**kwargs)
123         if not isinstance(num_outputs, int) and num_outputs < 1:
124             raise ValueError("Expected argument `num_outputs` to be an int larger than 0, but got {num_outputs}")
125         self.num_outputs = num_outputs
126 
127         self.add_state("mean_x", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)
128         self.add_state("mean_y", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)
129         self.add_state("var_x", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)
130         self.add_state("var_y", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)
131         self.add_state("corr_xy", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)
132         self.add_state("n_total", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)
133 
134     def update(self, preds: Tensor, target: Tensor) -> None:
135         """Update state with predictions and targets."""
136         self.mean_x, self.mean_y, self.var_x, self.var_y, self.corr_xy, self.n_total = _pearson_corrcoef_update(
137             preds,
138             target,
139             self.mean_x,
140             self.mean_y,
141             self.var_x,
142             self.var_y,
143             self.corr_xy,
144             self.n_total,
145             self.num_outputs,
146         )
147 
148     def compute(self) -> Tensor:
149         """Compute pearson correlation coefficient over state."""
150         if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1):
151             # multiple devices, need further reduction
152             _, _, var_x, var_y, corr_xy, n_total = _final_aggregation(
153                 self.mean_x, self.mean_y, self.var_x, self.var_y, self.corr_xy, self.n_total
154             )
155         else:
156             var_x = self.var_x
157             var_y = self.var_y
158             corr_xy = self.corr_xy
159             n_total = self.n_total
160         return _pearson_corrcoef_compute(var_x, var_y, corr_xy, n_total)
161
```
--- 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/regression/pearson.py b/src/torchmetrics/regression/pearson.py
--- a/src/torchmetrics/regression/pearson.py
+++ b/src/torchmetrics/regression/pearson.py
@@ -32,7 +32,8 @@
 
     Formula taken from here: `Aggregate the statistics from multiple devices`_
     """
-    # assert len(means_x) > 1 and len(means_y) > 1 and len(vars_x) > 1 and len(vars_y) > 1 and len(corrs_xy) > 1
+    if len(means_x) == 1:
+        return means_x[0], means_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0]
     mx1, my1, vx1, vy1, cxy1, n1 = means_x[0], means_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0]
     for i in range(1, len(means_x)):
         mx2, my2, vx2, vy2, cxy2, n2 = means_x[i], means_y[i], vars_x[i], vars_y[i], corrs_xy[i], nbs[i]

{"golden_diff": "diff --git a/src/torchmetrics/regression/pearson.py b/src/torchmetrics/regression/pearson.py\n--- a/src/torchmetrics/regression/pearson.py\n+++ b/src/torchmetrics/regression/pearson.py\n@@ -32,7 +32,8 @@\n \n     Formula taken from here: `Aggregate the statistics from multiple devices`_\n     \"\"\"\n-    # assert len(means_x) > 1 and len(means_y) > 1 and len(vars_x) > 1 and len(vars_y) > 1 and len(corrs_xy) > 1\n+    if len(means_x) == 1:\n+        return means_x[0], means_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0]\n     mx1, my1, vx1, vy1, cxy1, n1 = means_x[0], means_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0]\n     for i in range(1, len(means_x)):\n         mx2, my2, vx2, vy2, cxy2, n2 = means_x[i], means_y[i], vars_x[i], vars_y[i], corrs_xy[i], nbs[i]\n", "issue": "PearsonCorrCoef UnboundLocalError using ddp\nI want to use PearsonCorrCoef in my pytorch lightning code with ddp strategy.\r\nMy num_outputs > 1\r\nIn x_step_end, I use CorrCoef.update(preds, targets)\r\nIn x_epoch_end, I use CorrCoef.compute().mean()\r\nAlways received\r\n\r\n```\r\n  File \"/home/xx/Documents/anconda3/envs/xx/lib/python3.8/site-packages/torchmetrics/metric.py\", line 531, in wrapped_func\r\n    value = compute(*args, **kwargs)\r\n  File \"/home/xx/Documents/anconda3/envs/xx/lib/python3.8/site-packages/torchmetrics/regression/pearson.py\", line 152, in compute\r\n    _, _, var_x, var_y, corr_xy, n_total = _final_aggregation(\r\n  File \"/home/xx/Documents/anconda3/envs/xx/lib/python3.8/site-packages/torchmetrics/regression/pearson.py\", line 63, in _final_aggregation\r\n    return mean_x, mean_y, var_x, var_y, corr_xy, nb\r\nUnboundLocalError: local variable 'mean_x' referenced before assignment\r\n```\r\n\r\nBut when I change to dp strategy, it's fine.\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 Any, List, Tuple\n\nimport torch\nfrom torch import Tensor\n\nfrom torchmetrics.functional.regression.pearson import _pearson_corrcoef_compute, _pearson_corrcoef_update\nfrom torchmetrics.metric import Metric\n\n\ndef _final_aggregation(\n    means_x: Tensor,\n    means_y: Tensor,\n    vars_x: Tensor,\n    vars_y: Tensor,\n    corrs_xy: Tensor,\n    nbs: Tensor,\n) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:\n    \"\"\"Aggregate the statistics from multiple devices.\n\n    Formula taken from here: `Aggregate the statistics from multiple devices`_\n    \"\"\"\n    # assert len(means_x) > 1 and len(means_y) > 1 and len(vars_x) > 1 and len(vars_y) > 1 and len(corrs_xy) > 1\n    mx1, my1, vx1, vy1, cxy1, n1 = means_x[0], means_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0]\n    for i in range(1, len(means_x)):\n        mx2, my2, vx2, vy2, cxy2, n2 = means_x[i], means_y[i], vars_x[i], vars_y[i], corrs_xy[i], nbs[i]\n        nb = n1 + n2\n        mean_x = (n1 * mx1 + n2 * mx2) / nb\n        mean_y = (n1 * my1 + n2 * my2) / nb\n\n        # var_x\n        element_x1 = (n1 + 1) * mean_x - n1 * mx1\n        vx1 += (element_x1 - mx1) * (element_x1 - mean_x) - (element_x1 - mean_x) ** 2\n        element_x2 = (n2 + 1) * mean_x - n2 * mx2\n        vx2 += (element_x2 - mx2) * (element_x2 - mean_x) - (element_x2 - mean_x) ** 2\n        var_x = vx1 + vx2\n\n        # var_y\n        element_y1 = (n1 + 1) * mean_y - n1 * my1\n        vy1 += (element_y1 - my1) * (element_y1 - mean_y) - (element_y1 - mean_y) ** 2\n        element_y2 = (n2 + 1) * mean_y - n2 * my2\n        vy2 += (element_y2 - my2) * (element_y2 - mean_y) - (element_y2 - mean_y) ** 2\n        var_y = vy1 + vy2\n\n        # corr\n        cxy1 += (element_x1 - mx1) * (element_y1 - mean_y) - (element_x1 - mean_x) * (element_y1 - mean_y)\n        cxy2 += (element_x2 - mx2) * (element_y2 - mean_y) - (element_x2 - mean_x) * (element_y2 - mean_y)\n        corr_xy = cxy1 + cxy2\n\n        mx1, my1, vx1, vy1, cxy1, n1 = mean_x, mean_y, var_x, var_y, corr_xy, nb\n    return mean_x, mean_y, var_x, var_y, corr_xy, nb\n\n\nclass PearsonCorrCoef(Metric):\n    r\"\"\"Compute `Pearson Correlation Coefficient`_.\n\n    .. math::\n        P_{corr}(x,y) = \\frac{cov(x,y)}{\\sigma_x \\sigma_y}\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`): either single output float tensor with shape ``(N,)``\n      or multioutput float tensor of shape ``(N,d)``\n    - ``target`` (:class:`~torch.Tensor`): either single output tensor with shape ``(N,)``\n      or multioutput tensor of shape ``(N,d)``\n\n    As output of ``forward`` and ``compute`` the metric returns the following output:\n\n    - ``pearson`` (:class:`~torch.Tensor`): A tensor with the Pearson Correlation Coefficient\n\n    Args:\n        num_outputs: Number of outputs in multioutput setting\n        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.\n\n    Example (single output regression):\n        >>> from torchmetrics import PearsonCorrCoef\n        >>> target = torch.tensor([3, -0.5, 2, 7])\n        >>> preds = torch.tensor([2.5, 0.0, 2, 8])\n        >>> pearson = PearsonCorrCoef()\n        >>> pearson(preds, target)\n        tensor(0.9849)\n\n    Example (multi output regression):\n        >>> from torchmetrics import PearsonCorrCoef\n        >>> target = torch.tensor([[3, -0.5], [2, 7]])\n        >>> preds = torch.tensor([[2.5, 0.0], [2, 8]])\n        >>> pearson = PearsonCorrCoef(num_outputs=2)\n        >>> pearson(preds, target)\n        tensor([1., 1.])\n    \"\"\"\n    is_differentiable = True\n    higher_is_better = None  # both -1 and 1 are optimal\n    full_state_update: bool = True\n    preds: List[Tensor]\n    target: List[Tensor]\n    mean_x: Tensor\n    mean_y: Tensor\n    var_x: Tensor\n    var_y: Tensor\n    corr_xy: Tensor\n    n_total: Tensor\n\n    def __init__(\n        self,\n        num_outputs: int = 1,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        if not isinstance(num_outputs, int) and num_outputs < 1:\n            raise ValueError(\"Expected argument `num_outputs` to be an int larger than 0, but got {num_outputs}\")\n        self.num_outputs = num_outputs\n\n        self.add_state(\"mean_x\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"mean_y\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"var_x\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"var_y\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"corr_xy\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"n_total\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n\n    def update(self, preds: Tensor, target: Tensor) -> None:\n        \"\"\"Update state with predictions and targets.\"\"\"\n        self.mean_x, self.mean_y, self.var_x, self.var_y, self.corr_xy, self.n_total = _pearson_corrcoef_update(\n            preds,\n            target,\n            self.mean_x,\n            self.mean_y,\n            self.var_x,\n            self.var_y,\n            self.corr_xy,\n            self.n_total,\n            self.num_outputs,\n        )\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute pearson correlation coefficient over state.\"\"\"\n        if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1):\n            # multiple devices, need further reduction\n            _, _, var_x, var_y, corr_xy, n_total = _final_aggregation(\n                self.mean_x, self.mean_y, self.var_x, self.var_y, self.corr_xy, self.n_total\n            )\n        else:\n            var_x = self.var_x\n            var_y = self.var_y\n            corr_xy = self.corr_xy\n            n_total = self.n_total\n        return _pearson_corrcoef_compute(var_x, var_y, corr_xy, n_total)\n", "path": "src/torchmetrics/regression/pearson.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 Any, List, Tuple\n\nimport torch\nfrom torch import Tensor\n\nfrom torchmetrics.functional.regression.pearson import _pearson_corrcoef_compute, _pearson_corrcoef_update\nfrom torchmetrics.metric import Metric\n\n\ndef _final_aggregation(\n    means_x: Tensor,\n    means_y: Tensor,\n    vars_x: Tensor,\n    vars_y: Tensor,\n    corrs_xy: Tensor,\n    nbs: Tensor,\n) -> Tuple[Tensor, Tensor, Tensor, Tensor, Tensor, Tensor]:\n    \"\"\"Aggregate the statistics from multiple devices.\n\n    Formula taken from here: `Aggregate the statistics from multiple devices`_\n    \"\"\"\n    if len(means_x) == 1:\n        return means_x[0], means_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0]\n    mx1, my1, vx1, vy1, cxy1, n1 = means_x[0], means_y[0], vars_x[0], vars_y[0], corrs_xy[0], nbs[0]\n    for i in range(1, len(means_x)):\n        mx2, my2, vx2, vy2, cxy2, n2 = means_x[i], means_y[i], vars_x[i], vars_y[i], corrs_xy[i], nbs[i]\n        nb = n1 + n2\n        mean_x = (n1 * mx1 + n2 * mx2) / nb\n        mean_y = (n1 * my1 + n2 * my2) / nb\n\n        # var_x\n        element_x1 = (n1 + 1) * mean_x - n1 * mx1\n        vx1 += (element_x1 - mx1) * (element_x1 - mean_x) - (element_x1 - mean_x) ** 2\n        element_x2 = (n2 + 1) * mean_x - n2 * mx2\n        vx2 += (element_x2 - mx2) * (element_x2 - mean_x) - (element_x2 - mean_x) ** 2\n        var_x = vx1 + vx2\n\n        # var_y\n        element_y1 = (n1 + 1) * mean_y - n1 * my1\n        vy1 += (element_y1 - my1) * (element_y1 - mean_y) - (element_y1 - mean_y) ** 2\n        element_y2 = (n2 + 1) * mean_y - n2 * my2\n        vy2 += (element_y2 - my2) * (element_y2 - mean_y) - (element_y2 - mean_y) ** 2\n        var_y = vy1 + vy2\n\n        # corr\n        cxy1 += (element_x1 - mx1) * (element_y1 - mean_y) - (element_x1 - mean_x) * (element_y1 - mean_y)\n        cxy2 += (element_x2 - mx2) * (element_y2 - mean_y) - (element_x2 - mean_x) * (element_y2 - mean_y)\n        corr_xy = cxy1 + cxy2\n\n        mx1, my1, vx1, vy1, cxy1, n1 = mean_x, mean_y, var_x, var_y, corr_xy, nb\n    return mean_x, mean_y, var_x, var_y, corr_xy, nb\n\n\nclass PearsonCorrCoef(Metric):\n    r\"\"\"Compute `Pearson Correlation Coefficient`_.\n\n    .. math::\n        P_{corr}(x,y) = \\frac{cov(x,y)}{\\sigma_x \\sigma_y}\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`): either single output float tensor with shape ``(N,)``\n      or multioutput float tensor of shape ``(N,d)``\n    - ``target`` (:class:`~torch.Tensor`): either single output tensor with shape ``(N,)``\n      or multioutput tensor of shape ``(N,d)``\n\n    As output of ``forward`` and ``compute`` the metric returns the following output:\n\n    - ``pearson`` (:class:`~torch.Tensor`): A tensor with the Pearson Correlation Coefficient\n\n    Args:\n        num_outputs: Number of outputs in multioutput setting\n        kwargs: Additional keyword arguments, see :ref:`Metric kwargs` for more info.\n\n    Example (single output regression):\n        >>> from torchmetrics import PearsonCorrCoef\n        >>> target = torch.tensor([3, -0.5, 2, 7])\n        >>> preds = torch.tensor([2.5, 0.0, 2, 8])\n        >>> pearson = PearsonCorrCoef()\n        >>> pearson(preds, target)\n        tensor(0.9849)\n\n    Example (multi output regression):\n        >>> from torchmetrics import PearsonCorrCoef\n        >>> target = torch.tensor([[3, -0.5], [2, 7]])\n        >>> preds = torch.tensor([[2.5, 0.0], [2, 8]])\n        >>> pearson = PearsonCorrCoef(num_outputs=2)\n        >>> pearson(preds, target)\n        tensor([1., 1.])\n    \"\"\"\n    is_differentiable = True\n    higher_is_better = None  # both -1 and 1 are optimal\n    full_state_update: bool = True\n    preds: List[Tensor]\n    target: List[Tensor]\n    mean_x: Tensor\n    mean_y: Tensor\n    var_x: Tensor\n    var_y: Tensor\n    corr_xy: Tensor\n    n_total: Tensor\n\n    def __init__(\n        self,\n        num_outputs: int = 1,\n        **kwargs: Any,\n    ) -> None:\n        super().__init__(**kwargs)\n        if not isinstance(num_outputs, int) and num_outputs < 1:\n            raise ValueError(\"Expected argument `num_outputs` to be an int larger than 0, but got {num_outputs}\")\n        self.num_outputs = num_outputs\n\n        self.add_state(\"mean_x\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"mean_y\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"var_x\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"var_y\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"corr_xy\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n        self.add_state(\"n_total\", default=torch.zeros(self.num_outputs), dist_reduce_fx=None)\n\n    def update(self, preds: Tensor, target: Tensor) -> None:\n        \"\"\"Update state with predictions and targets.\"\"\"\n        self.mean_x, self.mean_y, self.var_x, self.var_y, self.corr_xy, self.n_total = _pearson_corrcoef_update(\n            preds,\n            target,\n            self.mean_x,\n            self.mean_y,\n            self.var_x,\n            self.var_y,\n            self.corr_xy,\n            self.n_total,\n            self.num_outputs,\n        )\n\n    def compute(self) -> Tensor:\n        \"\"\"Compute pearson correlation coefficient over state.\"\"\"\n        if (self.num_outputs == 1 and self.mean_x.numel() > 1) or (self.num_outputs > 1 and self.mean_x.ndim > 1):\n            # multiple devices, need further reduction\n            _, _, var_x, var_y, corr_xy, n_total = _final_aggregation(\n                self.mean_x, self.mean_y, self.var_x, self.var_y, self.corr_xy, self.n_total\n            )\n        else:\n            var_x = self.var_x\n            var_y = self.var_y\n            corr_xy = self.corr_xy\n            n_total = self.n_total\n        return _pearson_corrcoef_compute(var_x, var_y, corr_xy, n_total)\n", "path": "src/torchmetrics/regression/pearson.py"}]}