Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

3. Shannon Coding Theory

CNRS & DMA, École Normale Supérieure

Chapter PDF · Complete book

A sequence of symbols can often be stored using fewer bits when its probabilities and dependencies are taken into account. The challenge is to reduce the expected length while keeping every message unambiguously recoverable. Prefix codes and entropy lead to Shannon’s source coding bound; Huffman’s construction and block coding show how to approach it. Empirical block counts connect these bounds to finite texts, while models of dependent symbols reveal further compression gains.

3.1 Source Coding

Uniform coding.

We consider an alphabet (s1,,sK)(s_1,\ldots,s_K) of KK symbols. For signal samples 0f0<10 \leqslant f_0 < 1 quantized into KK bins, the symbols label the bins. For text, they may represent letters, punctuation marks, and spaces.

A fixed-length binary code uses log2(K)\lceil \log_2(K) \rceil bits per symbol. For example, if K=4K=4 and the symbols are {0,1,2,3}\{0,1,2,3\}, one possible code is (c0=00,c1=01,c2=10,c3=11)(c_0=00,c_1=01,c_2=10,c_3=11).

When some symbols are much more frequent than others, variable-length codes can reduce the average number of bits per symbol by assigning shorter codewords to frequent symbols.

Prefix coding.

A binary code assigns each symbol sks_k a finite word ck=c(sk)0{0,1}c_k=c(s_k)\in\bigcup_{\ell\geqslant 0}\{0,1\}^{\ell} of length ck|c_k|. An empty word is allowed only for a one-symbol alphabet, with the message length supplied separately.

A code is a prefix code if no codeword is a prefix of another. Equivalently, the codewords correspond to leaves of a binary tree TT: starting at the root, traversing an edge to the left appends 0, and traversing an edge to the right appends 1.

We write c=Leaves(T)c=\text{Leaves}(T) for this tree representation.

Figure 3.1. Left: the complete tree of binary words of length 3. Right: a prefix code.

To decode a binary stream, follow its bits down the tree. Upon reaching a leaf, output the corresponding symbol and return to the root. The prefix property makes this decoding unambiguous and instantaneous: each symbol is recognized as soon as the last bit of its codeword has been read.

For codes with nonempty codewords, unique decodability means that every encoded finite message has exactly one decomposition into codewords. Prefix codes have this property, but a uniquely decodable code need not be a prefix code. For example, consider

c(s1)=0,c(s2)=01.c(s_1)=0, \qquad c(s_2)=01.

The word 0 is a prefix of 01, yet decoding is unique: every 1 must be paired with the immediately preceding 0 to form 01, and every remaining 0 represents s1s_1. Thus 00101 can only be split as 001010\mid01\mid01, encoding s1s2s2s_1s_2s_2.

After reading a 0, however, the decoder must inspect the next bit, or know that the message has ended, before deciding which symbol to output. If it has already committed to s1s_1 and the next bit is 1, it must backtrack and decode 01 as s2s_2. One bit of lookahead avoids this backtracking here, but still introduces a decoding delay. Prefix coding avoids such tentative decisions and the associated lookahead or backtracking overhead.

Probabilistic modeling.

We seek a code with the smallest expected length.

Let p=(p1,,pK)R+Kp=(p_1,\ldots,p_K)\in\mathbb{R}_+^K be the symbol probability vector, with kpk=1\sum_kp_k=1.

In practice, one often estimates pkp_k from the relative frequency of sks_k in the data. The decoder must also know the resulting code, either from a shared model or from a transmitted description.

Figure 3.2. The concave function h(u)=ulog2uh(u)=-u\log_2u underlying entropy.

The entropy of the probability distribution pp is

H(p):=kpklog2(pk)H(p) \mathrel{:=}-\sum_k p_k \log_2(p_k)

with the convention 0log2(0)=00\log_2(0)=0.

For h(u)=ulog2uh(u)=-u\log_2u and u>0u>0, one has h(u)=(lnu+1)/ln2h'(u)=-(\ln u+1)/\ln2 and h(u)=1/(uln2)<0h''(u)=-1/(u\ln2)<0. Thus HH is strictly concave on the probability simplex.

For a probability density ff with respect to a reference measure dx\mathrm{d}x, such as Lebesgue measure on Rd\mathbb{R}^d, differential entropy is defined by H(f):=f(x)log2(f(x))dxH(f)\mathrel{:=}-\int f(x)\log_2(f(x))\,\mathrm{d}x, whenever this integral is defined. Unlike discrete entropy, it can be negative and depends on the reference measure.

Figure 3.3. Three examples of probability distributions with corresponding entropies in bits.

Figure 3.4. Entropy is minimized at a point mass and maximized at the uniform distribution. Left: level sets of the entropy formula in the positive quadrant and the constraint p1+p2=1p_1+p_2=1. Middle: its restriction to that constraint. Right: entropy level sets on the three-symbol probability simplex.

The quantity KL(pq):=ipilog2(pi/qi)0\mathrm{KL}(p\mid q)\mathrel{:=}\sum_i p_i\log_2(p_i/q_i)\geqslant 0 is called the Kullback–Leibler divergence, or relative entropy between pp and qq. The conventions are 0log2(0/qi)=00\log_2(0/q_i)=0 and pilog2(pi/0)=+p_i\log_2(p_i/0)=+\infty for pi>0p_i>0. Although it vanishes exactly when p=qp=q, it is not a metric: it is generally asymmetric and does not satisfy the triangle inequality. Minimizing the cross-entropy between an empirical distribution and a model is equivalent to maximizing the likelihood, and to minimizing their relative entropy. Cross-entropy is therefore a common objective in classification.

3.2 Shannon Source Coding Theorem

For a symbol distribution pp, the expected codeword length of a code cc is

L(c):=kpkck.L(c) \mathrel{:=}\sum_k p_k |c_k|.

We seek a prefix code minimizing L(c)L(c).

Shannon’s source coding theorem bounds the optimal expected length in terms of entropy.

Kraft’s inequality characterizes the possible codeword lengths of a prefix code and is the key to the proof.

This proof is constructive: rounding the ideal lengths and using Kraft’s lemma yields a Shannon code. It need not minimize L(c)L(c). Huffman’s greedy algorithm constructs an optimal binary prefix code by repeatedly merging the two least probable symbols. With a priority queue, its cost is O(KlogK)O(K\log K). Figure 3.6 illustrates the construction.

Figure 3.6. Successive merges in Huffman’s coding algorithm.

Associated code: coding/test_text.m

3.3 Probabilistic Modeling

3.3.1 Block Coding

Symbol-by-symbol prefix coding may be inefficient when one symbol has probability close to one: its ideal length log2pk-\log_2p_k is then below one bit, whereas a nontrivial prefix code uses at least one bit per symbol. A remedy is to group rr consecutive symbols into blocks and code the resulting alphabet of size KrK^r.

For independent symbols with common distribution pp, the block distribution is

Pk1,,kr=pk1pkr,H(P)=rH(p).P_{k_1,\ldots,k_r}=p_{k_1}\cdots p_{k_r}, \qquad H(P)=rH(p).

Shannon’s theorem applied to blocks gives an expected length per original symbol in the interval [H(p),H(p)+1/r)[H(p),H(p)+1/r). This is an exact expectation bound under the model; no large-sample limit is needed. The code is prefix-free on blocks, so it need not use an integer number of bits per original symbol on average.

For dependent symbols whose marginal distributions are all pp, entropy subadditivity gives

H(P)rH(p),H(P)\leqslant rH(p),

with equality if and only if the symbols within the block are independent. For NN divisible by rr, the expected total length is at most

Nr(H(P)+1)N(H(p)+1r).\frac{N}{r}\bigl(H(P)+1\bigr) \leqslant N\left(H(p)+\frac1r\right).

Modeling dependence can therefore reduce the expected length further. For a stationary source on a finite alphabet, the block entropies are subadditive, so the entropy rate limrH(P)/r\lim_{r\to\infty}H(P)/r exists. This rate is the asymptotic lower bound on the expected number of bits per symbol.

3.3.2 Empirical Block Coding

The same entropy bound has a finite-text counterpart. Fix a text x1xNx_1\cdots x_N over the alphabet A={s1,,sK}\mathcal A=\{s_1,\ldots,s_K\}, and assume N=mrN=mr with m,r1m,r\geqslant 1. Split it into mm non-overlapping blocks of length rr:

Bs=(x(s1)r+1,,xsr)Ar,s=1,,m.B_s=(x_{(s-1)r+1},\ldots,x_{sr})\in\mathcal A^r, \qquad s=1,\ldots,m.

Define the empirical symbol and block distributions by counting occurrences:

