【问题标题】:using numpy to fit data to y = y = a*x**2 + b*x + c (where c=0)使用 numpy 将数据拟合到 y = y = a*x**2 + b*x + c(其中 c=0)
【发布时间】:2021-12-03 00:33:34
【问题描述】:

这里是菜鸟问题,请多多包涵: 我正在尝试使用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('')

【问题讨论】:

  • 我们能看到你拟合的数据吗?当您使用deg=[0,1,2] 进行拟合时,拟合的c 系数是否接近于零?查看您正在运行以计算和查看拟合的完整代码也可能会有所帮助。
  • 我已经用一些代码修改了我的帖子。是的,对于我拥有的数据,c 系数接近于零。但如果数据变得更加嘈杂,情况可能并不总是如此。但在物理上,它固定为零。

标签: numpy data-fitting


【解决方案1】:

与之前的 post 类似,您在使用 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 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-07
    相关资源
    最近更新 更多