Home > OS >  using numpy to fit data to y = y = a*x**2 b*x c (where c=0)
using numpy to fit data to y = y = a*x**2 b*x c (where c=0)

Time:10-16

noob question here, please bear with me: I'm trying to use numpy.polynomial.polynomial.Polynomial.fit(x,y,deg).convert().coef to get the coefficients for a zero-intersecting polynomial y = ax**2 bx c (where c=0) fit to a set of measured data. When I use deg=2 or deg=[0,1,2] I get nicely fitting coefficients for a,b,and c. However, when I use deg = [1,2] in order to force c=0, I still get three coefficients and they don't fit at all. What am I doing wrong?

Here is a code example with real data:

import numpy as np
from numpy.polynomial.polynomial import Polynomial as p

x = np.array([0, .1, .5, 1, 2])
y_series = np.array([[2, 319, 1693, 3713, 8695],
                     [3, 327, 1828, 4131, 10111],
                     [3, 304, 1653, 3617, 8678],
                     [4,300,1675,3745,8922],
                     [3, 298,1661,3653,8694],
                     [5, 304,1642,3686,8670],
                     [3, 313,1688,3724,8657],
                     [5, 315,1736,3821,8963],
                     [3, 247,1300,2767,6376]
                     ])

for y in y_series:
    print('x: ', x,'y: ', y)
    print('deg=2:      ', p.fit(x, y, deg=2).convert().coef)
    print('deg=[0,1,2]:', p.fit(x, y, deg=[0,1,2]).convert().coef)
    print('deg=[1,2]:  ', p.fit(x, y, deg=[1,2]).convert().coef)
    print('')

CodePudding user response:

Similar to a previous post you are having trouble with the window argument of the Polynomial class. The coefficients are actually zero in your defined window, which is the default one namely [ -1, 1 ]. If one print the coefficients before calling convert() it is actually zero. Providing the window solves the issue.

Have a look at this:

import numpy as np
from numpy.polynomial.polynomial import Polynomial


def parabola( x, a, b, c , s=0 ):
    if isinstance( x, ( int, float, complex ) ):
        r = np.random.normal( scale=s )
    else:
        r = np.random.normal( scale=s, size=len( x ) )
    return a   b * x   c * x**2   r



xl = np.linspace( -2, 3, 15 )
yl = parabola( xl, 0.01, 0.8, 0.21, s=0.1 )

print("\n p1: ")
p1 = Polynomial.fit( xl, yl, deg=[0,1,2] )
print( p1.coef )
print( p1.convert().coef )

print("\n p2: ")
p2 = Polynomial.fit( xl, yl, deg=[1,2] )
print( p2.coef )
print( p2.convert().coef )
print( p2.domain )
print( p2.window )

print("\n p3: ")
p3 = Polynomial.fit( xl, yl, deg=[1,2], window=[ min( xl ), max( xl ) ] )
print( p3.coef )
  • Related