【问题标题】:Python curve fitting by specific polynominal通过特定多项式拟合 Python 曲线
【发布时间】:2019-03-02 06:53:04
【问题描述】:

我有一个关于 Python 曲线拟合的问题, 我知道 numpy 中有 polyfit 函数,但是如果我将多项式分配为 AX^4 + BX^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)         <---?   

谁能给个提示??? 谢谢!

【问题讨论】:

    标签: python curve-fitting


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2018-02-16
      • 2019-09-05
      • 1970-01-01
      • 2012-08-05
      • 2019-10-10
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 2021-10-29
      相关资源
      最近更新 更多