我对Python曲线拟合有疑问, 我知道numpy中有polyfit函数,但是如果我将多项式指定为 A X ^ 4 + B X ^ 2,如何找到这个A和B?
import numpy as np
import matplotlib.pyplot as plt
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
z = np.polyfit(x, y, 4) <---?
f = np.poly1d(z) <---?
有人可以提示吗??? 谢谢!
答案 0 :(得分:1)
您可以尝试使用最小二乘法。基本上找到值A和B,以便残差平方和最小。我为此使用了scipy
。
这是我的代码:
import numpy as np
from scipy.optimize import leastsq
# --------------------------------
import matplotlib as mpl
mpl.rcParams['font.size']=20
import matplotlib.pyplot as plt
# -------------------------------------
points = np.array([(1, 1), (2, 4), (3, 1), (9, 3)])
# get x and y vectors
x = points[:,0]
y = points[:,1]
# calculate polynomial
#z = np.polyfit(x, y, 4) <---?
#f = np.poly1d(z) <---?
# ----------------------------------------------
def poly(p,x):
return p[0]*x**4+p[1]*x**2
def res(p,x,y):
return y-poly(p,x)
# ----------------------------------------------
p0=[1.,1.];
pars=leastsq(res,p0,(x,y));
print pars[0]
# -----------------------------------------------
xi=np.linspace(np.min(x),np.max(x),100);
fig = plt.figure(figsize=(6,6));ax=fig.add_subplot(111);
ax.plot(x,y,ms=10,color='k',ls='none',marker='.');
ax.plot(xi,poly(pars[0],xi),color='0.8',lw=2.0);
plt.savefig('fit_result.png');
plt.show();