Polynomial Fitting in Python Using Just One Line of Code

JP Cajanding
Analytics Vidhya
Published in
2 min readApr 21, 2021

--

Curve fitting is one powerful tool when we want to determine or model the relationship between two sets of data and is done by finding the best fit function or curve across the whole range. This function then can be used to interpolate data within the given range or extrapolate possible values outside of the range.

The most common form of curve fitting is linear regression, where we find the line that best describes the relationship of a variable to another variable and use that line for predictions. However, we all know that most data are not in a linear relationship, and polynomials are then a better way of fitting.

Polynomial fitting follows the same concept as linear fitting but here, we are using a n-degree polynomial to describe the relationship of our data. Both however are using the least squares method in determining the best fitting functions.

In python, the most common way of doing curve fitting is using the curve fit function in Scipy.

from scipy.optimize import curve_fit

This is a good approach as the method can be used for fitting all functions, not just polynomials and the only code that you need to change is the code of the function that you want to fit in your data.

However, a problem arises, at least in polynomial fitting, when you want to find the best degree that will fit your data. Yes, you can still write a function for this but that actually complicates the coding part and gives you less time to do the actual analysis.

Good thing is that numpy has a built in function for fitting and can be called by simply calling numpy.polyfit.

Here’s an example code to use this instead of the usual curve fitting method in python.

The code above shows how to fit a polynomial with a degree of five to the rising part of a sine wave. Using this method, you can easily loop different n-degree polynomial to see the best one for your data.

The actual fitting happens in

poly = np.polyfit(x, sine, deg=5)

This method returns the coefficients of the best fit polynomial starting from the highest order to the constant.

The function:

np.polyval(poly, x)

can then be used to evaluate the independent variable x to the polynomial using the coefficients found.

--

--