Adaptive Filters: The LMS Algorithm
The 50 Hz notch works when the hum sits exactly at and you can afford a hole in the spectrum. A biomedical amplifier cannot: the heart signal has content near , 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 weights acts on the last samples of a reference input, :
The desired signal is whatever the filter should imitate, and the error is what is left. The arrangement decides the application:
| Configuration | Reference | Desired | 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 = cleaned signal |
| echo cancellation | far-end speech sent to the loudspeaker | microphone (near speech + echo) | , the echo-free near speech |
| equalisation | received, distorted symbols | known training symbols | the equalised stream |
| linear prediction | past samples | the present sample | the prediction error (whitening, coding) |
The LMS update
The best fixed weights (the Wiener solution) minimise ; they solve with the input autocorrelation matrix and the cross-correlation between and . LMS never forms . It takes one step down the gradient of the instantaneous squared error, :
That is multiply-adds per sample on top of the filter itself. The step size sets everything:
- Stability: for white input of power , the commonly quoted bound is (); mean-square stability needs somewhat less (about 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 samples, and the squared error twice as fast, .
- Misadjustment: the noisy gradient keeps the weights jittering around the optimum, adding excess error of about relative to the minimum.
Large is fast but noisy and risks instability; small is accurate but slow. Because the bound depends on input power, the normalised LMS (NLMS) divides the step by , so a step 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 , white input with , measurement noise on its output, an LMS filter with and .
Find: the stability bound, the convergence time constant, the misadjustment, and the weights after training.
Solve:
- Bound: ; is 25 times smaller.
- Time constants: samples for the weights ( for the squared error), so about 200 to 300 samples to converge (4 to 6 time constants).
- Misadjustment: : the error power settles about above the noise floor .
Check: the simulation below.
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, in theory) roughly ; at the end they match to the noise level, and the error power sits above the noise floor as predicted.
Adaptive hum cancellation
A biopotential amplifier at records a slow "pulse" waveform plus hum whose amplitude drifts from to and whose phase wanders. A reference of the hum's frequency (from a pickup, or generated locally at ) 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 , and which follows the hum.
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 while the pulse waveform passes through. What is left is the tracking lag: the hum keeps changing, and the weights (amplitude against ) follow it a little late. A larger tracks faster but lets more noise into the weights.
Guided lab: an adaptive canceller on a microcontroller
Hand calculation. Two weights, NLMS with : with a unit-power reference vector the weights converge with a time constant of about samples, at ; allow about a second (five time constants).
Simulation. Change mu_n to (a narrower notch, but too slow to follow the drifting hum: only about of reduction) and (it tracks closely, about of reduction, but the wider effective notch lets more noise through and starts to eat the signal near : the rms error rises to about ).
What you would measure. Use a two-channel function generator: channel 1 a "signal", channel 2 a "hum". Sum them with two resistors into ADC input A (with a offset so the sum stays within to ), 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 component in the output to fall by to 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 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 .
- Adapting during double talk in echo cancellation (both people speaking): freeze adaptation with a detector.
Practice
- White input with feeds a 32-tap LMS filter. What is the stability bound for , and the weights' time constant for ?
- What misadjustment does that give?
- Why does an adaptive canceller with a reference behave like a notch filter?
Answer
- ; weight time constant samples (200 for the squared error).
- , i.e. .
- 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 to is a notch whose width grows with .
Test yourself
The LMS weight update is
Increasing the LMS step size makes adaptation
- slower and more accurate
- faster but noisier, and eventually unstable
- independent of input power
- exactly equal to the Wiener solution
In adaptive noise cancellation, the cleaned signal is
- the filter output
- the error
- the reference
- the weights
Why is NLMS preferred when the input level varies?
- it needs fewer taps
- its step is divided by the input power, so stability does not depend on the level
- it converges in one step
- it needs no reference