---
title: R2 Score
description: Compute r2 score also known as R2 Score_Coefficient Determination.
canonical: 'https://lightning.ai/docs/torchmetrics/stable/regression/r2_score'
---
# R2 Score {#r2-score}

## Module Interface {#module-interface}

### `class torchmetrics.R2Score(adjusted=0, multioutput='uniform_average', **kwargs)` {#torchmetrics.R2Score}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/regression/r2.py#L28-L187)

Compute r2 score also known as [R2 Score\_Coefficient Determination](https://en.wikipedia.org/wiki/Coefficient_of_determination).

```math
R^2 = 1 - \frac{SS_{res}}{SS_{tot}}
```

where $`SS_{res}=\sum_i (y_i - f(x_i))^2`$ is the sum of residual squares, and $`SS_{tot}=\sum_i (y_i - \bar{y})^2`$ is total sum of squares. Can also calculate adjusted r2 score given by

```math
R^2_{adj} = 1 - \frac{(1-R^2)(n-1)}{n-k-1}
```

where the parameter $`k`$ (the number of independent regressors) should be provided as the adjusted argument. The score is only proper defined when $`SS_{tot}\neq 0`$, which can happen for near constant targets. In this case a score of 0 is returned. By definition the score is bounded between $`-inf`$ and 1.0, with 1.0 indicating perfect prediction, 0 indicating constant prediction and negative values indicating worse than constant prediction.

As input to `forward` and `update` the metric accepts the following input:

*   `preds` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): Predictions from model in float tensor with shape `(N,)` or `(N, M)` (multioutput)
    
*   `target` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): Ground truth values in float tensor with shape `(N,)` or `(N, M)` (multioutput)
    

As output of `forward` and `compute` the metric returns the following output:

*   `r2score` ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")): A tensor with the r2 score(s)
    

In the case of multioutput, as default the variances will be uniformly averaged over the additional dimensions. Please see argument `multioutput` for changing this behavior.

Parameters:

*   **num\_outputs** – Number of outputs in multioutput setting
    
*   **adjusted** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – number of independent regressors for calculating adjusted r2 score.
    
*   **multioutput** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) –
    
    Defines aggregation in the case of multiple output scores. Can be one of the following strings:
    
    *   `'raw_values'` returns full set of scores
        
    *   `'uniform_average'` scores are uniformly averaged
        
    *   `'variance_weighted'` scores are weighted by their individual variances
        
    
*   **kwargs** ([`Any`](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.15)")) – Additional keyword arguments, see [Advanced metric settings](/docs/torchmetrics/1.9.0/user-guide/overview.md#metric-kwargs) for more info.
    

Warning

Argument `num_outputs` in `R2Score` has been deprecated because it is no longer necessary and will be removed in v1.6.0 of TorchMetrics. The number of outputs is now automatically inferred from the shape of the input tensors.

Raises:

*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `adjusted` parameter is not an integer larger or equal to 0.
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `multioutput` is not one of `"raw_values"`, `"uniform_average"` or `"variance_weighted"`.
    

Example (single output):

```python
>>> from torch import tensor
>>> from torchmetrics.regression import R2Score
>>> target = tensor([3, -0.5, 2, 7])
>>> preds = tensor([2.5, 0.0, 2, 8])
>>> r2score = R2Score()
>>> r2score(preds, target)
tensor(0.9486)
```

Example (multioutput):

```python
>>> from torch import tensor
>>> from torchmetrics.regression import R2Score
>>> target = tensor([[0.5, 1], [-1, 1], [7, -6]])
>>> preds = tensor([[0, 2], [-1, 2], [8, -5]])
>>> r2score = R2Score(multioutput='raw_values')
>>> r2score(preds, target)
tensor([0.9654, 0.9082])
```

#### `plot(val=None, ax=None)` {#torchmetrics.R2Score.plot}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/regression/r2.py#L147-L187)

Plot a single or multiple values from the metric.

Parameters:

*   **val** (`Union`\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)"), [`Sequence`](https://docs.python.org/3/library/collections.abc.html#collections.abc.Sequence "(in Python v3.15)")\[[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")\], [`None`](https://docs.python.org/3/builtins/constants.html#None "(in Python v3.15)")\]) – Either a single result from calling metric.forward or metric.compute or a list of these results. If no value is provided, will automatically call metric.compute and plot that result.
    
*   **ax** ([`Optional`](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.15)")\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)")\]) – An matplotlib axis object. If provided will add plot to that axis
    

Return type:

