Optimal Code Lengths
The entropy bound says no symbol code beats bits per symbol, and equality needs . Those ideal lengths are usually not integers. This lesson shows that rounding them up costs less than one bit, that coding blocks of symbols spreads that bit over the block, and what it costs to use lengths matched to the wrong distribution.
Shannon code lengths
Choose . These lengths satisfy Kraft, because and the probabilities sum to 1, so a prefix code with them exists (The Kraft Inequality). Since ,
This is the source coding theorem for symbol codes.
import numpy as np
P = np.array([0.4, 0.3, 0.2, 0.1])
ideal = np.log2(1 / P)
shannon = np.ceil(ideal).astype(int)
print("ideal lengths: ", np.round(ideal, 3))
print("Shannon lengths:", shannon, " Kraft sum:", float(np.sum(2.0 ** -shannon)))
print(f"H = {-np.sum(P * np.log2(P)):.4f}, L = {P @ shannon:.4f}")ideal lengths: [1.322 1.737 2.322 3.322]
Shannon lengths: [2 2 3 4] Kraft sum: 0.6875
H = 1.8464, L = 2.4000
Shannon lengths are not always optimal: here the Kraft sum is well below 1, which wastes code space. Huffman's algorithm finds the best integer lengths (Huffman Coding).
Blocking removes the extra bit
Applying the bound to blocks of symbols, whose entropy is , gives , so per symbol
The overhead per symbol shrinks as . The cost is an alphabet of size ; arithmetic coding gets the same effect without building the huge code (Arithmetic Coding).
import numpy as np
from itertools import product
p = np.array([0.9, 0.1])
H = -np.sum(p * np.log2(p))
for n in [1, 2, 4, 8, 12]:
probs = np.array([np.prod(c) for c in product(p, repeat=n)])
L = probs @ np.ceil(np.log2(1 / probs))
print(f"n = {n:2d}: Shannon code {L / n:.4f} bits/symbol (H = {H:.4f})")n = 1: Shannon code 1.3000 bits/symbol (H = 0.4690)
n = 2: Shannon code 0.8000 bits/symbol (H = 0.4690)
n = 4: Shannon code 0.5509 bits/symbol (H = 0.4690)
n = 8: Shannon code 0.5501 bits/symbol (H = 0.4690)
n = 12: Shannon code 0.4951 bits/symbol (H = 0.4690)
The cost of a wrong model
If the code lengths are ideal for a model , , but the data follow , the expected length is the cross-entropy:
Every bit of KL divergence is a bit wasted per symbol (Relative Entropy (KL Divergence)).
import numpy as np
P = np.array([0.5, 0.25, 0.125, 0.125])
for name, Q in [("true model", P), ("slightly off", np.array([0.4, 0.3, 0.15, 0.15])),
("uniform", np.ones(4) / 4), ("badly off", np.array([0.05, 0.05, 0.45, 0.45]))]:
L = P @ np.log2(1 / Q)
print(f"{name:12s}: L = {L:.4f}, KL = {np.sum(P * np.log2(P / Q)):.4f}")true model : L = 1.7500, KL = 0.0000
slightly off: L = 1.7794, KL = 0.0294
uniform : L = 2.0000, KL = 0.2500
badly off : L = 3.5294, KL = 1.7794
Dyadic distributions
When every probability is a power of (a dyadic distribution), the ideal lengths are integers and exactly. For other distributions some redundancy remains for symbol codes.
In software
- Adaptive compressors estimate as they go, so their redundancy is the KL divergence between the true statistics and the running estimate, which shrinks as more data arrive.
- When a format allows blocking or arithmetic coding, prefer it for very skewed sources (one symbol with probability near 1), where symbol codes waste close to 1 bit per symbol.
Exercises
Exercise 1: Shannon lengths
Compute Shannon code lengths for .
Answer
.
Solution
, , , .
Exercise 2: Very skewed source
A source emits a with probability 0.99. What is the best expected length of a symbol code with 2 symbols, and what is the entropy?
Answer
1 bit versus about 0.081 bits.
Solution
Every codeword needs at least 1 bit, so , while . The redundancy is over 90%; blocking or arithmetic coding is needed.
Exercise 3: Mismatched code (code)
Code lengths were designed for , but the data follow . Compute the expected length and .
Answer
2.25 bits per symbol, and the divergence is 0.25 bits.
Solution
import numpy as np
P = np.ones(4) / 4; Q = np.array([0.5, 0.25, 0.125, 0.125])
print(float(P @ np.log2(1 / Q)), float(np.sum(P * np.log2(P / Q))))2.25 0.25
The uniform data have entropy 2, and the mismatch adds 0.25 bits.
Test yourself
Shannon code lengths give an expected length…
- between H and H + 1
- exactly H
- below H
- between H + 1 and H + 2
Coding blocks of n symbols reduces the per-symbol overhead to below…
- bit
- 1 bit
- bits
- bit
Using code lengths ideal for Q on data from P costs on average…
- bits
- bits
- bits
- bits