- Code: Select all
`def r2( y, f ) :`

from numpy import mean # importing required libraries

from cmath import sqrt

n = len(y)

ybar = mean(y) # mean of y

sigma_y^2 = (1.0/n)*sum((y-ybar)**2) # variance of y

m = (mean(x*y)-(mean(x)*mean(y)))/(mean(x**2)-(mean(x)**2))

b = mean(y) - m*mean(x)

f = m*x + b

sigma_f^2 = (1.0/n)*sum((f-y)**2)

R^2 = 1 - (sigma_f^2/sigma_y^2)

return R^2