TExcelTAD
Home › Information Theory › The Source Coding Theorem

The Source Coding Theorem

Shannon's source coding theorem answers the first central question of information theory: a source with entropy HH bits per symbol can be compressed to about HH bits per symbol, and not less. Typical sets make both halves of the proof short.

Statement

Let XX be a source of independent symbols with entropy HH. For blocks of nn symbols and any ϵ>0\epsilon > 0:

  1. Achievability: for large nn there is a code using at most n(H+ϵ)n(H + \epsilon) bits per block whose failure probability goes to zero.
  2. Converse: any code using at most n(H−ϵ)n(H - \epsilon) bits per block fails with probability that goes to one.

In MacKay's formulation with the essential bit content of Raw Bit Content and Lossy Counting: for any 0<δ<10 < \delta < 1, 1nHδ(Xn)→H\frac{1}{n}H_\delta(X^n) \to H.

Proof of achievability

Number the typical sequences (Typical Sets): there are at most 2n(H+β)2^{n(H + \beta)}, so n(H+β)+1n(H + \beta) + 1 bits label them all. Send a flag bit 0 followed by the label for typical sequences. For the rare atypical ones, send a 1 followed by the raw sequence (or declare failure). Because atypical sequences have vanishing probability, the average length per symbol tends to H+βH + \beta.

python · try it yourself
import numpy as np
from scipy.special import gammaln
from scipy.stats import binom

f, beta = 0.1, 0.03
H = -f * np.log2(f) - (1 - f) * np.log2(1 - f)
for n in [100, 1000, 10000, 100000]:
    k = np.arange(n + 1)
    surprise = -(k * np.log2(f) + (n - k) * np.log2(1 - f)) / n
    typ = np.abs(surprise - H) < beta
    p_typ = binom.pmf(k[typ], n, f).sum()
    label_bits = np.ceil(np.logaddexp2.reduce((gammaln(n + 1) - gammaln(k[typ] + 1) - gammaln(n - k[typ] + 1)) / np.log(2)))
    avg = 1 + p_typ * label_bits + (1 - p_typ) * n          # flag + label, or flag + raw
    print(f"n = {n:6d}: P(typical) = {p_typ:.4f}, average {avg / n:.4f} bits/symbol   (H = {H:.4f})")
n =    100: P(typical) = 0.1319, average 0.9362 bits/symbol   (H = 0.4690)
n =   1000: P(typical) = 0.6835, average 0.6545 bits/symbol   (H = 0.4690)
n =  10000: P(typical) = 0.9984, average 0.4984 bits/symbol   (H = 0.4690)
n = 100000: P(typical) = 1.0000, average 0.4982 bits/symbol   (H = 0.4690)

For short blocks the atypical escape costs a lot; as nn grows the rate falls toward H+βH + \beta, and a smaller β\beta brings it closer to HH for even larger nn.

Proof of the converse (idea)

A code with n(H−ϵ)n(H - \epsilon) bits has at most 2n(H−ϵ)2^{n(H - \epsilon)} codewords. Each typical sequence has probability at most 2−n(H−β)2^{-n(H - \beta)}, so the codewords can cover at most 2n(H−ϵ)⋅2−n(H−β)=2−n(ϵ−β)2^{n(H - \epsilon)} \cdot 2^{-n(H - \beta)} = 2^{-n(\epsilon - \beta)} of the typical probability (choose β<ϵ\beta < \epsilon). Atypical sequences have vanishing probability too. Hence the success probability goes to zero.

python · try it yourself
import numpy as np
from scipy.special import gammaln
from scipy.stats import binom

f = 0.1
H = -f * np.log2(f) - (1 - f) * np.log2(1 - f)
rate = H - 0.05                                    # try to compress below the entropy
for n in [100, 1000, 10000]:
    k = np.arange(n + 1)
    log2c = (gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1)) / np.log(2)   # log2 C(n, k)
    log2p = k * np.log2(f) + (n - k) * np.log2(1 - f)                            # log2 P(one sequence)
    # the best code spends its 2^(n rate) codewords on the most probable sequences (fewest ones first)
    left, covered = n * rate, 0.0                  # left = log2 of the codewords still available
    for kk in k:
        if log2c[kk] < left:
            covered += binom.pmf(kk, n, f)
            left += np.log2(-np.expm1((log2c[kk] - left) * np.log(2)))     # log2(2^left - C(n, kk))
        else:
            covered += 2.0 ** (left + log2p[kk])
            break
    print(f"n = {n:5d}: best success probability with {rate:.3f} bits/symbol = {covered:.4f}")
n =   100: best success probability with 0.419 bits/symbol = 0.4665
n =  1000: best success probability with 0.419 bits/symbol = 0.0756
n = 10000: best success probability with 0.419 bits/symbol = 0.0000

Only 0.05 bits per symbol below the entropy, even the best possible code succeeds 47% of the time at n=100n = 100, 8% at n=1000n = 1000 and essentially never at n=10000n = 10000.

Variable-length codes

The theorem is stated for fixed-length block codes that may fail. For variable-length codes that never fail, the same limit holds: the expected length of any uniquely decodable code is at least HH bits per symbol (The Kraft Inequality), and Huffman or arithmetic coding gets within 1 bit per block of it (Optimal Code Lengths).

In software

  • The theorem explains why every compressor reports results relative to an entropy estimate: a compressor beating the true entropy on long random data from a known model would be a bug in the measurement.
  • For sources with memory (text, images), the limit is the entropy rate lim⁡1nH(X1,…,Xn)\lim \frac{1}{n}H(X_1, \dots, X_n), which is lower than the per-symbol entropy because of correlations.

Exercises

Exercise 1: Minimum size

A source emits 10 million symbols with entropy 1.5 bits each. What is the smallest average size of a lossless encoding, in megabytes (1 MB = 10610^6 bytes)?

Answer

About 1.875 MB.

Solution

107×1.5=1.5×10710^7 \times 1.5 = 1.5 \times 10^7 bits =1.875×106= 1.875 \times 10^6 bytes.

Exercise 2: Beating the entropy

A compressor reports 0.4 bits per symbol on a long stream of independent coin flips with P(1)=0.1P(1) = 0.1. What is wrong?

Answer

It is below the entropy 0.469, which is impossible on average.

Solution

Either the flips are not independent with P(1)=0.1P(1) = 0.1, the measurement leaves out part of the output (headers, model parameters), or decompression does not actually reproduce the input.

Exercise 3: Entropy rate of a Markov source (code)

A binary Markov source stays in the same state with probability 0.95. Its stationary distribution is uniform, so its per-symbol entropy is 1 bit. Compute its entropy rate H(X2∣X1)H(X_2 \mid X_1).

Answer

About 0.286 bits per symbol.

Solution
python · try it yourself
import numpy as np

stay = 0.95
H2 = -stay * np.log2(stay) - (1 - stay) * np.log2(1 - stay)
print(round(float(H2), 4))
0.2864

Each step is a biased coin "stay or switch" with probability 0.95, whatever the state. A compressor that models the previous symbol can reach 0.286 bits per symbol.

Test yourself

The source coding theorem says a long block of n symbols needs about…

  1. nH bits
  2. n bits
  3. H bits
  4. 2nH2^{nH} bits

In the achievability proof, atypical sequences…

  1. are rare, so how they are handled hardly affects the average length
  2. are the most common sequences
  3. are discarded only for fair coins
  4. need no bits

Compressing below the entropy rate with fixed-length codes leads to…

  1. failure probability approaching one
  2. smaller files with no cost
  3. a slower decoder
  4. exactly half the sequences failing