Interpolation is a method of estimating unknown data points in a given dataset range. Discovering new values between two data points makes the curve smoother. Spline interpolation is a type of piecewise polynomial interpolation method.
The SciPy API provides several functions to implement the interpolation method for a given dataset.
In this tutorial, you'll learn how to apply interpolation for a given dataset by using SciPy API functions in Python. The tutorial covers;
- Preparing test data
- Direct spline interpolation
- Spline interpolation with InterpolatedUnivariateSpline
- Source code listing
We'll start by loading the required libraries.
from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
y = [1,3,4,3,5,7,5,6,8,7,8,9,8,7]
n = len(y)
x = range(0, n)
plt.plot(x,y,'ro')
plt.plot(x,y, 'b')
plt.title("Data set and linear interpolation")
plt.show()
To represent spline interpolation smoothing coefficients can be taken parametrically or directly. The 'splrep' function helps us to define the curve with direct method. It provides t, c, k tuple containing the vector of knots, the B-spline coefficients, and the degree of the spline. After taking the coefficients we'll use 'splev' function to evaluate the spline.
The 'splev' evaluates the value of the smoothing polynomial based on given coefficients. Finally, we'll visualize the curve on a graph.
tck = interpolate.splrep(x, y, s=0)
xfit = np.arange(0, n-1, np.pi/50)
yfit = interpolate.splev(xfit, tck, der=0)
plt.plot(x, y, 'ro')
plt.plot(xfit, yfit,'b')
plt.plot(xfit, yfit)
plt.title("Direct spline interpolantion")
plt.show()
s = interpolate.InterpolatedUnivariateSpline(x, y)
xfit = np.arange(0, n-1, np.pi/50)
yfit = s(xfit)
plt.plot(x, y, 'ro')
plt.plot(xfit, yfit,'green')
plt.title("InterpolatedUnivariateSpline interpolation")
plt.show()
from scipy import interpolate
import matplotlib.pyplot as plt
import numpy as np
y = [1,3,4,3,5,7,5,6,8,7,8,9,8,7]
n = len(y)
x = range(0, n)
plt.plot(x,y,'ro')
plt.plot(x,y, 'b')
plt.title("Data set and linear interpolation")
plt.show()
tck = interpolate.splrep(x, y, s=0)
xfit = np.arange(0, n-1, np.pi/50)
yfit = interpolate.splev(xfit, tck, der=0)
plt.plot(x, y, 'ro')
plt.plot(xfit, yfit,'b')
plt.plot(xfit, yfit)
plt.title("Direct spline interpolantion")
plt.show()
s = interpolate.InterpolatedUnivariateSpline(x, y)
xfit = np.arange(0, n-1, np.pi/50)
yfit = s(xfit)
plt.plot(x, y, 'ro')
plt.plot(xfit, yfit,'green')
plt.title("InterpolatedUnivariateSpline interpolation")
plt.show()
No comments:
Post a Comment