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

I do not understand why polynomial.Polynomial.fit() gives coefficients very different from the expected coefficients :

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

Gives :

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

The two first results are OK, and thanks to this answer I understand why the two arrays are in reversed order.

However, I do not understand the signification of the third result. The coefficients looks wrong, though the polynomial that I got this way seems to give correct predicted values.



Solution 1:[1]

Buried in the docs:

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.

So use:

poly.convert()    

This will rescale your coefficients to what you are probably expecting.

Example for data generated from 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())

Output:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1