Converting Numpy Lstsq residual value to R^2

流过昼夜 提交于 2019-12-03 07:17:43

See http://en.wikipedia.org/wiki/Coefficient_of_determination

Your R2 value =

1 - residual / sum((y - y.mean())**2) 

which is equivalent to

1 - residual / (n * y.var())

As an example:

import numpy as np

# Make some data...
n = 10
x = np.arange(n)
y = 3 * x + 5 + np.random.random(n)

# Note that polyfit is an easier way to do this...
# It would just be "model, resid = np.polyfit(x,y,1,full=True)[:2]" 
A = np.vstack((x, np.ones(n))).T
model, resid = np.linalg.lstsq(A, y)[:2]

r2 = 1 - resid / (y.size * y.var())
print r2
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!