3. Shannon Coding Theory

Painting detail by Louis Peyré (1923–2012). About the paintings.
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 of symbols. For signal samples quantized into bins, the symbols label the bins. For text, they may represent letters, punctuation marks, and spaces.
A fixed-length binary code uses bits per symbol. For example, if and the symbols are , one possible code is .
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 a finite word of length . 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 : starting at the root, traversing an edge to the left appends 0, and traversing an edge to the right appends 1.
We write 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
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 . Thus 00101 can only be split as , encoding .
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 and the next bit is 1, it must backtrack and decode 01 as . 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 be the symbol probability vector, with .
In practice, one often estimates from the relative frequency of 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 underlying entropy.
The entropy of the probability distribution is
with the convention .
For and , one has and . Thus is strictly concave on the probability simplex.
For a probability density with respect to a reference measure , such as Lebesgue measure on , differential entropy is defined by , 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 . Middle: its restriction to that constraint. Right: entropy level sets on the three-symbol probability simplex.
The quantity is called the Kullback–Leibler divergence, or relative entropy between and . The conventions are and for . Although it vanishes exactly when , 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 , the expected codeword length of a code is
We seek a prefix code minimizing .
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 . 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 . 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 is then below one bit, whereas a nontrivial prefix code uses at least one bit per symbol. A remedy is to group consecutive symbols into blocks and code the resulting alphabet of size .
For independent symbols with common distribution , the block distribution is
Shannon’s theorem applied to blocks gives an expected length per original symbol in the interval . 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 , entropy subadditivity gives
with equality if and only if the symbols within the block are independent. For divisible by , the expected total length is at most
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 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 over the alphabet , and assume with . Split it into non-overlapping blocks of length :
Define the empirical symbol and block distributions by counting occurrences:
These distributions describe the fixed text; no assumption on how it was generated is needed.
For each position within a block, let
Thus is the -th marginal of . The position marginals need not coincide, but every symbol occurrence contributes to exactly one of them. Consequently,
The first inequality is an equality exactly when ; the second is an equality exactly when all position marginals equal . Hence holds exactly when .
Encoded length of the fixed text.
For a prefix code on the observed blocks, the actual number of encoded bits is
Applying Theorem 3.2 to shows that every such code satisfies , and that some code satisfies
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, , and ; 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 , the excess expected length is the relative entropy, also called the Kullback–Leibler divergence. For whenever , this excess is
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 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 and transition probabilities , the entropy rate is . Coding with the conditional transition probabilities, or coding sufficiently long blocks, can approach this rate. Run-length coding alone does not guarantee this performance.