Contents / Information Theory / Source Coding and the Entropy Bound
Chapter 4
Source Coding and the Entropy Bound
Shannon's source coding theorem in both directions, and Kraft's inequality — why entropy is the floor no lossless code can beat.
Introduction
Shannon's source coding theorem in both directions, and Kraft's inequality — why entropy is the floor no lossless code can beat.
4.1What the Theorem Says
Shannon's source coding theorem — the noiseless coding theorem — is the first of the two pillars of information theory. It converts the counting facts of the previous chapter into a sharp statement about which compression schemes can exist. Its content is that a single number, the entropy rate, is simultaneously an upper and a lower bound on the achievable rate, so that the compressibility of a source is not a matter of ingenuity but of arithmetic.
To state the theorem we must first say precisely what a code is and what its rate means. Vagueness here is what makes the theorem sound paradoxical ("surely a clever enough algorithm...").
Definition 4.1 (Fixed-rate block code and its rate). A block code of length and rate for a source with alphabet is a pair of maps
the encoder and the decoder. Its error probability is
The rate is the number of bits transmitted per source symbol.
The encoder may be any function whatsoever — no structure, locality or computability is required — so a converse proved for this class applies to every conceivable algorithm. That generosity is what makes the negative half of the theorem meaningful.
Definition 4.2 (Achievable rate). A rate is achievable for the source if there exists a sequence of block codes of rate with as .
Theorem 4.3 (Shannon's source coding theorem). Let be a stationary ergodic source with entropy rate .
- Achievability. Every rate is achievable: there are block codes of rate with .
- Converse. No rate is achievable. In fact every sequence of block codes of rate has .
Consequently the infimum of achievable rates equals exactly.
The two halves squeeze the answer from opposite sides. Achievability is a construction; the converse is a counting argument. Neither alone would be worth much: without the converse, would merely be a rate someone once attained; without achievability, it would be a bound nobody could reach.
Remark (Where the error probability went). The typical-set code of the previous part was lossless with a variable length; this theorem concerns fixed-length codes that may fail. The two formulations are equivalent in the limit, and we will meet both: fixed length with vanishing error here, variable length with zero error in the discussion of Kraft's inequality. What cannot be had is fixed length, zero error, and rate below — that combination is forbidden by the pigeonhole principle at every .
Intuition. Entropy is the irreducible size of the data, in the way a suitcase has an irreducible volume. Good compression gets close to it; nothing gets past it, however the packing is organised.
If someone advertises a compressor that beats the entropy rate of your source on average and never errs, they are advertising a bijection from a set into a strictly smaller set.
Example 4.4 (Reading the theorem off a four-letter source). A memoryless source emits with probabilities . What does the theorem promise, and what does it forbid?
Solution. The entropy is
using , , .
Promised. Any rate above , say , is achievable: for large there are codes using bits per block whose failure probability is as small as desired. A file of symbols fits in about Mbit.
Forbidden. No scheme of rate can work: its error probability tends to , not merely away from .
Baseline. The naive fixed-length code uses bits per symbol, so the available saving is bits per symbol, a reduction.
Sanity check: the probabilities are all powers of , so a symbol code should hit exactly. Assigning , , , gives expected length — the entropy on the nose, with no block coding at all. Dyadic sources are the easy case; the theorem's asymptotics are what rescue the general one.□
4.2Achievability: Codes That Reach the Entropy
The achievability half is the typical-set code of the previous part, adapted from variable length to fixed length. The adaptation is where the error probability enters: with a fixed budget of bits and no flag bit to spend, atypical strings cannot be encoded at all, so they are declared errors.
Theorem 4.5 (Achievability). Let the source be i.i.d. with entropy , and let . Then there is a sequence of block codes of rate with . Moreover the error probability can be made to decay exponentially in .
Proof. Choose , so that . Let be the typical set. By clause (2) of the typical-set properties,
so for every there are strictly more codewords available than typical strings. Define to map the typical strings injectively onto distinct indices (possible by the count just made) and every atypical string to index ; define to invert on the image of the typical set.
Every typical string is then reconstructed exactly, so
by clause (1). This proves achievability.
For the exponential refinement, note that is the event that the average of the i.i.d. bounded variables deviates from its mean by at least . Hoeffding's inequality bounds this probability by , where is the range of ; hence decays exponentially in , at a rate controlled by .∎
Corollary 4.6 (The infimum of achievable rates is at most the entropy). Every is achievable, so .
Intuition. You do not need a codeword for every string, only for the strings that actually show up. Reserve one index for "something weird happened" and spend the rest of the codebook on ordinary strings.
Since there are only about ordinary strings, a codebook of entries with is roomy — exponentially roomy, which is why the failure probability collapses so fast.
Example 4.7 (Sizing a codebook). A source has bits/symbol on an eight-letter alphabet. For and , how many typical strings are there, how many codewords, and how much slack is there?
Solution. With , the typical set has at most members.
The codebook has entries.
The slack is a factor of : the codebook is a quadrillion times larger than it needs to be.
Sanity check: compare with the raw alternative. A fixed-length code with no modelling needs bits per symbol, i.e. codewords. The typical-set code uses , saving bits per block — precisely . The saving comes from the gap between and , which is the source's redundancy.□
Pitfall (Achievability does not make the code practical). The proof exhibits a code by listing a set of size . It says nothing about computing without that list. Every practical coder in this chapter — Huffman, arithmetic, Lempel–Ziv — exists because the achievability proof is useless as an implementation, and each attains the same asymptotic rate with resources that fit in a machine.
4.3The Converse: Why Entropy Cannot Be Beaten
The converse says that if you insist on a rate below , the decoder must fail, and fail almost always. It is proved by counting: a codebook of entries cannot address typical strings when .
Lemma 4.8 (Fano's inequality). Let be a random variable on a finite set , let be any other random variable, and let be an estimate of from . Put . Then
where is the binary entropy. In particular
Proof. Let be the error indicator. Expand by the chain rule in two ways:
Here , because is a function of , so knowing and determines . Also , since conditioning cannot increase entropy. Finally
because given we have exactly (zero entropy), while given the variable ranges over at most values, whose entropy is at most . Combining the three bounds with the chain-rule identity gives the inequality; the weaker form follows from and .∎
Fano's inequality is the formal version of "if uncertainty about remains after seeing , any guess must sometimes be wrong". It is the standard engine of converses throughout information theory; here we use a sharper, purely combinatorial argument that yields rather than merely .
Theorem 4.9 (Converse to the source coding theorem). Let the source be i.i.d. with entropy , and let . Then every sequence of block codes of rate satisfies .
Proof. Fix such a sequence and let
be the set of strings the code reconstructs correctly. Since is a function of an index taking at most values, and distinct elements of must receive distinct indices, we have the crucial count
Now choose with and split the success probability across the typical set:
For the first term, every typical string has , so
Since , this tends to exponentially fast. The second term is at most , which tends to by the AEP. Hence , i.e. .∎
Corollary 4.10 (Entropy is exactly the compression limit). Combining achievability and the converse, the infimum of achievable rates for an i.i.d. source equals ; for a stationary ergodic source it equals the entropy rate .
Intuition. A codebook with entries has pigeonholes. There are typical strings — the ones that actually arrive. If , almost every arriving string shares its pigeonhole with others, and the decoder, seeing only the pigeonhole, cannot tell which one was sent.
The error tends to rather than to some middling value because the mismatch is exponential: the shortfall is a factor , so the fraction of strings with a private pigeonhole is exponentially small.
Example 4.11 (Auditing a compression claim). A vendor claims a lossless compressor that maps every -bit file from a fair-coin source to at most bits. Refute it, and quantify how often it must fail.
Solution. For a fair coin bit/symbol, so the claimed rate is .
Counting. Outputs have length at most , so there are at most distinct outputs against equally likely inputs. At most inputs can be recovered, a fraction
Failure rate. The failure probability is therefore at least , indistinguishable from certainty.
Sanity check against the theorem. The converse predicts a success probability of at most plus the atypical term, and with and that is about — matching the direct count. Note also that the claim is refuted without the AEP: for a fair coin every string is typical, and plain pigeonhole suffices.□
Pitfall (Compressing one file is not compressing a source). It is entirely possible to map one particular -bit file to bits. What is impossible is to do so for all of them at once: any injective map into shorter strings must lengthen at least as many files as it shortens. Claims of universal compression always trade on this confusion between a single input and a distribution over inputs.
4.4Lossless and Lossy Compression
Definition 4.12 (Lossless and lossy compression). A compression scheme is a pair of maps . It is lossless on a set of inputs if for every — the encoder is injective on and the decoder inverts it. It is lossy if the reconstruction is allowed to differ from the input, the discrepancy being measured by a distortion function whose expectation is held below a budget .
Lossless compression (gzip, PNG, FLAC, ZIP) is required for text, executables and scientific data, where a single flipped bit is a defect. Lossy compression (JPEG, MP3, H.264, Opus) discards information judged perceptually irrelevant and thereby escapes the entropy bound entirely — at the price of an irreversible change to the data.
The distinction is not a matter of degree: it is the difference between an injective map and a non-injective one. And injectivity alone forbids the thing amateurs most often claim.
Theorem 4.13 (No lossless code compresses everything). Let be any injective map from binary strings to binary strings. Then for every and every , the fraction of strings of length with is less than .
In particular no lossless compressor can shorten even half of the -bit inputs by as much as bits, and any compressor that shortens some inputs must lengthen others.
Proof. The strings of length at most number
Because is injective, distinct inputs of length receive distinct outputs, so at most of the inputs can have an output that short. The fraction is therefore less than .
For the final claim, take : the number of strings of length is , so at least one string of length must map to an output of length . Iterating over all shows that a compressor that strictly shortens some inputs strictly lengthens others.∎
Intuition. Lossless compression is vacuum-packing: the suitcase shrinks, and everything is still inside when you open it. Lossy compression is deciding which souvenirs to leave behind — the case shrinks much more, and the decision is permanent.
The no-free-lunch theorem is just the observation that you cannot put distinct objects into fewer than distinct boxes. Compressors "work" because real files are not uniformly distributed over all bit strings; they are concentrated on a typical set.
Example 4.14 (Quantifying the no-free-lunch bound). Of all -bit files, what fraction can a lossless compressor possibly shrink to bits or fewer? To bits or fewer?
Solution. Apply the theorem with .
For : the fraction is less than .
For : the fraction is less than .
Sanity check: the numbers are consistent with everyday experience. gzip shrinks text by 60–70% not because the theorem is false but because text files are a vanishingly small, highly structured subset of all bit strings — exactly the typical set of a low-entropy source. Feed gzip the output of a good random number generator and the file grows by a few bytes, as the theorem requires.□
Remark (The lossy analogue). For lossy compression the entropy bound is replaced by the rate–distortion function , the minimum over all conditional distributions meeting . It satisfies for discrete sources, so lossless compression is the endpoint of the lossy theory. Rate–distortion theory is developed in its own chapter; here we only note that all rates below are purchased with distortion.
4.5Redundancy, Models, and the Cost of Being Wrong
Every compressor is a probability model in disguise. Given a model over strings, the ideal codelength for is bits; given a coder, the lengths it produces define an implicit model . Compression performance is therefore entirely a question of how close the model is to the truth, and information theory measures that distance exactly.
Definition 4.15 (Redundancy). For a source with entropy coded at expected length , the absolute redundancy is bits per symbol and the relative redundancy is . For a fixed-length code over the redundancy relative to the naive baseline is , the part of each symbol that a perfect model would have predicted.
Definition 4.16 (Relative entropy). The relative entropy (Kullback–Leibler divergence) between mass functions and on is
with the conventions and .
Lemma 4.17 (Gibbs' inequality). for all , with equality if and only if .
Proof. Let . Using and Jensen's inequality for the concave function ,
Hence . Jensen's inequality is strict for the strictly concave unless is constant on , and the final inequality is strict unless puts no mass outside ; both hold simultaneously exactly when .∎
Theorem 4.18 (The cost of the wrong model). Suppose a coder is designed for the model but the data are drawn from . Using the ideal codelengths , the expected length is
so the penalty for modelling as is exactly bits per symbol, and it is zero only if the model is right.
Proof. Expand the expectation and add and subtract :
Non-negativity of the second term is Gibbs' inequality.∎
This is the single most useful formula in practical compression: it says that model error is measured in bits, on the same scale as the data, and that the two contributions — the source's own entropy and the modeller's mistake — simply add.
Intuition. Redundancy is "what you already knew". In aaaaaaa the next a is predictable, so sending it explicitly wastes the bits you spend on it.
A compressor is a predictor with a bill attached: every time it is surprised it pays bits. Being surprised is unavoidable at rate ; being surprised because your model is wrong costs an extra , and you pay it on every symbol.
Example 4.19 (Paying for a mismatched model). A binary source has . A compressor assumes a fair coin, . What does it cost?
Solution. The true entropy is bits/symbol (computed earlier).
The divergence is
So the expected codelength is bits/symbol.
Sanity check: a coder built for a fair coin spends exactly bit on every symbol regardless of what it sees, so its expected length is exactly — matching the theorem to the digit. The mismatched model throws away the entire bits per symbol of available compression.□
Example 4.20 (Redundancy of a source with memory). A binary source alternates deterministically: of length . What is its entropy rate, and how many bits does an ideal description need?
Solution. Conditioned on the previous symbol the next one is certain, so and the entropy rate is .
An explicit description needs only the starting symbol ( bit) and the length ( bits): about bits in total.
The per-symbol rate is bits, which tends to as the string lengthens.
Sanity check: a memoryless model of this source would see and report a marginal entropy of bit per symbol, demanding bits — a factor of worse. The gap is exactly the redundancy that the first-order model captures and the zeroth-order model misses, and it is why "entropy rate, not marginal entropy" is the operative phrase.□
Pitfall (Redundancy is relative to a model class). There is no model-free measure of how compressible a particular file is (that is the province of Kolmogorov complexity, which is uncomputable). A file with zero redundancy under a memoryless model may be extremely redundant under a Markov model — the digits of pass every statistical test a compressor applies and are nonetheless generated by a short program.
4.6Prefix Codes, Kraft's Inequality and the Entropy Bound
The theory so far speaks of blocks of length and codebooks of astronomical size. Real compressors read a file once, symbol by symbol, and emit bits as they go. This part makes the transition: from block codes to symbol codes, where the combinatorial constraint is not a pigeonhole count but Kraft's inequality, and where the asymptotic bound is replaced by the sharp finite bound .
We now leave block codes behind. A symbol code assigns a binary string to each letter and codes a message by concatenation. The whole theory of such codes rests on one inequality.
Definition 4.21 (Symbol codes: non-singular, uniquely decodable, prefix). A symbol code is a map ; the string is the codeword of and its length. The code is
- non-singular if ;
- uniquely decodable if its extension to strings, , is non-singular — no two distinct messages have the same concatenation;
- prefix-free (or instantaneous) if no codeword is a prefix of another.
Every prefix code is uniquely decodable, and every uniquely decodable code is non-singular; both inclusions are strict.
Prefix codes are the ones worth building: they can be decoded left to right with no lookahead, each codeword being recognised the moment its last bit arrives. Geometrically, a prefix code is a set of leaves in a binary tree, one leaf per symbol, and no leaf on the path to another.
Theorem 4.22 (Kraft's inequality). If a binary prefix code has codeword lengths , then
Conversely, given positive integers satisfying this inequality, there exists a binary prefix code with exactly those lengths.
Proof. Necessity. Associate with each codeword of length the dyadic interval
where is the binary fraction whose digits are the bits of . The interval has length exactly . If is not a prefix of and is not a prefix of , then the two binary expansions differ at some position before both end, and : the intervals of a prefix code are pairwise disjoint. Being disjoint subintervals of , their total length is at most , which is the inequality.
Sufficiency. Order the lengths and define the cumulative sums
taking . Let be the first bits of the binary expansion of , so that — this is legitimate because is a multiple of , each earlier term with being such a multiple. The Kraft sum being at most guarantees , so all these intervals fit inside , and by construction they are consecutive and disjoint. Disjointness of and forces neither codeword to be a prefix of the other, since a prefix relation would make one interval contain the other. Hence is a prefix code with the prescribed lengths.∎
Theorem 4.23 (Kraft–McMillan: unique decodability buys nothing). Every uniquely decodable code satisfies .
Consequently the set of achievable length vectors is the same for uniquely decodable codes as for prefix codes: nothing is lost by insisting on instantaneous decoding.
Proof. Let and let . For any integer , expand the -th power:
where is the number of source strings of length whose concatenated encoding has exactly bits. Unique decodability means distinct length- strings give distinct binary strings, so is at most the number of binary strings of length , namely . Therefore
Thus for every . Since as , we conclude .∎
That -th power trick is due to Karush, and it is the reason the rest of the chapter can talk about prefix codes without loss of generality. Kraft's inequality now converts the coding problem into a constrained optimisation: choose lengths minimising subject to . Relaxing to real numbers, the solution is immediate.
Theorem 4.24 (Entropy is a lower bound on expected length). For any uniquely decodable binary code for a source with mass function , the expected codeword length satisfies
with equality if and only if for every — that is, if and only if all probabilities are dyadic (integer powers of ).
Proof. By Kraft–McMillan, . Define the probability mass function . Then
Both terms are non-negative: the first by Gibbs' inequality, the second because . Hence . Equality requires and , i.e. and , which is exactly .∎
Definition 4.25 (Shannon code). The Shannon code for assigns to symbol the length
Theorem 4.26 (The fundamental bound ). The Shannon lengths satisfy Kraft's inequality, so a prefix code with those lengths exists, and its expected length obeys
Hence the optimal expected length of any prefix code satisfies the same bounds.
Proof. Kraft. Since , we have , so . By the converse half of Kraft's inequality a prefix code with these lengths exists.
Upper bound. Since ,
Lower bound. Immediate from Theorem Entropy is a lower bound on expected length, since the Shannon code is a prefix code.
Finally, the optimal code has because the Shannon code is one candidate, and because Theorem Entropy is a lower bound on expected length applies to every uniquely decodable code.∎
Corollary 4.27 (Blocking removes the overhead). Apply an optimal prefix code to blocks of i.i.d. symbols. Writing for the optimal expected length per block,
so the per-symbol length converges to the entropy. For a stationary source the same argument with in place of gives .
Proof. The block is a single random variable over the alphabet with entropy by independence. Applying the theorem to it gives ; dividing by gives the claim. In the stationary case divide by and use the definition of the entropy rate.∎
Intuition. Kraft's inequality is a budget. Every codeword of length costs of a total budget of : short codewords are expensive, long ones cheap. Spending the whole budget optimally means buying a codeword of length for symbol — the more likely the symbol, the more you are willing to pay for a short name.
The " " in is the rounding loss: codeword lengths are integers, but generally is not. Coding blocks of symbols amortises one rounding error over symbols, which is why the overhead is .
Example 4.28 (Kraft: which length vectors are legal?). Decide whether a binary prefix code exists with lengths (a) , (b) , (c) .
Solution. (a) . Legal, and the budget is exactly exhausted — the code is complete (its tree has no unused leaves). Example: .
(b) . Illegal: no prefix code, and by Kraft–McMillan not even a uniquely decodable one.
(c) . Illegal — with -bit codewords there are only leaves available for symbols.
Sanity check: in (c), replacing one length by gives , still illegal; lengths give , legal. The budget interpretation predicts exactly this: five symbols need at least bits in the worst case.□
Example 4.30 (Shannon code and its overhead). Build the Shannon code for and compare to .
Solution. Compute and round up:
| symbol | |||
|---|---|---|---|
Kraft: ✓, so the code exists; e.g. , , , .
Expected length: bits.
Entropy: bits.
Sanity check: ✓ — the bound holds, though with bits of slack. The Kraft sum is well under , which signals waste: the code is incomplete, so some codeword could be shortened. Huffman, in the next part, will find for this same distribution, and no prefix code does better.□
Pitfall ( does not mean "within one bit of optimal"). The bound compares to the entropy, not to the best code. A code can satisfy and still be beaten by another code, as the example above shows ( versus Huffman's ). Only the Huffman code is guaranteed to be optimal, and even it can sit almost a full bit above when one symbol is very probable.
- Reading the theorem as a statement about single messages. It is asymptotic in block length and probabilistic in the source. Individual short messages can beat or fall far short of it.
- Confusing the source coding theorem with the channel coding theorem. Source coding removes redundancy to approach ; channel coding adds redundancy to approach capacity. They are dual, not the same.
- **Using for a source with memory.** The limit is the entropy *rate* , which can be far below the marginal entropy: English has a marginal letter entropy above bits but an entropy rate near bits.
- Forgetting the vanishing-error qualifier in the achievability half. Fixed-rate codes below must sometimes fail; the theorem promises only that the failure probability tends to zero.
- Believing the converse follows from Fano's inequality alone. Fano gives bounded away from zero; the exponential counting argument is what gives .
- Assuming a smarter codebook could beat the count. The converse quantifies over *all* functions , computable or not. There is no algorithmic escape from a pigeonhole.
- Expecting a compressor to shrink random or already-compressed data. The no-free-lunch theorem forbids it; the output of gzip run twice is slightly larger than run once.
- Confusing non-singular with uniquely decodable. is non-singular but not uniquely decodable: `01` could be one symbol or two.
- Believing unique decodability allows shorter codes than the prefix property. Kraft–McMillan says the achievable length vectors are identical; instantaneous decoding is free.
- Reading Kraft's inequality as a statement about a particular code. It constrains the *multiset of lengths*. Any length vector satisfying it can be realised, and no code can violate it.
- Ignoring model cost for small files. The penalty assumes a known model; if the model must be transmitted, its description length is charged to the file, which is why compression shines on large inputs.
- **Comparing against instead of . ** The naive baseline measures the saving; the entropy measures how much saving was left on the table.