TExcelTAD
Home › Signals, Systems & Digital Filters for Engineers › Adaptive Filters: The LMS Algorithm

Adaptive Filters: The LMS Algorithm

The 50 Hz notch works when the hum sits exactly at 50 Hz50\ \text{Hz} and you can afford a 6 Hz6\ \text{Hz} hole in the spectrum. A biomedical amplifier cannot: the heart signal has content near 50 Hz50\ \text{Hz}, and the hum's amplitude and phase drift as the patient moves. A hands-free phone faces a harder version: the echo path from loudspeaker to microphone changes every time someone moves in the room. Both are solved with adaptive filters: FIR filters whose coefficients adjust themselves, sample by sample, to minimise an error signal. The least-mean-squares (LMS) algorithm that does the adjusting is three lines of code and runs on the smallest microcontroller. This lesson derives it, gives its stability and speed rules, and applies it to system identification and hum cancellation.

The setup

An FIR filter with LL weights w\mathbf{w} acts on the last LL samples of a reference input, x[n]=(x[n],x[n−1],…,x[n−L+1])\mathbf{x}[n] = (x[n], x[n-1], \ldots, x[n-L+1]):

y[n]=wTx[n],e[n]=d[n]−y[n]y[n] = \mathbf{w}^{T}\mathbf{x}[n], \qquad e[n] = d[n] - y[n]

The desired signal d[n]d[n] is whatever the filter should imitate, and the error e[n]e[n] is what is left. The arrangement decides the application:

Configuration Reference xx Desired dd Useful output
system identification input of an unknown system its output the weights (a model of the system)
noise cancellation a noise reference (hum pickup, engine vibration) signal + correlated noise the error ee = cleaned signal
echo cancellation far-end speech sent to the loudspeaker microphone (near speech + echo) ee, the echo-free near speech
equalisation received, distorted symbols known training symbols the equalised stream yy
linear prediction past samples the present sample the prediction error (whitening, coding)

The LMS update

The best fixed weights (the Wiener solution) minimise E{e2}E\{e^2\}; they solve Rw=p\mathbf{R}\mathbf{w} = \mathbf{p} with the input autocorrelation matrix R\mathbf{R} and the cross-correlation p\mathbf{p} between x\mathbf{x} and dd. LMS never forms R\mathbf{R}. It takes one step down the gradient of the instantaneous squared error, ∇(e2)=−2e x\nabla(e^2) = -2e\,\mathbf{x}:

w[n+1]=w[n]+μ e[n] x[n]\mathbf{w}[n+1] = \mathbf{w}[n] + \mu\,e[n]\,\mathbf{x}[n]

That is 2L2L multiply-adds per sample on top of the filter itself. The step size μ\mu sets everything:

  • Stability: for white input of power σx2\sigma_x^2, the commonly quoted bound is 0<μ<2L σx20 < \mu < \dfrac{2}{L\,\sigma_x^2} (2/tr⁡R2/\operatorname{tr}\mathbf{R}); mean-square stability needs somewhat less (about 2/(3Lσx2)2/(3L\sigma_x^2) for Gaussian input), so stay well below it, by a factor of 10 or more.
  • Speed: for white input the weight errors decay with a time constant of roughly 1μσx2\dfrac{1}{\mu\sigma_x^2} samples, and the squared error twice as fast, 12μσx2\dfrac{1}{2\mu\sigma_x^2}.
  • Misadjustment: the noisy gradient keeps the weights jittering around the optimum, adding excess error of about M=μLσx22M = \dfrac{\mu L \sigma_x^2}{2} relative to the minimum.

Large μ\mu is fast but noisy and risks instability; small μ\mu is accurate but slow. Because the bound depends on input power, the normalised LMS (NLMS) divides the step by ε+∥x[n]∥2\varepsilon + \lVert \mathbf{x}[n] \rVert^2, so a step 0<μ~<20 < \tilde{\mu} < 2 works at any input level. Echo cancellers and most practical systems use NLMS or faster relatives (RLS, affine projection).

Worked example: identifying an unknown FIR system

Given: an unknown system h=(0.5,−0.3,0.2,0.1)h = (0.5, -0.3, 0.2, 0.1), white input with σx=1\sigma_x = 1, measurement noise σv=0.01\sigma_v = 0.01 on its output, an LMS filter with L=4L = 4 and μ=0.02\mu = 0.02.

Find: the stability bound, the convergence time constant, the misadjustment, and the weights after training.

Solve:

  • Bound: μ<2/(4×1)=0.5\mu < 2/(4 \times 1) = 0.5; μ=0.02\mu = 0.02 is 25 times smaller.
  • Time constants: 1/(0.02×1)=501/(0.02 \times 1) = 50 samples for the weights (2525 for the squared error), so about 200 to 300 samples to converge (4 to 6 time constants).
  • Misadjustment: 0.02×4×1/2=0.040.02 \times 4 \times 1/2 = 0.04: the error power settles about 4 %4\,\% above the noise floor σv2=10−4\sigma_v^2 = 10^{-4}.