p^(a)=1Ni=1N1{xi=a},aA,(3.4)\begin{aligned} \hat p(a)&=\frac1N\sum_{i=1}^N\mathbf1_{\{x_i=a\}}, &&a\in\mathcal A, \end{aligned} \tag{3.4}
P^(w)=1ms=1m1{Bs=w},wAr.(3.5)\begin{aligned} \hat P(w)&=\frac1m\sum_{s=1}^m\mathbf1_{\{B_s=w\}}, &&w\in\mathcal A^r. \end{aligned} \tag{3.5}

These distributions describe the fixed text; no assumption on how it was generated is needed.

For each position t{1,,r}t\in\{1,\ldots,r\} within a block, let

q^t(a)=1ms=1m1{x(s1)r+t=a}=w:wt=aP^(w).\hat q_t(a)=\frac1m\sum_{s=1}^m\mathbf1_{\{x_{(s-1)r+t}=a\}} =\sum_{w:w_t=a}\hat P(w).

Thus q^t\hat q_t is the tt-th marginal of P^\hat P. The position marginals need not coincide, but every symbol occurrence contributes to exactly one of them. Consequently,

p^=1rt=1rq^t.(3.6)\hat p=\frac1r\sum_{t=1}^r\hat q_t. \tag{3.6}

The first inequality is an equality exactly when P^=Q\hat P=Q; the second is an equality exactly when all position marginals equal p^\hat p. Hence H(P^)=rH(p^)H(\hat P)=rH(\hat p) holds exactly when P^=p^r\hat P=\hat p^{\otimes r}.

Encoded length of the fixed text.

For a prefix code cc on the observed blocks, the actual number of encoded bits is

text(c)=s=1mc(Bs)=mw:P^(w)>0P^(w)c(w).\ell_{\mathrm{text}}(c)=\sum_{s=1}^m|c(B_s)| =m\sum_{w:\hat P(w)>0}\hat P(w)|c(w)|.

Applying Theorem 3.2 to P^\hat P shows that every such code satisfies text(c)mH(P^)\ell_{\mathrm{text}}(c)\geqslant mH(\hat P), and that some code satisfies

text(c)N<H(P^)r+1rH(p^)+1r.(3.8)\frac{\ell_{\mathrm{text}}(c)}{N} <\frac{H(\hat P)}{r}+\frac1r \leqslant H(\hat p)+\frac1r. \tag{3.8}

This bounds the actual average number of bits per symbol for the given text, at every admissible block length. The decoder is assumed to know the block code, rr, and NN; any transmitted codebook or message-length description adds to this length. In particular, when only one distinct block occurs, its empty codeword can be decoded because the number of blocks is known.

3.3.3 Mismatched Probability Models

For ideal real-valued lengths based on a model qq, the excess expected length is the relative entropy, also called the Kullback–Leibler divergence. For qk>0q_k>0 whenever pk>0p_k>0, this excess is

KL(pq)=kpklog2qkH(p)=kpklog2pkqk0.\text{KL}(p|q) = -\sum_k p_k \log_2 q_k - H(p) = \sum_k p_k \log_2 \frac{p_k}{q_k} \geqslant 0.

After lengths are rounded to integers, the difference between the expected lengths of two prefix codes need not equal this divergence. Relative entropy is jointly convex in (p,q)(p,q) and is a central tool for comparing probability distributions in information theory and statistics.

3.4 Exploiting Statistical Dependence

A memoryless code based on the marginal distribution cannot have expected length below the marginal entropy. Dependent data, however, can be coded more efficiently by modeling their joint distribution. An invertible transformation of the discrete symbols can make the dependence easier to encode while preserving their joint entropy. For example, consecutive samples of a smooth signal often have small differences. Figure 3.7 illustrates coding these differences instead of the original values. The initial sample must also be retained to make the transformation invertible.

Figure 3.7. Difference coding. From left to right: the signal, its first differences, the corresponding histograms, and a code tree for the differences.

Another way to exploit temporal redundancy is run-length coding: each maximal run of identical symbols is represented by the symbol and the run length, which can itself be entropy-coded. Its performance depends on how the run lengths and transitions are modeled.

For a stationary finite-state Markov chain with stationary probabilities πi\pi_i and transition probabilities PijP_{ij}, the entropy rate is i,jπiPijlog2Pij-\sum_{i,j}\pi_iP_{ij}\log_2P_{ij}. Coding with the conditional transition probabilities, or coding sufficiently long blocks, can approach this rate. Run-length coding alone does not guarantee this performance.