多項式擬合
擬合函數:
方法:numpy.polyfit(x, y, deg)
deg即爲擬合函數中的n,表示幾階多項式,比如deg=1,即線性擬合, deg=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]