fitting data with numpy

后端 未结 2 663
长情又很酷
长情又很酷 2020-11-28 21:58

Let me start by telling that what I get may not be what I expect and perhaps you can help me here. I have the following data:

>>> x
array([ 3.08,  3         


        
相关标签:
2条回答
  • 2020-11-28 22:19

    Note that you can use the Polynomial class directly to do the fitting and return a Polynomial instance.

    from numpy.polynomial import Polynomial
    
    p = Polynomial.fit(x, y, 4)
    plt.plot(*p.linspace())
    

    p uses scaled and shifted x values for numerical stability. If you need the usual form of the coefficients, you will need to follow with

    pnormal = p.convert(domain=(-1, 1))
    
    0 讨论(0)
  • 2020-11-28 22:22

    Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

    In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
    Out[40]: 
    array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,
              0.65459882])
    
    In [41]: np.polyfit(x, y, 4)
    Out[41]: 
    array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,
             84.29340846])
    

    In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

    So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

    ffit = np.polyval(coefs[::-1], x_new)
    

    However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

    You're safest to use only the polynomial package:

    import numpy.polynomial.polynomial as poly
    
    coefs = poly.polyfit(x, y, 4)
    ffit = poly.polyval(x_new, coefs)
    plt.plot(x_new, ffit)
    

    Or, to create the polynomial function:

    ffit = poly.Polynomial(coefs)    # instead of np.poly1d
    plt.plot(x_new, ffit(x_new))
    

    fit and data plot

    0 讨论(0)
提交回复
热议问题