有多组数据要做线性拟合加R方,奈何刚开始学python没多久。数据是Excel里的,最后结果也要放回到excel里。
主要想解决的是R方。
我找到的numpy代码
这个是一元拟合的,很简单但是没有R2
import numpy as np
X=[ 1 ,2 ,3 ,4 ,5 ,6]
Y=[ 2.5 ,3.51 ,4.45 ,5.52 ,6.47 ,7.51]
z1 = np.polyfit(X, Y, 1) #一次多项式拟合,相当于线性拟合
p1 = np.poly1d(z1)
print (p1)
这个是网站上翻的二元拟合,有R方,但是最后结果出来没有公式(主要还是缺少X的系数)
import numpy
def polyfit(x, y, degree):
results = {}
coeffs = numpy.polyfit(x, y, degree)
results['polynomial'] = coeffs.tolist()
# r-squared
p = numpy.poly1d(coeffs)
# fit values, and mean
yhat = p(x) # or [p(z) for z in x]
ybar = numpy.sum(y)/len(y) # or sum(y)/len(y)
ssreg = numpy.sum((yhat-ybar)**2) # or sum([ (yihat - ybar)**2 for yihat in yhat])
sstot = numpy.sum((y - ybar)**2) # or sum([ (yi - ybar)**2 for yi in y])
results['determination'] = ssreg / sstot #准确率
return results
x=[ 1 ,2 ,3 ,4 ,5 ,6]
y=[ 2.5 ,3.51 ,4.45 ,5.52 ,6.47 ,7.51]
z1 = polyfit(x, y, 2)
print (z1)
想问各位大佬要怎么办呀???谢谢