使用numpy拟合数据到y = y = a*x**2 + b*x + c(其中c=0)



这里有一个新手问题,请耐心听我说:我试图使用numpy.polynomial.polynomial.Polynomial.fit(x,y,deg).convert().coef来获得零相交多项式y = ax**2 + bx + c(其中c=0)适合一组测量数据的系数。当我使用deg=2或deg=[0,1,2]时,我可以很好地拟合a,b和c的系数。然而,当我使用deg=[1,2]来强迫c=0时,我仍然得到三个系数,它们根本不适合。我做错了什么?

下面是一个真实数据的代码示例:

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('')

与之前的帖子类似,您在Polynomial类的window参数中遇到麻烦。系数实际上是零在您定义的窗口,这是默认的一个,即[ -1, 1 ]。如果在调用convert()之前打印系数,它实际上是零。提供窗口可以解决问题。

看看这个:

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 )

最新更新