Huffman Coding
Shannon code lengths are within one bit of the entropy, but they are not the best integer lengths. In 1952 David Huffman, then a student, found a simple greedy algorithm that produces an optimal prefix code: no other symbol code has a smaller expected length. The Huffman Coding lesson in the algorithms course covers the data structures; this lesson focuses on why it is optimal and how close it gets to the entropy.
The algorithm
- Start with one leaf per symbol, weighted by its probability.
- Repeatedly remove the two lightest nodes and join them under a new parent whose weight is their sum.
- When one node remains, the codeword of a symbol is the path from the root to its leaf (
0for one branch,1for the other).
import heapq
import numpy as np
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)] # (weight, tie-breaker, symbols in subtree)
heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap)
w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2:
lengths[s] += 1 # every merge adds one bit above these leaves
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return np.array(lengths)
P = np.array([0.4, 0.3, 0.2, 0.1])
L = huffman_lengths(P)
print("Huffman lengths:", L, " expected length:", round(float(P @ L), 4))
print("Shannon lengths:", np.ceil(np.log2(1 / P)).astype(int), " expected length:", round(float(P @ np.ceil(np.log2(1 / P))), 4))
print("entropy:", round(float(-np.sum(P * np.log2(P))), 4))Huffman lengths: [1 2 3 3] expected length: 1.9
Shannon lengths: [2 2 3 4] expected length: 2.4
entropy: 1.8464
Huffman's 1.9 bits beats the Shannon code's 2.4 and is the best possible, as the brute-force check in The Kraft Inequality also found.
Why it is optimal
The proof rests on two facts about some optimal code:
- The two least probable symbols have the longest codewords, and those codewords can be made siblings (they differ only in the last bit). Otherwise swapping codewords would not increase the expected length.
- Merging them reduces the problem: if two sibling leaves with probabilities and are replaced by one leaf of probability , the expected length drops by exactly , whatever the rest of the tree looks like. So an optimal code for the reduced alphabet extends to an optimal code for the original.
Induction on the alphabet size finishes the proof. Brute force over all length lists confirms it on small examples:
import heapq
import numpy as np
from itertools import product
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2: lengths[s] += 1
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return np.array(lengths)
rng = np.random.default_rng(0)
all_ok = True
for _ in range(200):
P = rng.dirichlet(np.ones(5))
best = min(P @ np.array(l) for l in product(range(1, 6), repeat=5) if sum(2.0 ** -np.array(l)) <= 1)
all_ok &= bool(np.isclose(P @ huffman_lengths(P), best))
print("Huffman matched the brute-force optimum on 200 random 5-symbol sources:", all_ok)Huffman matched the brute-force optimum on 200 random 5-symbol sources: True
How close to the entropy?
Huffman codes satisfy like Shannon codes, and in practice they are usually much closer. A tighter bound: , where is the largest probability. The redundancy is large only when one symbol dominates.
import heapq
import numpy as np
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2: lengths[s] += 1
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return np.array(lengths)
english = np.array([8.2, 1.5, 2.8, 4.3, 12.7, 2.2, 2.0, 6.1, 7.0, 0.15, 0.77, 4.0, 2.4,
6.7, 7.5, 1.9, 0.095, 6.0, 6.3, 9.1, 2.8, 0.98, 2.4, 0.15, 2.0, 0.074])
english /= english.sum()
for name, P in [("English letters", english), ("skewed", np.array([0.9, 0.05, 0.03, 0.02]))]:
H = -np.sum(P * np.log2(P)); L = P @ huffman_lengths(P)
print(f"{name:16s}: H = {H:.4f}, Huffman L = {L:.4f}, redundancy {L - H:.4f} bits")English letters : H = 4.1758, Huffman L = 4.2049, redundancy 0.0291 bits
skewed : H = 0.6175, Huffman L = 1.1500, redundancy 0.5325 bits
Huffman codes for blocks
For the skewed source, coding pairs or triples of symbols with a Huffman code over the block alphabet cuts the redundancy, at the price of a larger code table:
import heapq
import numpy as np
from itertools import product
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2: lengths[s] += 1
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return np.array(lengths)
p = np.array([0.9, 0.05, 0.03, 0.02])
H = -np.sum(p * np.log2(p))
for n in [1, 2, 3]:
probs = np.array([np.prod(c) for c in product(p, repeat=n)])
print(f"blocks of {n}: {len(probs):3d} codewords, {probs @ huffman_lengths(probs) / n:.4f} bits/symbol (H = {H:.4f})")blocks of 1: 4 codewords, 1.1500 bits/symbol (H = 0.6175)
blocks of 2: 16 codewords, 0.7690 bits/symbol (H = 0.6175)
blocks of 3: 64 codewords, 0.6735 bits/symbol (H = 0.6175)
In software
heapqgives the two lightest nodes in , so building the code is .- Real formats limit codeword lengths (DEFLATE to 15 bits) and transmit only the lengths (Huffman Coding in Practice).
Exercises
Exercise 1: By hand
Build a Huffman code for . What are the lengths and the expected length?
Answer
Lengths , expected length 2.2 bits.
Solution
Merge ; then ; then ; then . The symbols 0.35 and 0.25 sit at depth 2, the original 0.2 at depth 2, and 0.15, 0.05 at depth 3. .
Exercise 2: Ties
Is the Huffman code unique?
Answer
No.
Solution
Ties between equal weights and the choice of which branch is 0 give different codes, sometimes even different length lists, but all have the same optimal expected length.
Exercise 3: Huffman for a text (code)
Compute Huffman code lengths for the letter frequencies of "information theory" (spaces included) and compare the expected length with the entropy.
Answer
3.5 bits per character versus an entropy of about 3.461.
Solution
import heapq
import numpy as np
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]; heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap); w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2: lengths[s] += 1
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return np.array(lengths)
_, counts = np.unique(list("information theory"), return_counts=True)
P = counts / counts.sum()
print(round(float(P @ huffman_lengths(P)), 4), round(float(-np.sum(P * np.log2(P))), 4))3.5 3.4613
Test yourself
At each step, Huffman's algorithm merges…
- the two least probable nodes
- the two most probable nodes
- the most and least probable nodes
- two random nodes
Huffman codes are optimal among…
- symbol codes (prefix codes with one codeword per symbol)
- all compressors
- arithmetic codes
- block codes of any length
When is the redundancy of a Huffman code largest?
- when one symbol has probability close to 1
- when the distribution is uniform over 2^k symbols
- when the distribution is dyadic
- never: it is always zero