Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ENH: Change behavior for numpy.polynomial.polynomial.Polynomial.fit coefficients #26401

Open
Lolcroc opened this issue May 8, 2024 · 3 comments

Comments

@Lolcroc
Copy link

Lolcroc commented May 8, 2024

Currently polynomial fits work as follows

x = [0, 1]
y = [0, 1]
fit = Polynomial.fit(x, y, deg=1)

print(f"Coefficients for 1-order fit on {x=}, {y=}:")
print(f"Raw: {fit.coef}")
print(f"Converted: {fit.convert().coef}")

which prints

Coefficients for 1-order fit on x=[0, 1], y=[0, 1]:
Raw: [0.5 0.5]
Converted: [-1.66533454e-16  1.00000000e+00]

The result for the raw fit.coef is unexpected. The fit is scaled with respect to its current domain, which is by default the endpoints of x. The fit.convert().coef gives the expected result, but this extra call is somewhat awkward and can easily be overlooked.

Proposed new feature or change:

I would prefer to set domain=[-1, 1] as a default argument of numpy.polynomial.polynomial.Polynomial.fit, just as it is for the numpy.polynomial.polynomial.Polynomial class. This creates commonality, but also avoids the unexpected outcome as in the above example.

@olcc
Copy link

olcc commented May 20, 2024

I would say that the expansion on the polynomial basis is accurate over the window range.
This range is usually [-1,1], but for the Laguerre polynomial basis it is [0,1].
The domain represents the range of the x data and is meant to be mapped onto the window range.
Setting domain=[-1,1] as a default argument for the fit() method would increase numerical error.

However, I agree that P.coef is misleading, because it does not describe the coefficients of polynomial P in its natural variable x. It rather describes the coefficients of the internal representation of P. Most users probably only use P.convert().coef.

An improvement may be to hide the coefficients into a P._coef variable, and let P.coef return P.convert()._coef. Of course, this would break existing code.

@rkern
Copy link
Member

rkern commented May 20, 2024

The semantics of .coef can't change at this time. One could propose that there be an additional attribute that is equivalent to .convert().coef (either computed greedily or lazily) so that this common case is easy to access.

@olcc
Copy link

olcc commented May 20, 2024

A @property named P.coeffs could do the trick, where the property docstring would explain the difference with P.coef.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants