Unlike interp1d(), which always passes exactly through every given data point, UnivariateSpline() can optionally smooth the data via its s, smoothing factor, parameter — a higher s allows the fitted curve to deviate more from the original noisy points in exchange for a smoother overall shape, while s=0 forces the spline to pass through every point exactly, behaving similarly to interpolation. This makes it well suited for fitting a clean underlying trend to real-world, noisy measured data, rather than assuming every data point is perfectly accurate.
1Understanding interpolate.UnivariateSpline()
Unlike interp1d(), which always passes exactly through every given data point, UnivariateSpline() can optionally smooth the data via its s, smoothing factor, parameter — a higher s allows the fitted curve to deviate more from the original noisy points in exchange for a smoother overall shape, while s=0 forces the spline to pass through every point exactly, behaving similarly to interpolation. This makes it well suited for fitting a clean underlying trend to real-world, noisy measured data, rather than assuming every data point is perfectly accurate.
Set s=0 explicitly if you want UnivariateSpline() to pass exactly through every data point like a pure interpolator — the default smoothing factor lets the fitted curve deviate from noisy data points in exchange for a smoother overall shape.
from scipy.interpolate import UnivariateSpline
import numpy as np
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0.1, 0.9, 4.2, 8.8, 16.1, 24.9])
spline = UnivariateSpline(x, y, s=1)
print(round(float(spline(2.5)), 2))2Practical Example
Here is a real-world application of interpolate.UnivariateSpline() showing how it is used in production SciPy code.
from scipy.interpolate import UnivariateSpline
import numpy as np
x = np.array([0, 1, 2, 3, 4])
y = np.array([0, 1, 4, 9, 16])
spline = UnivariateSpline(x, y, s=0)
print(spline(2))3Best Practices
Follow these guidelines when working with interpolate.UnivariateSpline():
1. Use UnivariateSpline() with its default or a tuned smoothing factor when fitting real-world, noisy data where a smooth underlying trend matters more than passing through every exact point
2. Set s=0 when you specifically want interpolation behavior, passing exactly through every point, rather than smoothing
3. Experiment with different s values and visually compare the fitted curve against the raw data, since there's no single universally correct smoothing amount
Tip: Set s=0 explicitly if you want UnivariateSpline() to pass exactly through every data point like a pure interpolator — the default smoothing factor lets the fitted curve deviate from noisy data points in exchange for a smoother overall shape.
from scipy.interpolate import UnivariateSpline
import numpy as np
x = np.array([0, 1, 2, 3, 4, 5])
y = np.array([0.1, 0.9, 4.2, 8.8, 16.1, 24.9])
spline = UnivariateSpline(x, y, s=1)
print(round(float(spline(2.5)), 2))