Вопрос

I try to generate a generic fit polynom using SciPy's curve_fitmethod. My current simplified code looks like the following:

import functools
import scipy.optimize

def __fit_polynom_order_6(self, data):
    def func(x, c1=None, c2=None, c3=None, c4=None, c5=None, c6=None):
        return c1*x + c2*x**2 + c3*x**3 + c4*x**4 + c5*x**5 + c6*x**6

    x, y = data[:,0], data[:,1]
    popt, pcov = scipy.optimize.curve_fit(func, x, y)

    func_fit = functools.partial(func, c1=popt[0],c2=popt[1],c3=popt[2],c4=popt[3],c5=popt[4],c6=popt[5])

    return func_fit

Now I want also to do fits with polynoms of order n and thus generate a generic function __fit_polynom_order_n(self, n, data) that generates the polynom automatically and does essentially the same thing as my function above but with arbitrary polynoms.

My attempts doing this all came to nothing. Can you help? Thanks in advance!

Это было полезно?

Решение

There is already a function for that, np.polyfit:

fit = np.polyfit(x, y, n)

On the other hand, your func does not have a constant term. Is that on purpose?

If you wish to write your own polyfit-type method, you might want to study the source code for np.polyfit. You'll see that the problem is set up as a linear matrix equation and solved with np.linalg.lstsq, rather than the more general-purpose scipy.optimize.curve_fit.

# set up least squares equation for powers of x
lhs = vander(x, order)
rhs = y
c, resids, rank, s = lstsq(lhs, rhs, rcond)

Useful reference:

  • np.vander -- aha, this can be used to evaluate the polynomial at x. If you want to eliminate the constant term, you'd have to chop off the right-most column returned by np.vander.
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top