Numpy Polyfit Explained With Examples

Hello geeks and welcome in this article, we will cover NumPy.polyfit(). Along with that, for an overall better understanding, we will look at its syntax and parameter. Then we will see the application of all the theory parts through a couple of examples. But first, let us try to get a brief understanding of the function through its definition.

The function NumPy.polyfit() helps us by finding the least square polynomial fit. This means finding the best fitting curve to a given set of points by minimizing the sum of squares. It takes 3 different inputs from the user, namely X, Y, and the polynomial degree. Here X and Y represent the values that we want to fit on the 2 axes. Up next, let us look at its syntax.

Syntax Of Numpy Polyfit()

numpy.polyfit(xydegrcond=Nonefull=Falsew=Nonecov=False)

Given above is the general syntax of our function NumPy polyfit(). It has 3 compulsory parameters as discussed above and 4 optional ones, affecting the output in their own ways. Next, we will discuss the various parameters associated with it.

Parameters Of Numpy Polyfit()

1. X:array_like

It represents the set of points to be presented along X-axis.

2. Y:array_like

This parameter represents all sets of points to be represented along the Y-axis.

3. Deg: int

This parameter represents the degree of the fitting polynomial.

4. rcond: float

It is an optional parameter that is responsible for defining a relative number condition of the fit. Singular values smaller than this relative to the largest singular values are ignored.

5.full: bool

This an optional parameter that switches the determining nature of the return value. By default, the value is set to false due to which only the coefficients are returned. If the value is specified to true, then the decomposition singular value is also returned.

6.w:array_like

This optional parameter represents the weights to apply to the y-coordinate of the sample points.

7.Cov:bool or str

This optional parameter if given and not false returns not Just an array but also a covariance matrix.

Return

P: nadarray

It returns the polynomial coefficient with the highest power first.

residuals, rank, rcond

We get this only if the “full=True”. Residual is the sum of squared residuals of the least square fit.

V: ndarray

We get this only if the “full=false” and “cov=true”. Along with that, we get a covariance matrix of the polynomial coefficient estimate.

Examples Of Numpy Polyfit

Now let us look at a couple of examples that will help us in understanding the concept. At first, we will start with an elementary example, and moving ahead will look at some complex ones.

#input
import numpy as ppool
x=[1,2,3]
y=[3,45,5]
print(ppool.polyfit(x,y,2))

Output:

[ -41.  165. -121.]

In the above example, we can see NumPy.polyfit(). At first, we have imported NumPy. Moving ahead we have defined 2 arrays X and Y. X here represents all the points we want to represent along the X-axis and similarly for Y. Then we have used our defined syntax name. polyfit(x,y, deg) and a print statement to get the desired output. In this example, we have not used any optional parameter.

Now let us see a more complex example.

#input
import numpy as ppool
x=[1,2,3]
y=[4,5,6]
print(ppool.polyfit(x,y,2,full="true"))
(array([-1.3260643e-15,  1.0000000e+00,  3.0000000e+00]), array([], dtype=float64), 3, array([1.67660833, 0.43259345, 0.04298142]), 6.661338147750939e-16)

In the above example, again, we have followed similar steps as in the above example. But this time, we have used the optional variable full and defined it as true. The difference can be spotted in the output as we get a residual.

Now let us look at one more example

#input
import numpy as ppool
x=[1,2,3]
y=[4,5,6]
print(ppool.polyfit(x,y,2,full="false",cov="true"))

Output:

(array([-1.3260643e-15,  1.0000000e+00,  3.0000000e+00]), array([], dtype=float64), 3, array([1.67660833, 0.43259345, 0.04298142]), 6.661338147750939e-16)

Similar to the above example with the only difference of “cov.” For this example we have added cov =”true” and specified full=”false”. As a result of which in output, we get a covariance matrix.

Plot Linear Regression Line Using Matplotlob and Numpy Polyfit

Code:

import numpy as np
import matplotlib.pyplot as plt

x = [1,2,3,4]
y = [5,9,13,16]

coef = np.polyfit(x,y,1)
poly1d_fn = np.poly1d(coef) 

plt.plot(x,y, 'yo', x, poly1d_fn(x))
plt.xlim(0, 5)
plt.ylim(0, 20)
plt.show()

Output:

Linear Regression Numpy Polyfit

Explanation:

You can use the poly1d function of numpy to generate the best fitting line equation from polyfit. This equation can be used in plt.plot() to draw a line along with your data.

Numpy Polyfit Alternative

Numpy polyfit sets data in polynomial function. Least square method can be used in place of the numpy polyfit method. It is faster than the latter if we time it. Its syntax is: 

lstsq(x, y)

Numpy Polyfit Bounds

We can specify the limits with polyfit. Just subtract the limit from x and y. So in this case, the plot will not have y values exceeding 200 and x values exceeding 0.50.

Plot = poly.polyfit(x-0.50, y-200, [1,2,3])

Numpy polyfit Correlation Coefficient

Use polyfit to fit the coefficients to specified degree and then use corrcoef() function to find the value of the correlation coefficient,r.

Example:

co = numpy.polyfit(a, b, degree)
results['poly'] = co.tolist()

corr = numpy.corrcoef(a,b)[0,1]

Numpy Polyfit Ignore Nan

Polyfit can’t work with x and y values that are NAN so we need to pass only those values that are not NAN.

index = np.isfinite(x) & np.isfinite(y)
Result = np.polyfit(x[index], y[index], 1)

Numpy Polyfit vs Linear Regression

Numpy.polyfitLinear Regression
Numpy.polyfit works on polynomial fit of least squares. It estimates the polynomial regression of a single variable and extra statistical analysis is not offered. On the other hand, linear regression only handles the case of a variable with specialized code, extra statistical analysis is also made.
It can fit a polynomial of any order to a given x and y relationship.It can only fit a line.
For small vectors, it works faster.It is slower than numpy polyfit for smaller vectors.

FAQs

What does numpy Polyfit return?

It returns an equation which has fit the given polynomials, x and y. 

What is the difference between SciPy curve fit and numpy Polyfit?

Polyfit provides the programmer with a better curve and estimate of polynomial function than the SciPy curve.

Must Read

Conclusion

In this article, we have covered NumPy.polyfit(). Besides that, we have also looked at its syntax and parameters. For better understanding, we looked at a couple of examples. We varied the syntax and looked at the output for each case. I hope this article was able to clear all doubts. But in case you have any unsolved queries feel free to write them below in the comment section. Done reading this, why not read NumPy digitize next.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments