Skip to content Skip to sidebar Skip to footer

Curve_fit With Polynomials Of Variable Length

I'm new to python (and programming in general) and want to make a polynomial fit using curve_fit, where the order of the polynomials (or the number of fit parameters) is variable.

Solution 1:

You can define the function to be fit to your data like this:

def fit_func(x, *coeffs):
    y = np.polyval(coeffs, x)
    return y

Then, when you call curve_fit, set the argument p0 to the initial guess of the polynomial coefficients. For example, this plot is generated by the script that follows.

plot

import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt


# Generate a sample input dataset for the demonstration.
x = np.arange(12)
y = np.cos(0.4*x)


deffit_func(x, *coeffs):
    y = np.polyval(coeffs, x)
    return y


fit_results = []
for n inrange(2, 6):
    # The initial guess of the parameters to be found by curve_fit.# Warning: in general, an array of ones might not be a good enough# guess for `curve_fit`, but in this example, it works.
    p0 = np.ones(n)

    popt, pcov = curve_fit(fit_func, x, y, p0=p0)
    # XXX Should check pcov here, but in this example, curve_fit converges.

    fit_results.append(popt)


plt.plot(x, y, 'k.', label='data')

xx = np.linspace(x.min(), x.max(), 100)
for p in fit_results:
    yy = fit_func(xx, *p)
    plt.plot(xx, yy, alpha=0.6, label='n = %d' % len(p))

plt.legend(framealpha=1, shadow=True)
plt.grid(True)
plt.xlabel('x')
plt.show()

Post a Comment for "Curve_fit With Polynomials Of Variable Length"