xskillscore.r2(a, b, dim=None, weights=None, skipna=False, keep_attrs=False)

R^2 (coefficient of determination) score.

We first take the total sum of squares of our known vector, a.

\[SS_{\mathrm{tot}} = \sum_{i=1}^{n} (a_{i} - \bar{a})^{2}\]

Next, we take the sum of squares of the error between our known vector a and the predicted vector, b.

\[SS_{\mathrm{res}} = \sum_{i=1}^{n} (a_{i} - b_{i})^{2}\]

Lastly we compute the coefficient of determiniation using these two terms.

\[R^{2} = 1 - \frac{SS_{\mathrm{res}}}{SS_{\mathrm{tot}}}\]


The coefficient of determination is not symmetric. In other words, r2(a, b) != r2(b, a). Be careful and note that by our convention, b is the modeled/predicted vector and a is the observed vector.

  • a (xarray.Dataset or xarray.DataArray) – Labeled array(s) over which to apply the function.

  • b (xarray.Dataset or xarray.DataArray) – Labeled array(s) over which to apply the function.

  • dim (str, list) – The dimension(s) to apply the correlation along. Note that this dimension will be reduced as a result. Defaults to None reducing all dimensions.

  • weights (xarray.Dataset or xarray.DataArray or None) – Weights matching dimensions of dim to apply during the function.

  • skipna (bool) – If True, skip NaNs when computing function.

  • keep_attrs (bool) – If True, the attributes (attrs) will be copied from the first input to the new one. If False (default), the new object will be returned without attributes.


R^2 (coefficient of determination) score.

Return type

xarray.DataArray or xarray.Dataset




>>> a = xr.DataArray(np.random.rand(5, 3, 3), dims=['time', 'x', 'y'])
>>> b = xr.DataArray(np.random.rand(5, 3, 3), dims=['time', 'x', 'y'])
>>> r2(a, b, dim='time')
<xarray.DataArray (x: 3, y: 3)>
array([[ -3.77828319,  -1.25687543,  -2.52495914],
       [ -0.67280201, -39.45271514,  -5.78241791],
       [ -1.66615797,  -1.56749317,   0.09843265]])
Dimensions without coordinates: x, y