All formulas

Statistics

Coefficient of determination

stats.r-squaredAlso called r squared, r2, r2 score, coefficient of determination

R2=1−∑i=1n(yi−y^i)2∑i=1n(yi−yˉ)2R^2 = 1 - \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{\sum_{i=1}^{n} (y_i - \bar{y})^2}

whereyˉ=1n∑j=1nyj\bar{y} = \frac{1}{n}\sum_{j=1}^{n} y_j

One minus the ratio of the residual sum of squares to the total sum of squares about the mean of the observed values. It is 1 for a perfect fit and negative for fits worse than the mean.

Notation

yy

observed values

y ∈ ℝn

y^\hat{y}

predicted values

ŷ ∈ ℝn

nn

number of observations

Size, at least 2

R2R^2

Result: the coefficient of determination

scalar

Worked examples

Each result is solved exactly and confirmed by two independent computations.

  1. Given

    y=[1,2,3,4],y^=[1,2,3,5]y = [1, 2, 3, 4], \hat{y} = [1, 2, 3, 5]

    Result

    R2=45\displaystyle R^2 = \frac{4}{5}

    ≈ 0.8

  2. Given

    y=[1,2,3],y^=[1,1,5]y = [1, 2, 3], \hat{y} = [1, 1, 5]

    Result

    R2=−32\displaystyle R^2 = - \frac{3}{2}

    ≈ -1.5

  3. Given

    y=[0,2],y^=[0.5,1.5]y = [0, 2], \hat{y} = [0.5, 1.5]

    Result

    R2=34\displaystyle R^2 = \frac{3}{4}

    ≈ 0.75

Common mistakes

  • MSE over the sample variance

    The residual term divides by n and the total term by n − 1, so 1 − R2 comes out (n − 1)/n times its true value.

    Fix: Use plain sums of squares, or the same divisor in both terms.

  • Total sum of squares taken about the predictions

    The denominator uses the spread of the predicted values instead of the observed values.

    Fix: Compute the total sum of squares from the observed values and their mean.

Source

  • Murphy 2022

    Murphy, Kevin P. Probabilistic Machine Learning: An Introduction. MIT Press, 2022.