Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Adaptive filters: LMS, NLMS and RLS

ProblemAdjust the taps of a filter while it runs, so that its output tracks a desired signal: identify an unknown system, cancel noise or echo, equalise a channel
Devised byBernard Widrow and Marcian Hoff (1960), least mean squares; Jin-ichi Nagumo and Atsuhiko Noda (1967) and Arthur Albert and Leland Gardner (1967), normalised LMS; Robin Plackett (1950) and Dominique Godard (1974), recursive least squares
AccuracyLMS converges in the mean for small enough steps, with an excess error proportional to the step; RLS minimises the exponentially weighted squared error exactly at every step
CostLMS and NLMS: per sample for taps. RLS: per sample
Read firstBackground: frequency responses, Gradient descent and nonlinear conjugate gradients
APILmsFilter (new(taps, step_size, normalized), adapt, adapt_block, filter, weights), RlsFilter (new(taps, forgetting, initial_inverse_correlation), adapt, adapt_block, weights)

Overview

A fixed filter needs the signal’s statistics in advance. An adaptive filter learns them as it runs. At each sample it forms an output from the most recent inputs , compares it with a desired response , and nudges its weights to reduce the error . Arranged suitably, the same loop identifies an unknown system (the desired signal is the system’s output), cancels noise (the desired signal is the corrupted one, the input a reference correlated with the noise), cancels echoes on telephone lines, and equalises communication channels. LMS takes one cheap stochastic-gradient step per sample. RLS solves the least-squares problem exactly at every sample, converging far faster at quadratic cost.

Where it is used

An adaptive filter learns the system it is facing, so it works when nobody knows the system in advance, or when it changes.

  • Echo cancellation. Speakerphones, video-conferencing and mobile phones use LMS/NLMS filters to subtract the loudspeaker’s echo from the microphone signal.
  • Noise cancelling headphones. The anti-noise signal is computed by an adaptive filter fed by a reference microphone.
  • Channel equalisation and system identification. Modems adapt to the line they are connected to; control engineers identify a plant from its input and output.
  • Beamforming and prediction. The same recursions adapt array weights to null a jammer, or predict the next sample of a signal.

History

Bernard Widrow and his student Marcian Hoff (1960) invented the least-mean-squares rule for their ADALINE adaptive neuron at Stanford; it became the most widely used adaptive algorithm. Normalising the step by the input power was proposed independently by Jin-ichi Nagumo and Atsuhiko Noda (1967) and by Arthur Albert and Leland Gardner (1967). Recursive least squares goes back to Robin Plackett’s (1950) recursive form of Gauss’s least squares, and to the Kalman filter, of which it is a special case; Dominique Godard (1974) applied it to channel equalisation. Simon Haykin’s Adaptive Filter Theory (1986, now in its fifth edition) is the standard text.

The idea

The Wiener solution

The setting. An adaptive filter is an FIR filter with taps whose weights are adjusted while it runs. At each time step it has three things: the vector of the most recent input samples; a desired signal that its output should match; and its current weights . Its output is the weighted sum , and the error is . (The superscript is the conjugate transpose, which allows complex signals; for real signals it is the ordinary transpose.) In system identification, for example, the input is fed to both an unknown system and the filter, the desired signal is the unknown system’s output, and driving the error to zero makes the filter a copy of the system.

The best fixed filter. If the signals are stationary (their statistics do not change with time), there is a best set of weights: the one that minimises the mean squared error . This is a least-squares problem, and is a quadratic function of the weights, a bowl with a single minimum. Setting its gradient to zero gives the Wiener-Hopf equations

where is the correlation matrix of the input and the cross-correlation of the input with the desired signal. These are the normal equations with averages over the data replaced by expectations.

Solving them directly would require knowing and , which are properties of the signals that are not known in advance and may change. Adaptive filters approach using only the samples as they arrive, and follow it when the statistics drift.

LMS: stochastic gradient descent

The simplest way to find the bottom of the bowl is gradient descent: move the weights a small step against the gradient of . That gradient is , which again involves the unknown and .

Widrow and Hoff’s idea was to replace the expectations by the values at the current instant, however crude that estimate is. With in place of and in place of ,

The estimated gradient is just the input vector times the error. This gives the least mean squares (LMS) update

with step size . It costs one multiply-add per tap, and needs no knowledge of the signals. Each individual step is noisy, since it is based on a single sample, but the noise averages out over many steps and the weights drift towards the Wiener solution.

The behaviour of LMS follows from that of gradient descent on a quadratic.

  • Stability. The weights converge on average when . Since the largest eigenvalue is at most the sum of all of them, which is times the input power , a safe practical rule is to keep well below .
  • Speed. Convergence proceeds independently along each eigenvector of , at a rate set by . If the eigenvalue spread is large, the step size that is safe for the largest eigenvalue is far too small for the smallest, and the slow modes dominate. The spread is 1 for white noise and large for strongly correlated (“coloured”) inputs.
  • Accuracy. Because the gradient estimates are noisy, the weights never settle exactly; they jitter around the optimum. The resulting excess mean squared error is the misadjustment, and it grows with .

