Savitzky-Golay smoothing
| Problem | Smooth noisy, equally spaced samples, or estimate their derivatives, without flattening peaks |
| Devised by | Abraham Savitzky and Marcel Golay (1964), building on the moving polynomial least squares of actuarial graduation (Sheppard, 1913; Whittaker and Robinson, 1924) |
| Accuracy | Reproduces polynomials of the filter’s order exactly; reduces white-noise variance by roughly the window length |
| Cost | One convolution with a fixed set of coefficients: |
| Read first | Linear least squares |
| API | savitzky_golay, savitzky_golay_coefficients |
Overview
Measured signals are noisy, and the simplest cure, averaging each value with its neighbours, works against noise but also against the signal: a moving average flattens peaks and shifts their shapes. A Savitzky-Golay filter replaces the average by a local polynomial least-squares fit: around each sample, fit a polynomial of low degree to the samples in a window, and take the value (or a derivative) of that polynomial at the centre. Because a polynomial can follow a peak, the filter removes noise while preserving the shape, height and position of features much better than averaging.
The remarkable fact that makes the method practical is that, for equally spaced data, the fitted value is a fixed linear combination of the samples in the window. The whole filter is a convolution with a short set of coefficients, computed once.
Where it is used
Savitzky-Golay filters smooth noisy data without flattening peaks.
- Spectroscopy and chromatography. Peaks in absorbance, Raman and mass spectra are smoothed while preserving their height and width, and their derivatives are used to find peak positions.
- Biomedical signals. Smoothing and differentiating ECG and other physiological signals.
- General data analysis. Estimating derivatives of sampled data (velocity from position, rate of change of a temperature).
History
Fitting local polynomials to smooth data was practised by actuaries in the nineteenth and early twentieth centuries, who “graduated” mortality tables with moving least-squares formulas. Abraham Savitzky and Marcel Golay, chemists at the Perkin-Elmer Corporation, brought the idea to the smoothing of spectra in a 1964 paper in Analytical Chemistry, with tables of coefficients for many window sizes and polynomial degrees. It became one of the most cited papers in the history of the journal. Their tables contained some errors, corrected by Steinier, Termonia and Deltour in 1972.
The idea
Local polynomial least squares
Take a window of samples centred on sample , and number the samples in it by their offsets from the centre. Fit a polynomial of degree , , by least squares: choose the coefficients to minimise the sum of squared differences between the polynomial and the data,
The window must contain more samples than the polynomial has coefficients (), so that the polynomial cannot follow every sample and is forced to average out the noise.
The fit is linear in the data. Collect the samples of the window in a vector and the coefficients in a vector . The values of the polynomial at the offsets are , where is the Vandermonde matrix with entries . The least-squares solution is
where is called the pseudo-inverse of . The important point is that is a matrix times : each coefficient is a fixed weighted sum of the samples in the window.
Reading off the filter. We do not need the whole polynomial, only its value at the centre of the window, . That is the first row of applied to the window. Similarly the -th derivative at the centre is in units of the sample offset, or for samples spaced apart: row of . The matrix depends only on and , not on the data or on the position of the window, so these rows are the filter coefficients, the same for every position. For and the smoothing coefficients are the classic : each smoothed value is this weighted sum of the sample and its two neighbours on either side.
Properties. If the data in a window lie exactly on a polynomial of degree at most , the least-squares fit is that polynomial, and the filter returns the data unchanged. The filter therefore does not distort features that are locally polynomial, while it pays for this with less noise reduction than a moving average of the same length. For white noise of variance the output variance is (the squared weights, because the noise at different samples is independent). The moving average has for a window of points; a quadratic or cubic Savitzky-Golay filter has about for long windows, more than twice as much, which is the price of keeping peaks undistorted. The moving average is itself the special case : the best constant fit to a window is its mean. Degree gives the same weights, because adding a slope to the fit over a symmetric window does not change its value at the centre.
Figure 3.10. Smoothing a noisy peak.
The moving average cuts the peak to two-thirds of its height and widens it; the order-4 Savitzky-Golay filter follows it.
Derivatives of noisy data
Differentiating noisy data by finite differences divides the noise by the sample spacing and so amplifies it. This is the rounding-error problem of numerical differentiation again, with the measurement noise playing the role of rounding error, and a far larger one. The derivative of the local fit is much better behaved, because the fit averages the noise over the window before differentiating. On the noisy peak above:
Table 3.8. Second-derivative estimates by Savitzky-Golay filters.
| derivative estimate | RMS error |
|---|---|
| central differences | 17.2 |
| Savitzky-Golay, window 11, order 2 | 2.6 |
| Savitzky-Golay, window 21, order 2 | 4.0 |
| Savitzky-Golay, window 21, order 4 | 2.4 |
| Savitzky-Golay, window 41, order 4 | 4.5 |
The best window balances two sources of error, just as the best step does for finite differences. If the window is too short, too few samples are averaged and noise dominates. If it is too long, a polynomial of degree cannot follow the signal across the whole window, and the fit is biased.
Conditioning
The Vandermonde matrix in the raw offsets is badly conditioned for wide windows and high orders (its columns range from 1 to ), and forming the normal equations squares the condition number. The library scales the offsets to and computes the pseudo-inverse from an SVD, then adjusts the derivative factors for the scaling. (Forming the normal equations directly is visibly worse: a 51-point, order-8 filter reproduces its own polynomials only to , and 101-point windows fail as singular.)
Algorithm
Input: samples with spacing , a window of points, a polynomial degree and a derivative order (0 for smoothing).
- Build the design matrix. Form the Vandermonde matrix in the scaled offsets, for and .
- Invert it once. Compute the pseudo-inverse from the SVD of .
- Extract the filter. The coefficients are row of , multiplied by . The factor turns the polynomial coefficient into a derivative, and undoes the scaling of the offsets and converts to the units of the data.
- Filter the interior. For every sample at least from both ends, the output is the sum of the coefficients times the samples in the window centred there (a correlation).
- Treat the ends. For the first samples the centred window would run off the data. Instead fit one polynomial of degree to the first samples, and evaluate it (or its -th derivative) at each of those positions. Do the same at the other end.
The set-up costs one SVD of a matrix. Filtering costs multiplications per sample.
Implementation
// Least-squares polynomial in the scaled offset t = (i − m)/m ∈ [−1, 1]; the filter is row
// `deriv` of the pseudo-inverse, times deriv! / (m Δ)^deriv to undo the scaling.
let pinv = local_fit(window, order, m as f64, m.max(1) as f64)?;
let factorial: f64 = (1..=deriv).map(|k| k as f64).product();
let scale = factorial / (m.max(1) as f64 * delta).powi(deriv as i32);
Ok(pinv.row(deriv).iter().map(|&c| c * scale).collect())
- The window must be odd and larger than the polynomial order; a derivative of order above the polynomial’s is identically zero.
- The end treatment matches SciPy’s
mode="interp", so the output has the same length as the input.
In practice
//! Savitzky-Golay smoothing and differentiation of noisy samples.
//!
//! Run with `cargo run -p lib_jsl_interpolation --example interpolation_savitzky_golay`.
use lib_jsl_core::R1D;
use lib_jsl_interpolation::one_d::savitzky_golay::{savitzky_golay, savitzky_golay_coefficients};
fn main() {
// The classic 5-point quadratic smoothing filter: (−3, 12, 17, 12, −3) / 35.
let c = savitzky_golay_coefficients(5, 2, 0, 1.0).unwrap();
println!("5-point quadratic filter × 35: {:?}", c.iter().map(|v| (v * 35.0).round()).collect::<Vec<_>>());
// A position measured every 10 ms with noise: estimate the velocity.
let dt = 0.01;
let position = |t: f64| 2.0 * t + 0.5 * (3.0 * t).sin();
let mut seed = 7u64;
let mut noise = || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); ((seed >> 11) as f64 / (1u64 << 53) as f64 - 0.5) * 0.002 };
let samples = R1D::from_vec((0..300).map(|k| position(k as f64 * dt) + noise()).collect());
let velocity = savitzky_golay(samples.view(), 31, 3, 1, dt).unwrap();
let k = 150;
let t = k as f64 * dt;
let naive = (samples[k + 1] - samples[k - 1]) / (2.0 * dt);
println!("velocity at t = {t}: true {:.4}, central difference {naive:.4}, Savitzky-Golay {:.4}", 2.0 + 1.5 * (3.0 * t).cos(), velocity[k]);
}
Strengths
- Preserves peak heights and widths far better than a moving average of the same noise reduction.
- Smoothing and differentiation in one cheap convolution.
Weaknesses
- Requires equally spaced samples (for uneven spacing, fit local polynomials directly).
- The window and order must be chosen; a too-high order follows the noise, a too-wide window flattens the signal.
- Its frequency response has ripples in the stop band, so it is a poorer low-pass filter than a designed one (digital filters) when frequency selectivity matters.
Exercises
- Derive the 5-point quadratic smoothing coefficients by hand from the normal equations.
- Show that the smoothing coefficients for orders and are identical. Why?
- Compute the noise-reduction factor of a 21-point filter of orders 0, 2 and 4, and compare with .
- Compute and plot the frequency response of the 21-point order-4 filter.
- Estimate the second derivative of the noisy peak with Savitzky-Golay filters of several windows and find the best.
Hints and answers
- With offsets and basis , . The smoothed value at the centre is the first coefficient, which is the first row of ; it equals .
- On a symmetric window, odd powers are orthogonal to all even powers, so adding one to the fit does not change the fitted value at the centre; the weights for the centre value are therefore the same.
- is for order 0, for order 2 and for order 4: higher orders keep more detail but reduce noise less.
- The response is flat near and falls off at higher , with ripples beyond the cutoff; the order-4 filter has a wider flat region than the order-2 one.
- A window that is too short leaves the noise amplified by differentiation; one that is too long flattens the peak. Plot the error against window length and pick the minimum.
Further reading
- A. Savitzky and M. J. E. Golay, “Smoothing and differentiation of data by simplified least squares procedures”, Analytical Chemistry 36 (1964) 1627–1639.
- J. Steinier, Y. Termonia and J. Deltour, “Comments on smoothing and differentiation of data by simplified least square procedure”, Analytical Chemistry 44 (1972) 1906–1909.
- R. W. Schafer, “What is a Savitzky-Golay filter?”, IEEE Signal Processing Magazine 28 (2011) 111–117. The filter from the signal-processing point of view.