TExcelTAD
Home › SciPy › SciPy Splines and 2D Interpolation

SciPy Splines and 2D Interpolation

The Interpolation lesson drew curves that pass exactly through every data point. That's right for clean data, but measured data is noisy, and a curve that hits every noisy point wiggles needlessly. This lesson covers smoothing splines, which trade exactness for smoothness, and interpolation in two dimensions, on grids and on scattered points.

Smoothing splines

make_smoothing_spline(x, y, lam=...) fits a cubic spline that balances closeness to the data against how much it bends. The lam parameter sets the trade-off: small values follow the data closely, large values give a smoother, flatter curve. If you leave it out, SciPy chooses lam automatically by cross-validation:

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from scipy.interpolate import make_smoothing_spline, CubicSpline

rng = np.random.default_rng(12)
x = np.linspace(0, 10, 40)
truth = np.sin(x) + 0.3 * x
y = truth + rng.normal(0, 0.3, x.size)
fine = np.linspace(0, 10, 300)

exact = CubicSpline(x, y)
smooth = make_smoothing_spline(x, y)              # lam chosen automatically

plt.plot(x, y, "k.", label="noisy data")
plt.plot(fine, exact(fine), alpha=0.6, label="interpolating spline")
plt.plot(fine, smooth(fine), lw=2, label="smoothing spline")
plt.plot(fine, np.sin(fine) + 0.3 * fine, "--", label="true curve")
plt.legend()
plt.show()

true_fine = np.sin(fine) + 0.3 * fine
print(f"max error, interpolating: {np.abs(exact(fine) - true_fine).max():.3f}")
print(f"max error, smoothing    : {np.abs(smooth(fine) - true_fine).max():.3f}")
max error, interpolating: 0.573
max error, smoothing    : 0.333

The smoothing spline ignores most of the noise and lands much closer to the true curve.

Controlling the smoothness

python · try it yourself
import numpy as np
from scipy.interpolate import make_smoothing_spline

rng = np.random.default_rng(12)
x = np.linspace(0, 10, 40)
y = np.sin(x) + 0.3 * x + rng.normal(0, 0.3, x.size)

for lam in [0.001, 0.1, 10, 1000]:
    s = make_smoothing_spline(x, y, lam=lam)
    rms = np.sqrt(np.mean((s(x) - y) ** 2))
    bend = np.abs(s.derivative(2)(x)).mean()
    print(f"lam={lam:<6}  distance to data={rms:.3f}  average curvature={bend:.3f}")
lam=0.001   distance to data=0.115  average curvature=6.454
lam=0.1     distance to data=0.213  average curvature=0.593
lam=10      distance to data=0.440  average curvature=0.120
lam=1000    distance to data=0.619  average curvature=0.004

As lam grows the curve moves away from the data points and bends less; at very large values it approaches a straight line.

Spline objects: make_interp_spline and BSpline

Under the hood these splines are B-splines, stored as knots, coefficients and a degree. make_interp_spline(x, y, k) builds an interpolating B-spline of any degree, and the result supports derivatives, integrals and root finding:

python · try it yourself
import numpy as np
from scipy.interpolate import make_interp_spline

x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0.0, 0.8, 0.9, 0.1, -0.8, -1.0])

spl = make_interp_spline(x, y, k=3)
print("degree      :", spl.k)
print("value at 2.5:", round(float(spl(2.5)), 4))
print("slope at 2.5:", round(float(spl.derivative()(2.5)), 4))
print("area 0..5   :", round(float(spl.integrate(0, 5)), 4))

grid = np.linspace(1, 5, 401)
vals = spl(grid)
crossing = grid[np.flatnonzero(np.diff(np.sign(vals)))[0]]
print("crosses zero near x =", round(crossing, 2))
degree      : 3
value at 2.5: 0.575
slope at 2.5: -0.8472
area 0..5   : 0.55
crosses zero near x = 3.09

Interpolating on a regular grid

Data measured on a rectangular grid — a terrain height map, temperatures at grid stations — is handled by RegularGridInterpolator. Give it the grid axes and the values; then ask for any points inside. Cubic interpolation needs at least four grid points along each axis:

python · try it yourself
import numpy as np
from scipy.interpolate import RegularGridInterpolator

x = np.array([0, 10, 20, 30])          # metres east
y = np.array([0, 10, 20, 30])          # metres north
height = np.array([[5, 6, 8, 11],      # height[i, j] at (x[i], y[j])
                   [6, 7, 9, 12],
                   [7, 9, 12, 14],
                   [9, 11, 15, 18]], dtype=float)

terrain = RegularGridInterpolator((x, y), height)                 # linear
smooth = RegularGridInterpolator((x, y), height, method="cubic")
points = np.array([[15, 5], [25, 15], [10, 10]])
print("linear:", np.round(terrain(points), 3))
print("cubic :", np.round(smooth(points), 3))
linear: [ 7.25 11.75  7.  ]
cubic : [ 7.012 11.855  7.   ]

Scattered data with griddata

When measurements are at irregular locations — weather stations, survey points — use griddata(). It triangulates the points (the Delaunay triangulation from the Spatial Data lesson) and interpolates within each triangle:

python · try it yourself
import numpy as np
from scipy.interpolate import griddata

stations = np.array([[0, 0], [4, 0], [0, 4], [4, 4], [2, 1], [1, 3]])
rain_mm = np.array([10.0, 14.0, 8.0, 20.0, 12.0, 9.0])

query = np.array([[2, 2], [3, 3], [5, 5]])
print("linear :", np.round(griddata(stations, rain_mm, query, method="linear"), 3))
print("nearest:", griddata(stations, rain_mm, query, method="nearest"))
print("cubic  :", np.round(griddata(stations, rain_mm, query, method="cubic"), 3))
linear : [12.286 16.143    nan]
nearest: [12. 20. 20.]
cubic  : [11.77  15.244    nan]

The point (5, 5) lies outside the stations' convex hull, so the linear and cubic methods return nan; "nearest" simply copies the closest station's value.

Tip: For smooth interpolation of scattered data in any number of dimensions, also try RBFInterpolator (radial basis functions). It can smooth noisy data and extrapolate gently beyond the hull.

Test yourself

What happens to a smoothing spline as lam increases?

  1. It follows the data more closely
  2. It becomes smoother and moves toward a straight line
  3. It adds more knots
  4. It raises an error

Which tool interpolates data measured at irregular (scattered) locations?

  1. RegularGridInterpolator
  2. griddata
  3. CubicSpline
  4. np.interp

Why does griddata(..., method='linear') return nan for some points?

  1. The data contains nan
  2. The points lie outside the convex hull of the data
  3. Linear interpolation needs a grid
  4. The method is deprecated