python: 曲線擬合

多項式擬合

擬合函數y=p0xn+p1xn1+...+pny=p_0x^n+p_1x^{n-1}+...+p_n

方法numpy.polyfit(x, y, deg)
deg即爲擬合函數中的n,表示幾階多項式,比如deg=1,即線性擬合y=p0x+p1y=p_0x+p_1, deg=2,即二次曲線擬合y=p0x2+p1x+p2y=p_0x^2+p_1x+p_2,

實例

n = 10
x = np.arange(n)
y = 2*x+4 + np.random.uniform(-1,1,n)
p = np.polyfit(x,y,1)
y_fit = np.polyval(p,x)
# y_fit = p[0]*x+p[1]
print('p:',p)
_, ax = plt.subplots()
ax.plot(x,y,'.',x,y_fit)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(('y','y_fit'))

結果

p: [2.00033669 3.88812688]

在這裏插入圖片描述

指數擬合

實例:

def func(x,a,b,c):
    return a*np.power(b,x)+c

x = np.arange(0,1000,10)
y = np.power(0.995,x) + np.random.uniform(-0.1,0.1,len(x))
p_opt,p_cov = curve_fit(func,x,y)
y_fit = func(x,*p_opt)

print('p_opt:',p_opt)
_, ax = plt.subplots()
ax.plot(x,y,'.',x,y_fit)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.legend(('y','y_fit'))

結果:

p_opt: [ 0.9986722   0.99532845 -0.01810115]

在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章