2020-04-23 16:12

# numpy做线性拟合并有R-square

``````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)
``````

``````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)
``````

• 写回答
• 好问题 提建议
• 追加酬金
• 关注问题
• 邀请回答

#### 1条回答默认 最新

• 吃鸡王者 2020-04-23 17:28

np.polyfit(X, Y, 2) 就可以拟合二次多多项式啊
np.polyfit(X, Y, n) 可以拟合一元n次多项式

评论
解决 无用 2
打赏 举报