Check: the simulation below.

python · try it yourself
import numpy as np

rng = np.random.default_rng(5)
h_true = np.array([0.5, -0.3, 0.2, 0.1])
L, mu, Nn = 4, 0.02, 3000
x = rng.standard_normal(Nn)
d = np.convolve(x, h_true)[:Nn] + 0.01 * rng.standard_normal(Nn)

w = np.zeros(L)
e_hist = np.zeros(Nn)
for n in range(L - 1, Nn):
    xv = x[n - L + 1:n + 1][::-1]            # x[n], x[n-1], ..., x[n-L+1]
    e = d[n] - w @ xv
    w = w + mu * e * xv                      # the LMS update
    e_hist[n] = e
    if n + 1 in (25, 100, 3000):
        print(f"after {n + 1:4d} samples: w = {np.round(w, 4)}")
print("true h               :", h_true)
mse = np.mean(e_hist[2000:] ** 2)
print(f"steady-state error power {mse:.3e} (noise floor 1.0e-04, predicted {1e-4 * 1.04:.3e})")
after   25 samples: w = [ 0.1048 -0.0762 -0.0023  0.0591]
after  100 samples: w = [ 0.4043 -0.2316  0.1694  0.087 ]
after 3000 samples: w = [ 0.4997 -0.301   0.1998  0.099 ]
true h               : [ 0.5 -0.3  0.2  0.1]
steady-state error power 1.043e-04 (noise floor 1.0e-04, predicted 1.040e-04)

After 25 samples (half a weight time constant) the weights are only a fifth of the way there; after 100 samples (two time constants, 1−e−2=86 %1 - e^{-2} = 86\,\% in theory) roughly 80 %80\,\%; at the end they match hh to the noise level, and the error power sits 4 %4\,\% above the noise floor as predicted.

Adaptive hum cancellation

A biopotential amplifier at 500 Sa/s500\ \text{Sa/s} records a slow 1.2 Hz1.2\ \text{Hz} "pulse" waveform plus 50 Hz50\ \text{Hz} hum whose amplitude drifts from 0.50.5 to 0.80.8 and whose phase wanders. A reference of the hum's frequency (from a pickup, or generated locally at 50 Hz50\ \text{Hz}) feeds a two-weight NLMS filter with a cosine and a sine: the weights track amplitude and phase, and the error is the cleaned signal. This adaptive canceller acts as a notch whose width is set by μ\mu, and which follows the hum.

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt

fs = 500.0
t = np.arange(int(8 * fs)) / fs
rng = np.random.default_rng(11)
pulse = 0.4 * np.sin(2 * np.pi * 1.2 * t) ** 3                 # wanted slow signal
amp = 0.5 + 0.3 * t / t[-1]                                     # hum amplitude drifts 0.5 -> 0.8
phase = 0.3 * np.sin(2 * np.pi * 0.1 * t)                       # and its phase wanders
hum = amp * np.sin(2 * np.pi * 50 * t + phase)
d = pulse + hum + 0.01 * rng.standard_normal(len(t))
ref = np.stack([np.cos(2 * np.pi * 50 * t), np.sin(2 * np.pi * 50 * t)], axis=1)

w, mu_n = np.zeros(2), 0.02
e = np.zeros(len(t))
for n in range(len(t)):
    xv = ref[n]
    e[n] = d[n] - w @ xv
    w = w + mu_n * e[n] * xv / (1e-6 + xv @ xv)               # NLMS

def hum_db(sig, a, b):                                          # 50 Hz component by correlation
    seg, tt = sig[a:b], t[a:b]
    return 20 * np.log10(2 * abs(np.mean(seg * np.exp(-2j * np.pi * 50 * tt))))
late = slice(int(6 * fs), int(8 * fs))
print(f"hum level before: {hum_db(d, int(6 * fs), int(8 * fs)):.1f} dB, after: {hum_db(e, int(6 * fs), int(8 * fs)):.1f} dB (re 1 V)")
print(f"rms error vs the clean pulse (last 2 s): {np.sqrt(np.mean((e[late] - pulse[late])**2)):.4f} V")
print(f"final weights: amplitude {np.hypot(*w):.3f} V (true {amp[-1]:.3f} V)")

fig, ax = plt.subplots(figsize=(7, 3))
k = slice(int(6 * fs), int(7 * fs))
ax.plot(t[k], d[k], lw=0.7, label="recorded (pulse + hum)")
ax.plot(t[k], e[k], lw=1.5, label="LMS output")
ax.set(xlabel="time (s)", ylabel="V"); ax.legend(loc="upper right", fontsize=8)
plt.tight_layout(); plt.show()
hum level before: -2.3 dB, after: -37.4 dB (re 1 V)
rms error vs the clean pulse (last 2 s): 0.0149 V
final weights: amplitude 0.793 V (true 0.800 V)

