Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 38 ยท Interpolation and Smoothing

Multidimensional and Scattered-Data Interpolation

Interpolate in 2D and beyond with RegularGridInterpolator, griddata and RBFInterpolator, smooth noisy data with splines, and resample images in SciPy.

In One-Dimensional Interpolation every sample was a pair (x, y). Real data often has more dimensions: temperature over a map, a sensor reading as a function of two settings, brightness over the pixels of an image. The core question is the same (estimate a value between known ones), but now it matters where the known points are.

If the samples sit on a neat rectangular grid, interpolation is cheap and well behaved. If they are scattered (weather stations, GPS fixes, measurements taken whenever it was convenient), SciPy has to work out the neighbourhood relationships itself, which is slower and needs more care. This lesson covers both cases, then turns to smoothing: when your data is noisy, passing exactly through every point is the wrong goal.

flowchart TD
    A["Values at known locations"] --> B{"Regular grid?"}
    B -->|"yes"| C["RegularGridInterpolator<br/>fast, linear or cubic"]
    B -->|"no, scattered"| D{"Noisy?"}
    D -->|"no, exact data"| E["griddata or RBFInterpolator"]
    D -->|"yes"| F["RBFInterpolator with smoothing"]
    A --> G{"One dimension, noisy?"}
    G -->|"yes"| H["make_smoothing_spline<br/>or UnivariateSpline"]

Choose the tool by the layout and quality of your data.

Regular grids: RegularGridInterpolator

RegularGridInterpolator(points, values) takes a tuple of 1D coordinate arrays (one per axis, each strictly increasing) and an N-dimensional array of values with matching shape. You then call it with an array of query points shaped (m, ndim). It works in any number of dimensions, not only two.

Python Interpolating a table of values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Linear interpolation of x**2 is not exact (the curve bends between grid points), whereas the cubic method reproduces this smooth function. Three habits to remember:

  • Always build the table with indexing="ij" in meshgrid, so that the first array axis is the first coordinate.
  • Query points are rows of an (m, ndim) array, not separate x and y arrays.
  • Outside the grid you get an error; bounds_error=False gives nan, and fill_value=None extrapolates (use with caution, as before).

Scattered data: griddata

When points have no pattern, griddata(points, values, xi, method=...) does the work in one call. The points array has shape (n, ndim), values has shape (n,), and xi holds the places you want. The methods:

  • "nearest": the value of the closest sample (piecewise constant, never invents values).
  • "linear": it triangulates the points (Delaunay) and interpolates linearly in each triangle.
  • "cubic" (2D only): a smooth piecewise cubic over the same triangulation.

A key limitation: linear and cubic only work inside the convex hull of the data, the smallest convex shape containing all the points. Outside it you get nan.

Python Interpolating scattered points

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The three methods improve in that order, at the cost of smoothness assumptions. The black dots on the plot are the data; the contour map is the cubic interpolant.

Radial basis functions: RBFInterpolator

RBFInterpolator(points, values) builds a smooth surface as a sum of "bumps" centred at each data point, and it works in any dimension. It also has no convex-hull restriction: it extrapolates (though cautiously). It returns an object you call with new points, just like the other interpolants. Useful options:

  • kernel: the bump shape. The default "thin_plate_spline" is a good general choice; "cubic", "multiquadric" and "gaussian" are alternatives (the last two need an epsilon scale).
  • smoothing: a non-negative number. 0 interpolates exactly; larger values relax the fit and average out noise.
  • neighbors: use only the nearest k points for each query, which makes large data sets practical (the full method solves a dense system and slows down for many thousands of points).
Python RBF with noisy data

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With smoothing=0 the surface is forced through every noisy value, so the noise is baked into the result. As smoothing increases, the error against the true surface keeps dropping across this range. Push it much higher and the surface becomes too stiff and the error rises again. The best value depends on how noisy the data is and is usually found by trial or cross-validation.

Interpolation is not a statistical model. It says nothing about uncertainty, and it assumes the samples are exact. If your readings are noisy, use smoothing or a fitted model.

Smoothing noisy data in one dimension

For 1D data, SciPy offers several smoothing splines. The easiest to use is make_smoothing_spline(x, y). It balances closeness to the data against roughness of the curve, and when you do not give it a penalty lam, it picks one itself with generalized cross-validation. The lam argument sets the penalty by hand: 0 interpolates, and very large values flatten the curve toward a straight line.

UnivariateSpline(x, y, s=...) is the older alternative. Its s controls the allowed total squared error: a good starting value is n * sigma**2 for n points with noise level sigma; s=0 interpolates.

Python Smoothing splines versus interpolation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The smoothing spline cuts the error to roughly a quarter of the raw noise, whereas lam=0 reproduces the noisy data exactly (error unchanged) and lam=10 is over-smoothed and makes things worse. If you need the noise level to be estimated rather than guessed, fit a model with Curve Fitting and Least Squares.

BSpline: the engine underneath

Most of the spline tools above hand you a BSpline object (from make_interp_spline and make_smoothing_spline), which stores three things: the knots t (where the pieces join), the coefficients c (the control values), and the degree k. You can also build one directly. A degree-k spline needs len(t) = len(c) + k + 1, and repeating the end knots k + 1 times makes the curve start and end at the first and last coefficient.

Python Building a BSpline by hand

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Resampling an image

An image is a 2D grid of values, so changing its size is interpolation: evaluate the grid at a finer set of positions. RegularGridInterpolator does that directly. (The dedicated function scipy.ndimage.zoom, which you will meet in the lesson on image processing, is more convenient and faster for real images, but this shows what is happening.)

Python Upsampling a tiny image

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Nearest-neighbour keeps hard blocky pixels, linear gives soft edges, and cubic is smoother still but can create tiny values below 0 or above 1 near sharp edges (the same overshoot you saw in 1D). For photographs this is invisible; for data that must stay in range, clip the result with np.clip.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What shape do query points have when calling a RegularGridInterpolator built over 3 axes?

    Query points are rows: an array of shape (m, ndim), here (m, 3). A single point can be passed as (3,).
  2. 2. griddata(..., method='linear') returns nan for some of your target points. The most likely reason?

    Linear and cubic griddata interpolate inside the Delaunay triangulation. Outside the convex hull of the data there is no triangle to use, so the result is nan.
  3. 3. Which tool lets you interpolate scattered data in many dimensions and also average out noise with a single parameter?

    RBFInterpolator accepts scattered points in any dimension, and its smoothing parameter relaxes the exact fit so noise is averaged out.
  4. 4. With make_smoothing_spline, what happens if you set lam=0?

    lam is the roughness penalty. With lam=0 nothing penalises wiggles, so the spline interpolates the data exactly. Omitting lam lets SciPy choose a penalty by cross-validation.

Summary

  • On a regular grid use RegularGridInterpolator((x, y, ...), values) with indexing="ij" tables and (m, ndim) query arrays; choose "linear", "nearest" or "cubic".
  • For scattered points, griddata is the quick tool, but linear and cubic give nan outside the convex hull.
  • RBFInterpolator handles scattered points in any dimension, and smoothing trades exactness for noise reduction.
  • Do not interpolate noisy data exactly: use make_smoothing_spline (1D, automatic penalty), UnivariateSpline(s=...) or smoothing RBFs.
  • A BSpline stores knots, coefficients and degree; image resizing is just interpolation on a grid.

Next up: describe data and model randomness with Distributions and Descriptive Statistics.