numpy polynomial.Polynomial.fit() 给出的系数与 polynomial.polyfit() 不同

numpy polynomial.Polynomial.fit() gives different coefficients than polynomial.polyfit()

我不明白为什么 polynomial.Polynomial.fit() 给出的系数与预期的系数非常不同:

import numpy as np

x = np.linspace(0, 10, 50)
y = x**2 + 5 * x + 10

print(np.polyfit(x, y, 2))
print(np.polynomial.polynomial.polyfit(x, y, 2))
print(np.polynomial.polynomial.Polynomial.fit(x, y, 2))

给出:

[ 1.  5. 10.]
[10.  5.  1.]
poly([60. 75. 25.])

前两个结果还可以,感谢我明白了为什么两个数组顺序相反

但是,我不明白第三个结果的含义。系数看起来不对,尽管我通过这种方式得到的多项式似乎给出了正确的预测值。

当然,答案稍微隐藏在文档中。看着 class numpy.polynomial.polynomial.Polynomial(coef, domain=None, window=None) 很明显,通常系数 [abc、...] 是多项式 a + b * x + c * x**2 + ... 的系数。但是,关键字参数 domainwindow 都默认为 [-1,1]。我不喜欢那个 class,所以我不确定目的,但很明显会发生重新映射。现在在 polynomial.Polynomial.fit() 的情况下,有一个 class 方法自动将 x 数据作为域,但仍然映射到 window。因此,在 OP 中 [0-10] 被映射到 [-1,1]。这是由 x = x' / 5 - 1x' -> 5 * x + 5 完成的。将后者放入我们得到的 OP 多项式中

( 5 x' + 5 )**2 + 5 * ( 5 * x' + 5 ) + 10 = 25 * x'**2 + 75 * x' + 60

瞧。

要获得预期的结果,必须输入

print(np.polynomial.polynomial.Polynomial.fit(x, y, 2, window=[0, 10] ) )

至于

poly([10.  5.  1.])

埋在文档中:

Note that the coefficients are given in the scaled domain defined by the linear mapping between the window and domain. convert can be used to get the coefficients in the unscaled data domain.

所以使用:

poly.convert()    

这会将您的系数重新调整为您可能期望的值。

从 1 + 2x + 3x^2 生成的数据示例:

from numpy.polynomial import Polynomial

test_poly = Polynomial.fit([0, 1, 2, 3, 4, 5],
                           [1, 6, 17, 34, 57, 86],
                           2)

print(test_poly)
print(test_poly.convert())

输出:

poly([24.75 42.5  18.75])
poly([1. 2. 3.])