The hum drops by about 35 dB35\ \text{dB} while the pulse waveform passes through. What is left is the tracking lag: the hum keeps changing, and the weights (amplitude 0.793 V0.793\ \text{V} against 0.800 V0.800\ \text{V}) follow it a little late. A larger μ~\tilde{\mu} tracks faster but lets more noise into the weights.

Guided lab: an adaptive canceller on a microcontroller

Hand calculation. Two weights, NLMS with μ~=0.02\tilde{\mu} = 0.02: with a unit-power reference vector the weights converge with a time constant of about L/μ~=2/0.02=100L/\tilde{\mu} = 2/0.02 = 100 samples, 0.2 s0.2\ \text{s} at 500 Sa/s500\ \text{Sa/s}; allow about a second (five time constants).

Simulation. Change mu_n to 0.0020.002 (a narrower notch, but too slow to follow the drifting hum: only about 15 dB15\ \text{dB} of reduction) and 0.20.2 (it tracks closely, about 54 dB54\ \text{dB} of reduction, but the wider effective notch lets more noise through and starts to eat the signal near 50 Hz50\ \text{Hz}: the rms error rises to about 0.027 V0.027\ \text{V}).

What you would measure. Use a two-channel function generator: channel 1 a 5 Hz5\ \text{Hz} "signal", channel 2 a 50 Hz50\ \text{Hz} "hum". Sum them with two 10 kΩ10\ \text{k}\Omega resistors into ADC input A (with a 1.5 V1.5\ \text{V} offset so the sum stays within 00 to 3 V3\ \text{V}), and take channel 2 alone into ADC input B as the reference. Run the NLMS loop with input B as ref (subtract its mean and use it directly, or generate cos/sin locked to it). Expect the 50 Hz50\ \text{Hz} component in the output to fall by 3030 to 45 dB45\ \text{dB} within about a second, limited by ADC noise and the reference's own noise; change channel 2's amplitude and watch the weights follow.

Hazards and safe setup. Generator signals only; never connect a person or the mains to the board. USB power; check both channels on a scope before connecting; series resistors protect the ADC pins.

Pitfalls

  • Choosing μ\mu for one input level: if the reference gets 10 times stronger, plain LMS becomes unstable. Use NLMS.
  • Letting the wanted signal leak into the reference: the canceller then removes part of the signal.
  • Expecting LMS to converge quickly with strongly coloured input: the slowest mode follows the smallest eigenvalue of R\mathbf{R}.
  • Adapting during double talk in echo cancellation (both people speaking): freeze adaptation with a detector.

Practice

  1. White input with σx2=0.25\sigma_x^2 = 0.25 feeds a 32-tap LMS filter. What is the stability bound for μ\mu, and the weights' time constant for μ=0.01\mu = 0.01?
  2. What misadjustment does that give?
  3. Why does an adaptive canceller with a 50 Hz50\ \text{Hz} reference behave like a notch filter?
Answer
  1. μ<2/(32×0.25)=0.25\mu < 2/(32 \times 0.25) = 0.25; weight time constant 1/(0.01×0.25)=4001/(0.01 \times 0.25) = 400 samples (200 for the squared error).
  2. M=0.01×32×0.25/2=0.04M = 0.01 \times 32 \times 0.25/2 = 0.04, i.e. 4 %4\,\%.
  3. It can only subtract a sinusoid at the reference frequency, with whatever amplitude and phase minimise the error; components elsewhere pass. The equivalent transfer function from dd to ee is a notch whose width grows with μ\mu.

Test yourself

The LMS weight update is

  1. w←w−μe\mathbf{w} \leftarrow \mathbf{w} - \mu e
  2. w←w+μ e x\mathbf{w} \leftarrow \mathbf{w} + \mu\,e\,\mathbf{x}
  3. w←R−1p\mathbf{w} \leftarrow \mathbf{R}^{-1}\mathbf{p}
  4. w←μx\mathbf{w} \leftarrow \mu\mathbf{x}

Increasing the LMS step size μ\mu makes adaptation

  1. slower and more accurate
  2. faster but noisier, and eventually unstable
  3. independent of input power
  4. exactly equal to the Wiener solution

In adaptive noise cancellation, the cleaned signal is

  1. the filter output yy
  2. the error e=d−ye = d - y
  3. the reference xx
  4. the weights

Why is NLMS preferred when the input level varies?

  1. it needs fewer taps
  2. its step is divided by the input power, so stability does not depend on the level
  3. it converges in one step
  4. it needs no reference