Quantization
Quantization maps a continuous value to one of a finite set of levels. It is the step where lossy compression actually loses information, and it happens every time an analog signal is digitized. This lesson measures uniform quantizers, designs optimal ones with the Lloyd-Max algorithm, and compares them with the rate-distortion limit.
The uniform quantizer
With step size , a uniform quantizer rounds to the nearest multiple of . If the signal is much wider than , the error is approximately uniform on , with mean squared error
import numpy as np
rng = np.random.default_rng(0)
x = rng.normal(0, 1, 1_000_000)
for delta in [1.0, 0.5, 0.1]:
q = delta * np.round(x / delta)
print(f"delta = {delta}: MSE {np.mean((x - q)**2):.5f}, delta^2/12 = {delta**2 / 12:.5f}")delta = 1.0: MSE 0.08325, delta^2/12 = 0.08333
delta = 0.5: MSE 0.02084, delta^2/12 = 0.02083
delta = 0.1: MSE 0.00083, delta^2/12 = 0.00083
Six decibels per bit
A -bit uniform quantizer covering a range of width has , so every extra bit halves and quarters the error: about 6.02 dB more signal-to-quantization-noise ratio per bit. CD audio's 16 bits give roughly 96 dB of range.
import numpy as np
rng = np.random.default_rng(1)
x = np.sin(2 * np.pi * rng.random(500_000)) # full-scale sine values in [-1, 1]
for b in [4, 8, 12, 16]:
delta = 2 / 2**b
q = np.clip(delta * (np.floor(x / delta) + 0.5), -1 + delta / 2, 1 - delta / 2)
snr = 10 * np.log10(np.mean(x**2) / np.mean((x - q)**2))
print(f"{b:2d} bits: SQNR = {snr:6.2f} dB (6.02 b + 1.76 = {6.02 * b + 1.76:.2f})") 4 bits: SQNR = 25.32 dB (6.02 b + 1.76 = 25.84)
8 bits: SQNR = 49.78 dB (6.02 b + 1.76 = 49.92)
12 bits: SQNR = 73.97 dB (6.02 b + 1.76 = 74.00)
16 bits: SQNR = 98.08 dB (6.02 b + 1.76 = 98.08)
Optimal scalar quantizers: Lloyd-Max
For a non-uniform signal, a non-uniform quantizer does better. The Lloyd-Max algorithm alternates two optimality conditions, exactly like k-means clustering in one dimension:
- Each decision threshold lies halfway between neighbouring reconstruction levels (nearest-neighbour rule).
- Each reconstruction level is the mean of the values that map to it (centroid rule).
import numpy as np
rng = np.random.default_rng(2)
x = np.sort(rng.normal(0, 1, 200_000))
def lloyd_max(x, levels, iters=200):
c = np.quantile(x, (np.arange(levels) + 0.5) / levels)
for _ in range(iters):
t = (c[:-1] + c[1:]) / 2
idx = np.searchsorted(t, x)
c = np.array([x[idx == k].mean() for k in range(levels)])
return c, np.mean((x - c[np.searchsorted((c[:-1] + c[1:]) / 2, x)])**2)
for b in [1, 2, 3]:
c, mse = lloyd_max(x, 2**b)
# best uniform quantizer with the same number of levels
best_u = min((np.mean((x - np.clip(d * (np.floor(x / d) + 0.5), -d * (2**b / 2 - 0.5), d * (2**b / 2 - 0.5)))**2), d)
for d in np.linspace(0.2, 2.0, 181))
print(f"{b} bits: Lloyd-Max MSE {mse:.4f}, best uniform MSE {best_u[0]:.4f}, R(D) limit {2.0 ** (-2 * b):.4f}")
if b == 2:
print(" levels:", np.round(c, 3))1 bits: Lloyd-Max MSE 0.3649, best uniform MSE 0.3649, R(D) limit 0.2500
2 bits: Lloyd-Max MSE 0.1177, best uniform MSE 0.1192, R(D) limit 0.0625
levels: [-1.524 -0.462 0.442 1.5 ]
3 bits: Lloyd-Max MSE 0.0345, best uniform MSE 0.0374, R(D) limit 0.0156
Even the optimal scalar quantizer stays above the rate-distortion limit (Rate-Distortion Theory). The gap closes by quantizing vectors of samples jointly (vector quantization) or by entropy-coding the output of a fine uniform quantizer.
Entropy-coded quantization
A uniform quantizer followed by an entropy coder spends bits per sample on average. At high resolution this gets within bits of , whatever the source:
import numpy as np
rng = np.random.default_rng(3)
x = rng.normal(0, 1, 1_000_000)
for delta in [0.5, 0.25, 0.1]:
q = np.round(x / delta).astype(int)
_, counts = np.unique(q, return_counts=True); p = counts / counts.sum()
H = -np.sum(p * np.log2(p))
D = np.mean((x - delta * q)**2)
R_D = 0.5 * np.log2(1 / D)
print(f"delta = {delta}: rate H = {H:.4f} bits, MSE = {D:.5f}, R(D) = {R_D:.4f}, gap {H - R_D:.4f}")delta = 0.5: rate H = 3.0620 bits, MSE = 0.02084, R(D) = 2.7924, gap 0.2696
delta = 0.25: rate H = 4.0506 bits, MSE = 0.00521, R(D) = 3.7925, gap 0.2581
delta = 0.1: rate H = 5.3696 bits, MSE = 0.00083, R(D) = 5.1142, gap 0.2553
In software
np.round(x / delta) * deltais a uniform quantizer;np.digitizewith custom thresholds gives a non-uniform one.- Neural-network quantization (8-bit or 4-bit weights) uses the same ideas: per-channel step sizes, clipping ranges chosen to minimize error, and sometimes k-means codebooks for the weights.
- Scikit-learn's
KMeanson 1-D data is the Lloyd-Max algorithm; on vectors it gives a vector quantizer.
Exercises
Exercise 1: Uniform error
A quantizer has step 0.02. What is its approximate mean squared error?
Answer
About .
Solution
.
Exercise 2: Bits for 60 dB
How many bits does a uniform quantizer need for about 60 dB SQNR on a full-scale sine?
Answer
10 bits.
Solution
gives , so 10 bits.
Exercise 3: 1-bit quantizer (code)
The best 1-bit quantizer for a standard Gaussian outputs . Show that (the mean of ) and compute its MSE.
Answer
and MSE .
Solution
import numpy as np
rng = np.random.default_rng(4)
x = rng.normal(0, 1, 1_000_000)
c = np.abs(x).mean()
print(round(float(c), 3), round(np.sqrt(2 / np.pi), 3), round(float(np.mean((x - c * np.sign(x))**2)), 4), round(1 - 2 / np.pi, 4))0.797 0.798 0.3623 0.3634
By the centroid rule, the level for is .
Test yourself
The mean squared error of a fine uniform quantizer with step Delta is about…
Each extra bit of a uniform quantizer improves the SQNR by about…
- 6 dB
- 3 dB
- 10 dB
- 1 dB
Lloyd-Max quantizer design is equivalent to…
- one-dimensional k-means
- Huffman coding
- gradient descent on the entropy
- the Fourier transform