TExcelTAD
Home › Information Theory › Quantization

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 Δ\Delta, a uniform quantizer rounds xx to the nearest multiple of Δ\Delta. If the signal is much wider than Δ\Delta, the error is approximately uniform on [−Δ2,Δ2][-\frac{\Delta}{2}, \frac{\Delta}{2}], with mean squared error

D≈Δ212D \approx \frac{\Delta^2}{12}
python · try it yourself
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 bb-bit uniform quantizer covering a range of width AA has Δ=A2b\Delta = \frac{A}{2^b}, so every extra bit halves Δ\Delta 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.

python · try it yourself
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:

  1. Each decision threshold lies halfway between neighbouring reconstruction levels (nearest-neighbour rule).
  2. Each reconstruction level is the mean of the values that map to it (centroid rule).
python · try it yourself
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 D=2−2bD = 2^{-2b} (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 H(X^)H(\hat X) bits per sample on average. At high resolution this gets within 12log⁡2πe6≈0.254\frac{1}{2}\log_2 \frac{\pi e}{6} \approx 0.254 bits of R(D)R(D), whatever the source:

python · try it yourself
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) * delta is a uniform quantizer; np.digitize with 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 KMeans on 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 3.33×10−53.33 \times 10^{-5}.

Solution

0.02212=0.000412=3.33×10−5\frac{0.02^2}{12} = \frac{0.0004}{12} = 3.33 \times 10^{-5}.

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

6.02b+1.76≥606.02b + 1.76 \ge 60 gives b≥9.67b \ge 9.67, so 10 bits.

Exercise 3: 1-bit quantizer (code)

The best 1-bit quantizer for a standard Gaussian outputs ±c\pm c. Show that c=2/πc = \sqrt{2/\pi} (the mean of ∣X∣|X|) and compute its MSE.

Answer

c≈0.798c \approx 0.798 and MSE =1−2π≈0.363= 1 - \frac{2}{\pi} \approx 0.363.

Solution
python · try it yourself
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 x>0x > 0 is E[X∣X>0]=2/πE[X \mid X > 0] = \sqrt{2/\pi}.

Test yourself

The mean squared error of a fine uniform quantizer with step Delta is about…

  1. Δ212\frac{\Delta^2}{12}
  2. Δ2\frac{\Delta}{2}
  3. Δ2\Delta^2
  4. Δ24\frac{\Delta^2}{4}

Each extra bit of a uniform quantizer improves the SQNR by about…

  1. 6 dB
  2. 3 dB
  3. 10 dB
  4. 1 dB

Lloyd-Max quantizer design is equivalent to…

  1. one-dimensional k-means
  2. Huffman coding
  3. gradient descent on the entropy
  4. the Fourier transform