r2#

mvpy.math.r2(y: ndarray | Tensor, y_h: ndarray | Tensor, y_b: ndarray | Tensor | None = None) ndarray | Tensor[source]#

Compute \(R^2\) between the final dimension of \(y\) and \(\hat{y}\).

\(R^2\), also referred to as the coefficient of determination, is computed as:

\[R^2 = 1 - \frac{\sum_i{(y_i - \hat{y}_i)^2}}{\sum_i{(y_i - \bar{y})^2}}\]

where \(i\) are samples and \(\bar{y}\) is the mean over observed samples.

Warning

In cross-validated procedures, \(\bar{y}\) naturally represents the mean of the test distribution. Principally, this constitutes a form of data leakage, as the trained model should not have access to those data. In practice, this leads to miscalibrated \(R^2\) computations and should be avoided. To remedy this, please supply y_b in these cases which will then be substituted for \(\bar{y}\) in computations.

Parameters:
ynp.ndarray | torch.Tensor

True outcomes of shape ([n_samples, ...,] n_features).

y_hnp.ndarray | torch.Tensor

Predicted outcomes of shape ([n_samples, ...,] n_features).

y_bnp.ndarray | torch.Tensor | None, default=None

Mean of the training data, if available. Must match shape of y with first dimension of size one.

Returns:
rnp.ndarray | torch.Tensor

\(R^2\) scores of shape ([n_samples, ...]).

Examples

>>> import torch
>>> from mvpy.math import rank
>>> y = torch.tensor([1.0, 2.0, 3.0])
>>> y_h = torch.tensor([1.0, 2.0, 3.0])
>>> r2(x)
tensor([1.0])