用python的numpy作线性拟合、多项式拟合、对数拟合
轉(zhuǎn)自:http://blog.itpub.net/12199764/viewspace-1743145/
項(xiàng)目中有涉及趨勢預(yù)測的工作,整理一下這3種擬合方法:
1、線性擬合-使用math
import math
def linefit(x , y):
? ? N = float(len(x))
? ? sx,sy,sxx,syy,sxy=0,0,0,0,0
? ? for i in range(0,int(N)):
? ? ? ? sx ?+= x[i]
? ? ? ? sy ?+= y[i]
? ? ? ? sxx += x[i]*x[i]
? ? ? ? syy += y[i]*y[i]
? ? ? ? sxy += x[i]*y[i]
? ? a = (sy*sx/N -sxy)/( sx*sx/N -sxx)
? ? b = (sy - a*sx)/N
? ? r = abs(sy*sx/N-sxy)/math.sqrt((sxx-sx*sx/N)*(syy-sy*sy/N))
? ? return a,b,r
if __name__ == '__main__':
? ? X=[ 1 ,2 ?,3 ,4 ,5 ,6]
? ? Y=[ 2.5 ,3.51 ,4.45 ,5.52 ,6.47 ,7.51]
? ? a,b,r=linefit(X,Y)
? ? print("X=",X)
? ? print("Y=",Y)
? ? print("擬合結(jié)果: y = %10.5f x + %10.5f , r=%10.5f" % (a,b,r) )
#結(jié)果為:y = ? ?0.97222 x + ? ?1.59056 , r= ? 0.98591
1、線性擬合-使用numpy
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) ?#一次多項(xiàng)式擬合,相當(dāng)于線性擬合
p1 = np.poly1d(z1)
print z1 ?#[ 1. ? ? ? ? ?1.49333333]
print p1 ?#?1 x + 1.493
2、二次多項(xiàng)式擬合
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 #準(zhǔn)確率
? ? return results
x=[ 1 ,2 ?,3 ,4 ,5 ,6]
y=[ 2.5 ,3.51 ,4.45 ,5.52 ,6.47 ,7.2]
z1 = polyfit(x, y, 2)
print z1
3、對數(shù)函數(shù)擬合-這個是最難的,baidu上都找不到,google了半天才找到的。指數(shù)、冪數(shù)擬合啥的,都用這個,把func改寫一下就行
from scipy import log as log print pcov
import numpy
from scipy import log
from scipy.optimize import curve_fit
def func(x, a, b):
? ? y = a * log(x) + b
? ? return y
def polyfit(x, y, degree):
? ? results = {}
? ? #coeffs = numpy.polyfit(x, y, degree)
? ? popt, pcov = curve_fit(func, x, y)
? ? results['polynomial'] = popt
? ? # r-squared
? ? yhat = func(x ,popt[0] ,popt[1] ) ? ? ? ? ? ? ? ? ? ? ? ? # 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
轉(zhuǎn)載于:https://www.cnblogs.com/gslyyq/p/5043847.html
總結(jié)
以上是生活随笔為你收集整理的用python的numpy作线性拟合、多项式拟合、对数拟合的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 看了这么多期的《爸爸去哪儿》,为什么我最
- 下一篇: JAVA的instanceOf什么时候用