How to do it...

This code represents the main part of the function and how to solve it:

import numpy
import scipy
import matplotlib.pyplot as plt
x=numpy.linspace(0,1,10)
y=numpy.sin(x*numpy.pi/2)
line=numpy.polyfit(x,y,deg=1)
plt.plot(x,y,'.',x,numpy.polyval(line,x),'r')
plt.show()

This gives the following plot that shows linear regression with polyfit:

Curve fitting is also possible with splines if we use the parameters wisely. For example, in the case of univariate spline fitting that we introduced before, we can play around with the weights, smoothing factor, the degree of the smoothing spline, and so on. If we want to fit a parabolic spline for the same data as the previous example, we could issue the following commands:

import numpy
import scipy.interpolate
import matplotlib.pyplot as plt
x=numpy.linspace(0,1,10)
y=numpy.sin(x*numpy.pi/2)
spline=scipy.interpolate.UnivariateSpline(x,y,k=2)
xn=numpy.linspace(0,1,100)
plt.plot(x,y,'.', xn, spline(xn))
plt.show()

This gives a graph that shows curve fitting with splines.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset