I have a very specific requirement for interpolating nonlinear data using a 6th degree polynomial. I've seen numpy/scipy routines (scipy.interpolate.InterpolatedUnivariateSpline) that allow interpolation only up to degree 5.
Even if there's no direct function to do this, is there a way to replicate Excel's LINEST linear regression algorithm in Python? LINEST allows 6th degree curve-fitting but I do NOT want to use Excel for anything as this calculation is part of a much larger Python script.
Any help would be appreciated!
The SciPy open source library provides the curve_fit() function for curve fitting via nonlinear least squares. The function takes the same input and output data as arguments, as well as the name of the mapping function to use. The mapping function must take examples of input data and some number of arguments.
In this program, also, first, import the libraries matplotlib and numpy. Set the values of x and y. Then, calculate the polynomial and set new values of x and y. Once this is done, fit the polynomial using the function polyfit().
curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.
You can use scipy.optimize.curve_fit
to fit whatever function you want (within reason) to your data. The signature of this function is
curve_fit(f, xdata, ydata, p0=None, sigma=None, **kw)
and it uses non-linear least squares fitting to fit a function f
to the data ydata(xdata)
. In your case I would try something like:
import numpy
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt
def _polynomial(x, *p):
"""Polynomial fitting function of arbitrary degree."""
poly = 0.
for i, n in enumerate(p):
poly += n * x**i
return poly
# Define some test data:
x = numpy.linspace(0., numpy.pi)
y = numpy.cos(x) + 0.05 * numpy.random.normal(size=len(x))
# p0 is the initial guess for the fitting coefficients, set the length
# of this to be the order of the polynomial you want to fit. Here I
# have set all the initial guesses to 1., you may have a better idea of
# what values to expect based on your data.
p0 = numpy.ones(6,)
coeff, var_matrix = curve_fit(_polynomial, x, y, p0=p0)
yfit = [_polynomial(xx, *tuple(coeff)) for xx in x] # I'm sure there is a better
# way of doing this
plt.plot(x, y, label='Test data')
plt.plot(x, yfit, label='fitted data')
plt.show()
which should give you something like:
Use numpys polyfit routine.
http://docs.scipy.org/doc/numpy-1.3.x/reference/generated/numpy.polyfit.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With