Compression by Keeping Few Coefficients
Most real signals are compressible: in the right basis, a few coefficients carry almost all the energy. Transform coding exploits this: transform, keep the largest coefficients (or quantize the small ones coarsely), and invert. This lesson measures how well Fourier and cosine bases compress smooth and non-smooth signals, and how denoising by thresholding follows from the same idea.
Keep the largest
By Parseval, in an orthonormal basis the squared error of dropping coefficients equals the energy of the dropped coefficients. So the best -term approximation keeps the largest in magnitude.
import numpy as np
from scipy.fft import dct, idct
N = 512
t = np.arange(N) / N
signals = {
"smooth": np.exp(-((t - 0.4) / 0.15) ** 2) + 0.3 * np.sin(6 * np.pi * t),
"with a jump": np.where(t < 0.5, np.sin(2 * np.pi * t), 0.2 + 0.5 * t),
}
for name, x in signals.items():
c = dct(x, norm="ortho")
order = np.argsort(np.abs(c))[::-1]
for K in (8, 32, 128):
keep = np.zeros(N); keep[order[:K]] = c[order[:K]]
err = np.linalg.norm(x - idct(keep, norm="ortho")) / np.linalg.norm(x)
print(f"{name:12s} K={K:3d} ({100 * K / N:4.1f} % of coefficients): relative error {err:.1e}")smooth K= 8 ( 1.6 % of coefficients): relative error 6.0e-02
smooth K= 32 ( 6.2 % of coefficients): relative error 3.5e-03
smooth K=128 (25.0 % of coefficients): relative error 2.6e-04
with a jump K= 8 ( 1.6 % of coefficients): relative error 7.4e-02
with a jump K= 32 ( 6.2 % of coefficients): relative error 3.2e-02
with a jump K=128 (25.0 % of coefficients): relative error 1.4e-02
The smooth signal is captured almost perfectly by 32 of 512 coefficients; the signal with a jump needs many more, because jumps spread energy over all frequencies (coefficients decaying like ). Wavelet bases handle such localized features better, which is why JPEG 2000 uses them.
DFT versus DCT
For non-periodic data the DFT pays for the implied jump between the end and the start of the frame. The DCT's mirrored extension avoids it:
import numpy as np
from scipy.fft import dct
N = 256
t = np.arange(N) / N
x = 1 + 2 * t + 0.3 * np.sin(5 * np.pi * t) # trends up: start and end differ
def energy_in_top(c, K):
e = np.sort(np.abs(c) ** 2)[::-1]
return e[:K].sum() / e.sum()
for K in (4, 16):
print(f"top {K:2d} coefficients hold: DCT {100 * energy_in_top(dct(x, norm='ortho'), K):.4f} % "
f"DFT {100 * energy_in_top(np.fft.fft(x) / np.sqrt(N), K):.4f} %")top 4 coefficients hold: DCT 99.7540 % DFT 97.0029 %
top 16 coefficients hold: DCT 99.9983 % DFT 99.4268 %
Denoising by thresholding
White noise spreads evenly across all coefficients of any orthonormal basis, while the signal concentrates in a few. Setting small coefficients to zero (hard thresholding) removes most of the noise and little of the signal:
import numpy as np
from scipy.fft import dct, idct
rng = np.random.default_rng(8)
N = 1024
t = np.arange(N) / N
clean = np.sin(2 * np.pi * 3 * t) + 0.5 * np.cos(2 * np.pi * 11 * t) * np.exp(-2 * t)
sigma = 0.3
noisy = clean + sigma * rng.normal(size=N)
c = dct(noisy, norm="ortho")
thr = sigma * np.sqrt(2 * np.log(N)) # the "universal" threshold
den = idct(np.where(np.abs(c) > thr, c, 0.0), norm="ortho")
rms = lambda e: float(np.sqrt(np.mean(e ** 2)))
print(f"threshold {thr:.3f}: kept {int(np.sum(np.abs(c) > thr))} of {N} coefficients")
print(f"RMS error noisy {rms(noisy - clean):.4f} -> denoised {rms(den - clean):.4f}")threshold 1.117: kept 10 of 1024 coefficients
RMS error noisy 0.3029 -> denoised 0.0722
In software
- MP3/AAC (MDCT plus a psychoacoustic model deciding which coefficients matter), JPEG (DCT), JPEG 2000 and wavelet denoising (
pywt), and compressed sensing, which reconstructs compressible signals from few measurements. - Low-rank approximation with the SVD is the same "keep the largest coefficients" idea in a data-adapted basis; see Low-Rank Approximation.
Exercises
Exercise 1: Error from dropped energy
An orthonormal transform of a signal with energy 100 has coefficients you drop with total energy 1. What is the relative RMS error of the reconstruction?
Answer
10 % (relative norm error ).
Solution
By Parseval the error energy is 1, so the relative error in norm is .
Exercise 2: Why does noise not compress?
Why is white noise incompressible in every orthonormal basis?
Answer
Its energy is spread equally over all coefficients in any orthonormal basis.
Solution
White noise has covariance , and for an orthonormal the coefficients have covariance as well. No basis concentrates it, so there is nothing to drop without losing noise energy in proportion.
Exercise 3: How many coefficients for 99.9 %? (code)
For the smooth signal above, how many of the largest DCT coefficients hold 99.9 % of the energy?
Answer
12 coefficients out of 512.
Solution
import numpy as np
from scipy.fft import dct
N = 512
t = np.arange(N) / N
x = np.exp(-((t - 0.4) / 0.15) ** 2) + 0.3 * np.sin(6 * np.pi * t)
e = np.sort(dct(x, norm="ortho") ** 2)[::-1]
print(int(np.argmax(np.cumsum(e) / e.sum() >= 0.999)) + 1)12
Test yourself
In an orthonormal basis, the best -term approximation keeps…
- the first coefficients
- the largest coefficients in magnitude
- random coefficients
- the smallest coefficients
Signals with jumps compress poorly in Fourier or cosine bases because…
- they are too short
- their coefficients decay only like
- they are complex
- they have no DC
Thresholding small coefficients denoises because…
- noise is concentrated in a few coefficients
- the signal is concentrated in a few coefficients while noise is spread evenly
- it removes the DC term
- it increases the sampling rate