The choice of therefore trades speed against final accuracy.

NLMS: a step normalised by the input power

The stability limit of LMS depends on the input power, so a step size that works for a quiet signal makes the filter diverge when the signal gets louder. Normalised LMS removes the dependence by dividing the step by the energy of the current input vector:

The small constant prevents division by zero during silence. The step size is now a pure number, with the same stability range whatever the input level, and the filter converges faster when the input power varies. There is a neat interpretation of : the update is then exactly large enough that, if the same input were presented again, the error would be zero.

RLS: exact recursive least squares

LMS takes a small step towards the solution at each sample. Recursive least squares (RLS) jumps to the exact least-squares solution at every sample. It minimises

the sum of squared errors over all the data so far, with older samples weighted down by the forgetting factor . A sample steps old has weight , so the filter effectively remembers about samples, which lets it track changing statistics.

Solving a new least-squares problem from scratch at every sample would cost each time. The saving comes from noticing how little changes. The normal equations involve the weighted sum of the matrices , and each new sample adds one such rank-one term. The matrix inversion lemma (the Sherman-Morrison formula) gives the inverse of a matrix after a rank-one change in terms of the old inverse, in operations. So RLS maintains the inverse correlation matrix directly and updates it together with the weights:

The vector is the gain: it plays the role of in LMS, but with the input multiplied by . That multiplication rescales every eigen-direction of the input to the same size (“whitens” it), so all modes converge at the same rate. In optimisation terms, RLS takes a Newton step where LMS takes a gradient step. It converges in about samples whatever the eigenvalue spread.

The cost is per sample instead of . There is also a numerical hazard: in exact arithmetic is Hermitian and positive definite, but rounding errors can destroy both properties, after which the filter diverges. The library updates one triangle of and mirrors it, which keeps it exactly Hermitian.

Learning curves

Identifying an 8-tap system from noisy observations (noise floor −40 dB), averaged over 50 runs:

With white input all three reach the noise floor, RLS in a few dozen samples, LMS in a few hundred. With strongly coloured input (a first-order autoregressive process with coefficient 0.9, eigenvalue spread 113 for 8 taps), LMS needs thousands of samples, while RLS is unaffected. The price of RLS grows with the square of the length:

Table 14.9. Cost per sample of NLMS and RLS adaptive filters.

tapsNLMS (ns per sample)RLS (ns per sample)
831134
32671632
12823224333

Algorithm

All three filters keep a regressor , the most recent input samples, and the weights , initially zero. For each new input sample with desired value :

LMS.

  1. Shift into the regressor, discarding the oldest sample.
  2. Compute the output and the error .
  3. Update the weights: .

NLMS: the same, with the step in place of in step 3.

Both cost per sample.

RLS also keeps the matrix , initialised to with a large , which expresses little confidence in the zero initial weights.

  1. Shift into the regressor.
  2. Compute and the gain .
  3. Compute the output and the error , using the weights before the update (the a priori error).
  4. Update the weights: .
  5. Update , computing one triangle and copying it to the other.

The cost is per sample, from the matrix-vector product and the update of .

Implementation

    pub fn adapt(&mut self, x: C64, desired: C64) -> (C64, C64) {
        self.regressor.rotate_right(1);
        self.regressor[0] = x;
        let y: C64 = self.weights.iter().zip(&self.regressor).map(|(w, u)| w.conj() * u).sum();
        let e = desired - y;
        let mu = if self.normalized {
            self.step_size / (self.regularization + self.regressor.iter().map(|u| u.norm_sqr()).sum::<f64>())
        } else {
            self.step_size
        };
        self.weights.iter_mut().zip(&self.regressor).for_each(|(w, u)| *w += mu * e.conj() * u);
        (y, e)
    }
    pub fn adapt(&mut self, x: C64, desired: C64) -> (C64, C64) {
        self.regressor.rotate_right(1);
        self.regressor[0] = x;
        let u = &self.regressor;
        let pu: Vec<C64> = self.p.iter().map(|row| row.iter().zip(u).map(|(a, b)| a * b).sum()).collect();
        let denominator = self.forgetting + u.iter().zip(&pu).map(|(a, b)| a.conj() * b).sum::<C64>().re;
        let k: Vec<C64> = pu.iter().map(|v| v / denominator).collect();
        let y: C64 = self.weights.iter().zip(u).map(|(w, v)| w.conj() * v).sum();
        let e = desired - y;
        self.weights.iter_mut().zip(&k).for_each(|(w, ki)| *w += ki * e.conj());
        // uᴴP = (P u)ᴴ for Hermitian P. Updating one triangle and mirroring it keeps P exactly
        // Hermitian; without this, rounding drives P indefinite and it diverges like λ^{−n}.
        for (i, ki) in k.iter().enumerate() {
            for (j, puj) in pu.iter().enumerate().skip(i) {
                let v = (self.p[i][j] - ki * puj.conj()) / self.forgetting;
                self.p[i][j] = v;
                self.p[j][i] = v.conj();
            }
        }
        (y, e)
    }
  • Both filters work on complex samples; pass real signals with zero imaginary parts.
  • adapt returns the a priori output and error; filter (LMS) applies the current weights without adapting.

