How to fix “polyfit maybe poorly conditioned” in numpy?

后端 未结 2 1563
醉酒成梦
醉酒成梦 2021-01-18 11:26

I am trying to do a polyfit on a set of data using numpy package.

The following is the code, it can run successfully. The fitted line seems to fit the data when the o

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-18 11:37

    You will get a better fit if you use the Polynomial class, although if you go past the ends of the data with a high order fit you will see the fast divergence shown above because you are extrapolating. To use the Polynomial class

    from numpy.polynomial import Polynomial as P
    p = P.fit(x, y, order)
    

    You can also experiment with more stable polynomial basis that will be better conditioned at high orders, say 100+, although that is hardly justified with noisy data like you are playing with.

    from numpy.polynomial import Chebyshev as T
    p = T.fit(x, y, order)
    

    You can get in bounds plotting points x, y from the fits like so:

    plot(*p.linspace(500))
    

提交回复
热议问题