Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] np.ployfit() — Curve Fitting with NumPy Polyfit

#1
np.ployfit() — Curve Fitting with NumPy Polyfit

<div><p class="has-pale-cyan-blue-background-color has-background">The .<code>polyfit()</code> function, accepts three different input values: <code>x</code>, <code>y</code> and the polynomial degree. Arguments <code>x</code> and <code>y</code> correspond to the values of the data points that we want to fit, on the <code>x</code> and <code>y</code> axes, respectively. The third parameter specifies the degree of our polynomial function. For example, to obtain a linear fit, use degree 1. </p>
<h2>What is Curve Fitting?</h2>
<p>Curve fitting consists in building a mathematical function that is able to fit some specific data points. Most of the times, the fitting equation is subjected to constraints; moreover, it is also possible to make initial guess for providing useful starting points for the estimation of the fitting parameters, this latter procedure has the advantage of lowering the computational work. In this article we will explore the <a href="https://blog.finxter.com/numpy-tutorial/" target="_blank" rel="noreferrer noopener" title="NumPy Tutorial – Everything You Need to Know to Get Started">NumPy</a> function <code>.polyfit()</code>, which enables to create polynomial fit functions in a very simple and immediate way.</p>
<h2>Linear fit</h2>
<p>The simplest type of fit is the linear fit (a first-degree polynomial function), in which the data points are fitted using a straight line. The general equation of a straight line is:</p>
<p><em><strong>y = mx + q</strong></em></p>
<p>Where “m” is called <em>angular coefficient</em> and “q” <em>intercept</em>. When we apply a linear fit, we are basically searching the values for the parameters “m” and “q” that yield the best fit for our data points. In Numpy, the function <code>np.polyfit()</code> is a very intuitive and powerful tool for fitting datapoints; let’s see how to fit a random series of data points with a straight line.&nbsp;</p>
<p>In the following example, we want to apply a linear fit to some data points, described by the arrays <em><code>x</code></em> and <em><code>y</code></em>. The .<code>polyfit()</code> function, accepts three different input values: <code>x</code>, <code>y</code> and the polynomial degree. While <code>x</code> and <code>y</code> correspond to the values of the data points that we want to fit, on the <code>x</code> and <code>y</code> axes, respectively; the third parameter specifies the degree of our polynomial function. Since we want a linear fit, we will specify a degree equal to 1. The outputs of the <code>polyfit()</code> function will be a list containing the fitting parameters; the first is the one that in the function is multiplied by the highest degree term; the others then follow this order. </p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">import numpy as np
from numpy import random #it will be useful for generating some random noise (on purpose) in the data points that we want to fit
import matplotlib.pyplot as plt #for plotting the data #---LINEAR FIT---- #generate the x array
x = np.linspace(0,60,60) # generate an array of 60 equally space points #generate the y array exploiting the random.randint() function to introduce some random noise
y = np.array([random.randint(i-2, i+2) for i in x]) #each element is a random number with value between +-2 the respective x axis value #Applying a linear fit with .polyfit()
fit = np.polyfit(x,y,1)
ang_coeff = fit[0]
intercept = fit[1]
fit_eq = ang_coeff*x + intercept #obtaining the y axis values for the fitting function #Plotting the data
fig = plt.figure()
ax = fig.subplots()
ax.plot(x, fit_eq,color = 'r', alpha = 0.5, label = 'Linear fit')
ax.scatter(x,y,s = 5, color = 'b', label = 'Data points') #Original data points
ax.set_title('Linear fit example')
ax.legend()
plt.show()</pre>
<p>As mentioned before, the variable <em><code>fit</code></em> will contain the fitting parameters. The first one is the angular coefficient, the last one the intercept. At this point, in order to plot our fit, we have to build the y-axis values from the obtained parameters, using the original x-axis values. In the example, this step is described by the definition of the <em><code>fit_eq</code> </em>variable. The last remaining thing is to plot the data and the fitting equation. The result is:</p>
<div class="wp-block-image">
<figure class="aligncenter"><img src="https://lh3.googleusercontent.com/dhXLJOqybXaBF01uEDb9DE3Pkszl-cYThx2JtdWZ_TTLASnYzSKSt7RH9d0ZzMPnYLL4L72WgnHEzGpnq7lDgrgWYnqrTSD6xjGxDQx38lYwOy5h2TbZOdZ2Wmb7rpaPlf4lwxjfR3aV7XGSLQ" alt=""/></figure>
</div>
<h2>Polynomial fit of second degree</h2>
<p>In this second example, we will create a second-degree polynomial fit. The polynomial functions of this type describe a parabolic curve in the <em>xy</em> plane; their general equation is:</p>
<p><em><strong>y = ax<sup>2</sup><sub> </sub>+ bx + c</strong></em></p>
<p>where <em>a</em>, <em>b</em> and <em>c</em> are the equation parameters that we estimate when generating a fitting function. The data points that we will fit in this example, represent the trajectory of an object that has been thrown from an unknown height. Exploiting the <code>.polyfit()</code> function, we will fit the trajectory of the falling object and we will also obtain an estimate for its initial speed in the x-direction, <em>v<sub>0</sub></em>.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">#-----POLYNOMIAL FIT----
x = np.array([1.2,2.5,3.4,4.0,5.4,6.1,7.2,8.1,9.0,10.1,11.2,12.3,13.4,14.1,15.0]) # x coordinates
y = np.array([24.8,24.5,24.0,23.3,22.4,21.3,20.0,18.5,16.8,14.9,12.8,10.5,8.0,5.3,2.4]) # y coordinates
fit = np.polyfit(x, y, 2)
a = fit[0]
b = fit[1]
c = fit[2]
fit_equation = a * np.square(x) + b * x + c
#Plotting
fig1 = plt.figure()
ax1 = fig1.subplots()
ax1.plot(x, fit_equation,color = 'r',alpha = 0.5, label = 'Polynomial fit')
ax1.scatter(x, y, s = 5, color = 'b', label = 'Data points')
ax1.set_title('Polynomial fit example')
ax1.legend()
plt.show()</pre>
<p>Once initialized the <code>x</code> and <code>y</code> arrays defining the object trajectory, we apply the function <code>.polyfit()</code>, this time inserting “2” as degree of the polynomial fit function. This is because the trajectory of a falling object can be described by a second-degree polynomial; in our case the relation between the <code>x</code> and <code>y</code> coordinates is given by:</p>
<p><em>y = y</em><em><sub>0</sub></em><em> – ½ (g/ v</em><em><sub>0</sub></em><em><sup>2</sup></em><em>)x</em><em><sup>2</sup></em></p>
<p>where <em>y<sub>0 </sub></em>is the initial position (the height from which the object has been thrown), <em>g </em>the acceleration of gravity (  ̴9.81 m/s<sup>2</sup>) and <em>v<sub>0</sub></em> the initial speed (m/s) in the x-direction (visit: <a href="https://en.wikipedia.org/wiki/Equations_for_a_falling_body" target="_blank" rel="noreferrer noopener">https://en.wikipedia.org/wiki/Equations_for_a_falling_body</a> for more details). We then assign at the variables <em><code>a</code>, <code>b</code></em> and <em><code>c</code> </em>the value of the 3 fitting parameters and we define <em><code>fit_equation</code></em>, the polynomial equation that will be plotted; the result is:</p>
<div class="wp-block-image">
<figure class="aligncenter"><img src="https://lh6.googleusercontent.com/vl3GLU5HwQX7wWMbr0b-fl88boeFcO5LUY9itI95J4AiI6QHgGQD7tr-Mk8lUXW4MCt-07hS7szDXc_qpYdR5NnsJRtDLNPsvjR61F-5SGwDrsNGK-XlNCPeSM0Ke4ClNryKcSgeZ6VKo0HKUw" alt=""/></figure>
</div>
<p>If we now print the three fitting parameters, <em>a,b</em> and <em>c</em>, we obtain the following values: <em>a = -0.100 , b = 0.038, c = 24.92.</em> In the equation describing the trajectory of a falling body there is no <em>b</em> term; since the fit is always an approximation of the real result, we will always get a value for all the parameters; however we shall notice that the value of our <em>b</em> term is much smaller than the others and can be somehow neglected, when comparing our fit with the equation describing the physics of the problem. The <em>c</em> term represents the initial height (<em>y</em><em><sub>0</sub></em>) while the <em>a </em>term describes the quantity <em>– ½ (g/ v</em><em><sub>0</sub></em><em><sup>2</sup></em><em>)</em>. Hence, the initial velocity <em>v</em><em><sub>0</sub></em><em> </em>is given by:</p>
<p><em>v0=2-g2a</em></p>
<p>Yielding the final value of <em>v<sub>0</sub> = 6.979 m/s.</em></p>
</p>
<p>The post <a href="https://blog.finxter.com/np-ployfit/" target="_blank" rel="noopener noreferrer">np.ployfit() — Curve Fitting with NumPy Polyfit</a> first appeared on <a href="https://blog.finxter.com/" target="_blank" rel="noopener noreferrer">Finxter</a>.</p>
</div>


https://www.sickgaming.net/blog/2020/11/...y-polyfit/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016