In practice

//! System identification with NLMS and RLS adaptive filters.

use lib_jsl_dsp::discrete::filters::adaptive::lms::LmsFilter;
use lib_jsl_dsp::discrete::filters::adaptive::rls::RlsFilter;
use num_complex::Complex;

fn main() {
    // An unknown 4-tap system, driven by a deterministic pseudo-random input.
    let plant = [0.6, -0.3, 0.2, 0.05];
    let mut state = 12345u64;
    let x: Vec<Complex<f64>> = (0..2000)
        .map(|_| {
            state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
            Complex::new((state >> 11) as f64 / (1u64 << 53) as f64 * 2.0 - 1.0, 0.0)
        })
        .collect();
    let d: Vec<Complex<f64>> = (0..x.len()).map(|n| (0..4).filter(|&k| k <= n).map(|k| x[n - k] * plant[k]).sum()).collect();
    let mut nlms = LmsFilter::new(4, 0.5, true).unwrap();
    let mut rls = RlsFilter::new(4, 0.999, 100.0).unwrap();
    for n in 0..x.len() {
        let (_, e1) = nlms.adapt(x[n], d[n]);
        let (_, e2) = rls.adapt(x[n], d[n]);
        if [10, 50, 200, 1999].contains(&n) {
            println!("n = {n:4}: |e| NLMS {:.1e}, RLS {:.1e}", e1.norm(), e2.norm());
        }
    }
    let show = |w: &[Complex<f64>]| w.iter().map(|c| format!("{:.4}", c.re)).collect::<Vec<_>>().join(", ");
    println!("NLMS weights [{}]", show(nlms.weights()));
    println!("RLS weights  [{}]", show(rls.weights()));
}
n =   10: |e| NLMS 1.4e-1, RLS 3.7e-3
n =   50: |e| NLMS 1.5e-4, RLS 2.2e-4
n =  200: |e| NLMS 1.8e-14, RLS 7.8e-5
n = 1999: |e| NLMS 0.0e0, RLS 5.2e-7
NLMS weights [0.6000, -0.3000, 0.2000, 0.0500]
RLS weights  [0.6000, -0.3000, 0.2000, 0.0500]

Without noise, both recover the system exactly. RLS is far ahead after 10 samples, but its error then shrinks slowly: the initial acts as a weak prior pulling the weights towards zero, and its influence fades only at the rate . NLMS with converges geometrically to machine precision.

Strengths

  • LMS is simple, cheap and robust, and tracks slow changes; NLMS removes the dependence on the input level.
  • RLS converges in a few multiples of the filter length, regardless of the input’s spectrum.

Weaknesses

  • LMS slows down with coloured input and trades speed against misadjustment through one parameter.
  • RLS costs per sample and needs care to stay numerically stable; both assume a linear FIR model.

Exercises

  1. Derive the Wiener-Hopf equations from .
  2. Show that LMS converges in the mean when , by writing the mean weight error as a linear recursion.
  3. Show that NLMS with makes the a posteriori error zero (for ).
  4. Derive the RLS update of from the matrix inversion lemma.
  5. Set up a noise canceller: a sinusoid plus noise as the desired signal, and a filtered copy of as the input. Show that the error converges to the sinusoid.
Hints and answers
  1. with and . Setting the gradient to zero gives .
  2. With the mean recursion is . It decays in every eigendirection iff , i.e. .
  3. NLMS: . Then , which is zero for .
  4. Write and apply the Sherman-Morrison formula: with gain .
  5. The canceller can only produce what is correlated with its input (the filtered noise). The sinusoid is uncorrelated with the noise reference, so the optimum filter removes the noise and the error tends to the sinusoid.

Further reading

  • B. Widrow and M. E. Hoff, “Adaptive switching circuits”, IRE WESCON Convention Record 4 (1960) 96–104.
  • S. Haykin, Adaptive Filter Theory, 5th ed., Pearson, 2014.
  • A. H. Sayed, Fundamentals of Adaptive Filtering, Wiley, 2003.
  • B. Widrow, J. R. Glover et al., “Adaptive noise cancelling: principles and applications”, Proceedings of the IEEE 63 (1975) 1692–1716.