[`tuple`](https://docs.python.org/3/builtins/stdtypes.html#tuple "(in Python v3.15)")\[[`Figure`](https://matplotlib.org/stable/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure "(in Matplotlib v3.11.2)"), `Union`\[[`Axes`](https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.html#matplotlib.axes.Axes "(in Matplotlib v3.11.2)"), [`ndarray`](https://numpy.org/doc/stable/reference/generated/numpy.ndarray.html#numpy.ndarray "(in NumPy v2.5)")\]\]

Returns:

Figure and Axes object

Raises:

[**ModuleNotFoundError**](https://docs.python.org/3/builtins/exceptions.html#ModuleNotFoundError "(in Python v3.15)") – If matplotlib is not installed

```python
>>> from torch import randn
>>> # Example plotting a single value
>>> from torchmetrics.regression import R2Score
>>> metric = R2Score()
>>> metric.update(randn(10,), randn(10,))
>>> fig_, ax_ = metric.plot()
```

[![../../\_images/r2\_score-1.png](/docs/torchmetrics/1.9.0/static/_images/r2_score-1.png)](/docs/torchmetrics/1.9.0/static/_images/r2_score-1.png)

```python
>>> from torch import randn
>>> # Example plotting multiple values
>>> from torchmetrics.regression import R2Score
>>> metric = R2Score()
>>> values = []
>>> for _ in range(10):
...     values.append(metric(randn(10,), randn(10,)))
>>> fig, ax = metric.plot(values)
```

[![../../\_images/r2\_score-2.png](/docs/torchmetrics/1.9.0/static/_images/r2_score-2.png)](/docs/torchmetrics/1.9.0/static/_images/r2_score-2.png)

## Functional Interface {#functional-interface}

### `torchmetrics.functional.r2_score(preds, target, adjusted=0, multioutput='uniform_average')` {#torchmetrics.functional.r2_score}

[\[source\]](https://github.com/Lightning-AI/torchmetrics/blob/v1.9.0/src/torchmetrics/functional/regression/r2.py#L121-L174)

Compute r2 score also known as [R2 Score\_Coefficient Determination](https://en.wikipedia.org/wiki/Coefficient_of_determination).

```math
R^2 = 1 - \frac{SS_{res}}{SS_{tot}}
```

where $`SS_{res}=\sum_i (y_i - f(x_i))^2`$ is the sum of residual squares, and $`SS_{tot}=\sum_i (y_i - \bar{y})^2`$ is total sum of squares. Can also calculate adjusted r2 score given by

```math
R^2_{adj} = 1 - \frac{(1-R^2)(n-1)}{n-k-1}
```

where the parameter $`k`$ (the number of independent regressors) should be provided as the `adjusted` argument.

Parameters:

*   **preds** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – estimated labels
    
*   **target** ([`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")) – ground truth labels
    
*   **adjusted** ([`int`](https://docs.python.org/3/builtins/functions.html#int "(in Python v3.15)")) – number of independent regressors for calculating adjusted r2 score.
    
*   **multioutput** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str "(in Python v3.15)")) –
    
    Defines aggregation in the case of multiple output scores. Can be one of the following strings:
    
    *   `'raw_values'` returns full set of scores
        
    *   `'uniform_average'` scores are uniformly averaged
        
    *   `'variance_weighted'` scores are weighted by their individual variances
        
    

Raises:

*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If both `preds` and `targets` are not `1D` or `2D` tensors.
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `len(preds)` is less than `2` since at least `2` samples are needed to calculate r2 score.
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `multioutput` is not one of `raw_values`, `uniform_average` or `variance_weighted`.
    
*   [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError "(in Python v3.15)") – If `adjusted` is not an `integer` greater than `0`.
    

Return type:

[`Tensor`](https://docs.pytorch.org/docs/stable/tensors.html#torch.Tensor "(in PyTorch v2.15)")

Example

```python
>>> from torchmetrics.functional.regression import r2_score
>>> target = torch.tensor([3, -0.5, 2, 7])
>>> preds = torch.tensor([2.5, 0.0, 2, 8])
>>> r2_score(preds, target)
tensor(0.9486)
```

```python
>>> target = torch.tensor([[0.5, 1], [-1, 1], [7, -6]])
>>> preds = torch.tensor([[0, 2], [-1, 2], [8, -5]])
>>> r2_score(preds, target, multioutput='raw_values')
tensor([0.9654, 0.9082])
```

---

**Navigation**

- Parent: [Regression](/docs/torchmetrics/1.9.0/regression.md)
