python做資料擬合

2021-07-25 04:31:33 字數 2789 閱讀 4545

專案中有涉及趨勢**的工作,整理一下這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("擬合結果: y = %10.5f x + %10.5f , r=%10.5f" % (a,b,r) )

#結果為: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)  #一次多項式擬合,相當於線性擬合

p1 = np.poly1d(z1)

print z1  #[ 1.          1.49333333]

print p1  # 1 x + 1.493

2、二次多項式擬合

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.2]

z1 = polyfit(x, y, 2)

print z1

3、對數函式擬合-這個是最難的,baidu上都找不到,google了半天才找到的。指數、冪數擬合啥的,都用這個,把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

python資料擬合怎麼做的 將資料擬合到分布?

這是個複雜的問題,沒有完美的答案,對於給定的資料,有兩種設定概率分布函式引數的方法 在我的經驗中,最近幾年最大似然是首選的,儘管這可能不是每個領域的情況。這是如何估算r中引數的具體示例。考慮從高斯分布生成的一組隨機點,它均值為0,標準差為1 x rnorm n 100,mean 0,sd 1 在r中...

python 線性擬合

1 線性擬合 使用math import math deflinefit x,y n float len x sx,sy,sxx,syy,sxy 0,0,0,0,0for 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...

Python 高斯擬合

通常我們進行高斯擬合的辦法是匯入scipy的curve fit 包,不過這需要自己手寫乙個高斯分布的函式表示式,不是很方便,astropy提供了乙個寫好的高斯擬合包 調包from astropy.modeling import models,fitting import numpy as np im...