Spline Interpolation in Python

Rana Hasnain Khan Oct 10, 2023
  1. SciPy Interpolation in Python
  2. Spline Interpolation in Python
Spline Interpolation in Python

We will introduce the SciPy module with some interpolation techniques in Python. We will also introduce spline interpolation in Python with examples.

SciPy Interpolation in Python

When we work with data to get the predictions, we need to go through interpolation in Python. We use it to construct data points between given data points.

Python provides a built-in module, scipy.interpolate, that can be used to achieve interpolation. It consists of classes, spline functions, univariate and multivariate interpolation classes.

There are many ways of interpolations, as shown below.

  1. Spline interpolation
  2. RBF interpolation
  3. 1-D interpolation
  4. Univariate Spline interpolation

In this tutorial, we will learn spline interpolation in detail.

Spline Interpolation in Python

To draw smooth curves through data points, we use spline interpolation. We compute the spline representation of the curve, and after that, we can compute the spline at the desired points.

We can use the function splrep to find the spline representation in a two-dimensional plane. If we want to compute the B-spline or its derivatives, scipy.interpolate.splev is used as shown below.

# python
# for B-spline representation of a 1-D curve
scipy.interpolate.splrep(x, y, s=1)

# for B-spline or derivatives
spicy.interpolate.splev(x, tck, der)

Now, let’s go through an example and try to find the spline interpolation. First of all, we will install NumPy, Matplotlib, and SciPy using the following commands.

pip install numpy
pip install matplotlib
pip install scipy

These commands will install the required modules, and once we have installed them, we will import them in our main.py file, as shown below.

# python
import numpy as np
import matplotlib.pyplot as plt
from scipy import interpolate

We will define the points on the graph as shown below.

# python
y = [1, 3, 5, 7, 2, 4, 9, 6]
n = len(y)
x = range(0, n)

We will create the figure and make curved spline interpolation using the above methods.

# python
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("Spline interpolation In Python")
plt.show()

Output:

spline interpolation in python

As you can see from the above example that we can easily create a spline interpolation using the above methods.

Rana Hasnain Khan avatar Rana Hasnain Khan avatar

Rana is a computer science graduate passionate about helping people to build and diagnose scalable web application problems and problems developers face across the full-stack.

LinkedIn

Related Article - Python Interpolation