Source Coding and Compression - Entropy, Huffman and the Quality-Bitrate Trade-off
In questa pagina 5
The uncompressed bit-rates of audio, images and video (Digital Representation of Audio and Image SignalsAnalog-to-digital conversion has three steps, sampling at Fs at least twice the signal bandwidth after an anti-aliasing low-pass filter, uniform quantization on L = 2^b levels, and binarization of each level into b bits, giving a nominal bit-rate R = Fs times b times the number of channels (speech 64 kbit/s, CD audio 1.411 Mbit/s); an image is a two-dimensional sampled signal with 8 bits per grey level or 24 bits per RGB pixel (12 in YCbCr 4:2:0), and quality is measured with MSE and PSNR.Digital Representation of Audio and Image Signals →) are too high for networks and memories. Source coding reduces the number of bits. Two kinds exist:
- lossless (without loss): from the coded bits the original sequence is rebuilt exactly (zip, PNG);
- lossy (with loss): exactness is given up to reach a lower rate (MP3, JPEG).
The first part of this note studies the lossless case and its theoretical limit, the entropy; the second discusses lossy compression and the quality-bitrate trade-off. Compression is not channel coding: channel coding adds controlled redundancy to protect against errors (Network Key Performance IndicatorsA network is a stack of layers; the packet of one layer is the payload of the layer below, with efficiency eta = |SDU|/|PDU|; the key indicators are bit-rate R0 >= throughput S >= goodput, nodal delay d = d_proc + d_queue + d_trans + d_prop with d_trans = L/R and d_prop = x/c, jitter (delay variability), the bandwidth-delay product BDP = S times RTT, and reliability (packet error rate PER = 1 - (1 - eps)^L on a binary symmetric channel, loss rate and delivery ratio), measurable with ping.Network Key Performance Indicators →), source coding removes redundancy.
1. Information and entropy
Information theory (Shannon, 1948) quantifies the information of a source. A source emits an event (a symbol) from a set , the alphabet, with probability . One looks for a function , the information of the event, with four reasonable properties:
- ;
- (a certain event gives no information);
- if then (the rarer, the more informative);
- if and are independent.
The function must be positive, zero at 1, decreasing and satisfy : the logarithm. One sets
Example: "heads" in a coin toss has and bit. An event of probability is worth bits; a certain event bits.
The entropy is the average information of the source:
It represents the degree of randomness (uncertainty) of the output; for terms with one sets .
Example (Bernoulli variable). : . The derivative gives , where bit. At the ends .
Two properties (the second follows from Jensen's inequality for concave functions):
- . If one symbol has probability 1, ; otherwise .
- if and only if the symbols are equiprobable; otherwise .
Example. Probabilities : bits, against bits for the equiprobable case.
Words of symbols, joint and conditional entropy
A source emits a sequence; one considers words of symbols in a dictionary . The joint entropy is
- If is a function of , ; otherwise .
- If and are independent, . In general .
The conditional entropy is , and if and only if and are independent: knowing does not reduce the uncertainty on .
Example (the weather forecaster). Tomorrow's weather and the forecast have joint distribution ( = sun, = rain): , , , . bits; the marginals are , , so bits and : the forecast does not reduce the uncertainty, because it is independent of the weather.
Entropy per symbol, rate and efficiency
The average entropy per symbol of a word of symbols is . If the source (or quantizer) emits symbols per second:
| Quantity | Formula | Meaning |
|---|---|---|
| nominal rate | bit/s if bits (rounded) per symbol are used, with no coding | |
| information rate | bit/s of information actually produced | |
| efficiency | how much of the "nominal" capacity is information | |
| redundancy | the part that can be saved |
Always . If symbols are not equiprobable or have memory, bits can be saved: this is source coding.
Example. A source with symbols with the probabilities above ( bits) emitting symbols per second needs bits per symbol without coding, i.e. bit/s, while the information produced is bit/s.
Example (quantizer on a Laplacian signal). Independent samples with density , mid-riser quantized with levels and : the levels have probabilities (for each sign): bits; with kHz the information rate is kbit/s, against the nominal rate kbit/s (with 3 whole bits: kbit/s).
Example (source with memory). is an unlimited sequence of independent equiprobable bits and . The alphabet of is with probabilities : bits. For there are 15 distinct sequences: the null one has probability and the other 14 have , so bits. In general for samples and the entropy per symbol tends to bit: .
2. Lossless coding: prefix codes and Shannon's theorem
The scheme is: source S/P (groups symbols into a word ) map P/S. The map must be invertible, so that and no information is lost.
The code has an alphabet of symbols (2 for a binary code); is the length of word and the average length is
Without coding . The idea: frequent words short, rare words long. The efficiency of the code is
The nominal rate after coding is (bit/s) while the information rate is .
Decodable and prefix codes
Example. Alphabet with the code : the sequence is not uniquely decodable (for example can be , or ). The receiver must be able to rebuild the sequence uniquely: the code must be uniquely decodable.
A word is a prefix of if and coincides with the first symbols of . A code is a prefix code if no word is a prefix of another.
Proposition. A prefix code is decodable: reading symbols one by one, as soon as a codeword is recognised it can be emitted (no longer word contains it at the beginning), and one restarts. The decoding is instantaneous. The converse is false: is decodable (after a 0 one waits for the next bit) but is a prefix of .
Example of a prefix code: . The sequence reads without ambiguity. Prefix codes can be built with a binary tree: each word is a leaf, the path from the root writes it (0 left, 1 right) and no word is on an internal node.
Kraft-McMillan theorem
Let be a code with an alphabet of symbols and the length of word .
- If is decodable, then
- Conversely, if there exist integers with , then a prefix code exists with alphabet and words of lengths .
Point 1 serves to exclude codes (if the sum exceeds 1 the code is not decodable); point 2 to build them. Careful: point 1 is a necessary condition, not sufficient. Counterexample: has sum but is ambiguous ( or ).
Example. For the two codes above (binary): : : not decodable; : : compatible (and it is a prefix code). Lengths for 8 words: : no decodable code exists with these lengths.
Shannon's source coding theorem
Let be a code with alphabet of cardinality for the word of entropy .
- If is decodable: .
- A decodable prefix code exists with .
The theorem gives only bounds: it does not say whether an optimal code exists or how to find it.
Proof of point 1. From Kraft's inequality . Applying the logarithm in base (decreasing: it reverses the inequality) and Jensen's inequality: Hence .
Proof of point 2. Choose the lengths . Then and : Kraft holds, so a prefix code exists with these lengths (shorter words for likelier symbols). Moreover and, averaging, .
The code is optimal (reaches the lower bound) if and only if with integer (probabilities that are powers of ): then , i.e. .
Example. Probabilities : lengths , bits: . For ( bits) the bounds are ; the lengths of point 2 () give : a prefix code exists but it is not the best (Huffman gets ).
Grouping symbols to approach the limit
If the probabilities are not powers of , the average length per symbol of a code with whole-bit words can stay far from . One encodes a word of symbols together: is per word, per symbol divide by (the margin "+1" weighs ).
Example. Memoryless binary source with , : bit/symbol. One bit per symbol gives . Coding pairs (, , , ) with Huffman gives lengths : bits/pair bit/symbol, . With triples bit/symbol, . The cost is complexity (a dictionary of words).
3. Shannon-Fano and Huffman codes
A code is optimal if it has the minimum average length among decodable codes for the same source. Two properties (binary codes):
- If is optimal and , then . Proof by contradiction: if with , swapping the two words the new average length is , and the product of the two factors (both ) is , so .
- In an optimal code there are two words of maximum length identical except for the last symbol (otherwise the last word could be shortened by dropping its last bit).
Shannon-Fano coding (top-down)
- order the symbols by decreasing probability;
- split them into two subsets (first and the rest) with total probabilities as close as possible;
- repeat the split in each subset, until one symbol per group;
- label each branch 0 (left group) or 1 (right group); the word of a symbol is the sequence of labels from the root.
Example. . Step 1: (0.57) and (0.43), minimum difference (0.14); step 2: ; (0.20) and (0.23); step 3: . Words: . Average length bits. The algorithm does not guarantee the optimum (it does if the probabilities are powers of ).
Huffman coding (bottom-up)
- order the symbols by decreasing probability;
- group the two symbols with minimum probability into a new node whose probability is the sum;
- repeat (new nodes take part as symbols) until one node (the root) remains;
- label the two branches leaving each node with and and read the words from root to leaves.
It is optimal: it has the minimum among all prefix codes and, by Kraft-McMillan, among all decodable codes (see also Huffman Codescharacter-by-character compression needs an injective variable-length code, which prefix codes guarantee; a prefix code is a binary trie with one leaf per character of cost B(T) = sum of f(c) d_T(c), the optimal trie is full with n-1 internal nodes, Huffman repeatedly merges the two lowest-frequency trees using a priority queue (2n-1 extractions, O(n log n)), and optimality follows from the greedy choice (two rarest characters are deepest sibling leaves, by exchange) and substructure B(T) = B(T') + f(x) + f(y).Huffman Codes →).
Example (same source). Merge (), then (), then (), finally (). One possible choice is (swapping the 0/1 gives an equivalent code).
Average length. Two equivalent ways: bits; or the shortcut: is the sum of the probabilities of the internal nodes (the merges): (each leaf contributes its probability as many times as the nodes it crosses towards the root, i.e. its length).
Efficiency and rate. bits, so . Without coding bits per symbol are needed (, ): with symbols/s the nominal rate falls from to bit/s, close to the information rate bit/s. The Huffman code is not unique (choices at equal probability give different trees and the 0/1 labels can be swapped), but is unique.
Complete example with eight symbols. Probabilities . Successive merges: (node ); two of the three (for instance , node ); (node ); (node ); the four nodes/symbols at : two pairs ( and ), then the root. Lengths: three symbols of at bits; those of and at bits; those of and at bits. Sum of the internal nodes: bits. With bits, (fixed length 3 bits: ).
Variable-length coding and rate. A real case (8-level quantizer, probabilities ): bits, Huffman with lengths has bits (); at kHz the rate falls from to kbit/s, almost the information rate kbit/s.
4. Lossy compression and the quality-bitrate trade-off
In lossy coding a degradation of the signal is accepted to obtain stronger compression. The input is already digitised (the ADC loss is negligible by construction). The figures to reduce: 8 bits per pixel for a grey image, 24 for RGB, 12 for YCbCr 4:2:0; speech 64 kbit/s; stereo music 1.41 Mbit/s; HD 1080p video at 50 Hz 1.244 Gbit/s. Besides the rate (bit/s or bits per pixel, bpp) and the quality (here the PSNR, see Digital Representation of Audio and Image SignalsAnalog-to-digital conversion has three steps, sampling at Fs at least twice the signal bandwidth after an anti-aliasing low-pass filter, uniform quantization on L = 2^b levels, and binarization of each level into b bits, giving a nominal bit-rate R = Fs times b times the number of channels (speech 64 kbit/s, CD audio 1.411 Mbit/s); an image is a two-dimensional sampled signal with 8 bits per grey level or 24 bits per RGB pixel (12 in YCbCr 4:2:0), and quality is measured with MSE and PSNR.Digital Representation of Audio and Image Signals →) other parameters of a compression system matter:
- complexity: memory and number of operations;
- delay: is it necessary to "accumulate" data before starting to encode?
- robustness: how much does the signal degrade if there are errors in the bitstream?
They are conflicting parameters: improving one almost always worsens one or more of the others. In particular, the quality-bitrate trade-off is explicit: more bits give less distortion, fewer bits give more distortion. The only tool to lower the rate with loss is quantization; but the samples have already been quantized in the ADC, and quantizing them again directly makes the quality degrade quickly, because in the original domain multimedia signals are not sparse: all samples (pixels, acoustic pressure values) are important. The idea is to find a sparse representation in which some coefficients "are not important" and quantizing them coarsely gives imperceptible degradation. A linear orthogonal transform achieves this for images; this is the principle of JPEG (Image Coding - DCT and JPEGQuantizing pixels directly is inefficient because they are not sparse, so JPEG applies an orthogonal linear transform on 8x8 blocks (the 2-D DCT, Y = A X A^T) that concentrates energy in few coefficients, quantizes them with a table of steps scaled by a quality factor Q, scans them in zig-zag order, codes the DC coefficient differentially and the AC coefficients as (run, category) pairs with Huffman codes; one worked block shrinks from 512 bits to 49 bits (0.766 bit/pixel) and higher Q gives more bits and higher PSNR.Image Coding - DCT and JPEG →). For audio the sparsity is perceptual: components masked by louder ones can be quantized coarsely (Digital Representation of Audio and Image SignalsAnalog-to-digital conversion has three steps, sampling at Fs at least twice the signal bandwidth after an anti-aliasing low-pass filter, uniform quantization on L = 2^b levels, and binarization of each level into b bits, giving a nominal bit-rate R = Fs times b times the number of channels (speech 64 kbit/s, CD audio 1.411 Mbit/s); an image is a two-dimensional sampled signal with 8 bits per grey level or 24 bits per RGB pixel (12 in YCbCr 4:2:0), and quality is measured with MSE and PSNR.Digital Representation of Audio and Image Signals →, perceptual coding).
Lossless coding on raw images does not reduce the size much, since grey levels are almost equiprobable; to reduce by a factor of 10 or more a loss must be accepted. The measured trade-off for an example JPEG block (more quality, more bits, less error) is in Image Coding - DCT and JPEGQuantizing pixels directly is inefficient because they are not sparse, so JPEG applies an orthogonal linear transform on 8x8 blocks (the 2-D DCT, Y = A X A^T) that concentrates energy in few coefficients, quantizes them with a table of steps scaled by a quality factor Q, scans them in zig-zag order, codes the DC coefficient differentially and the AC coefficients as (run, category) pairs with Huffman codes; one worked block shrinks from 512 bits to 49 bits (0.766 bit/pixel) and higher Q gives more bits and higher PSNR.Image Coding - DCT and JPEG →. The comparison between lossy codecs at equal bitrate and perceived quality (listening or viewing tests) is part of the program, but no certified source describes such experiments, so it is not written here.
Typical mistakes
- Believing that the entropy depends on the values of the symbols: it depends only on the probabilities. A one-to-one transformation does not change it; a non-one-to-one one (merging ) lowers it.
- Writing without checking independence.
- Confusing (maximum) with the actual entropy; computing efficiency with and not with the real word length.
- Believing that Kraft proves decodability: it only excludes or builds codes.
- Forgetting that Shannon's theorem is per word: if symbols are coded together, and is the average word length.
- Saying that a prefix code must have all words of the same length.
- In Huffman: merging the two most likely symbols instead of the two least likely; forgetting to re-sort new nodes with the remaining ones; believing the code is unique or that efficiency can exceed 1.
- Confusing average length (per word) with rate (per second): is needed.
Versione ripasso
Lossless vs lossy. Lossless: exact reconstruction (zip, PNG); lossy: exactness traded for rate (MP3, JPEG). Source coding removes redundancy; channel coding adds controlled redundancy.
Information and entropy. bits (positive, zero for a certain event, decreasing, additive for independent events). Coin: 1 bit; : 4 bits. , , maximum only if equiprobable. Bernoulli: maximum 1 bit at . Example : bits (vs ).
- Joint/conditional: ; independent ; in general ; , equal to iff independent. Forecaster: , .
- ; nominal rate , information rate , efficiency , redundancy . 5 symbols, , : 300 bit/s vs 219 bit/s. Laplacian quantizer : , kbit/s (nominal 20.7; 24 with 3 bits). : , three samples , , .
Prefix codes. ; (binary ); rate . Decodable: unique reading. Prefix: no word is the start of another; instantaneous; is decodable but not prefix. Counterexample , , , , : is ambiguous.
Kraft-McMillan. Decodable (necessary only: sums to 1 but is ambiguous). Conversely a prefix code with those lengths. Counterexample code: . Prefix : sum 1. Lengths : , impossible.
Shannon. Decodable (Kraft in the form , base- logarithm, Jensen). A prefix code exists with (lengths , Kraft holds since ). Optimal () iff . : . : bounds , point-2 lengths give , Huffman .
Grouping. Code symbols together: , the weighs . , : 1 bit/symbol ; pairs per pair per symbol, ; triples , . Cost: dictionary .
Shannon-Fano (top-down). Sort by decreasing probability; split into two groups of nearly equal total; repeat; 0/1 on branches. Not always optimal. : , then : , .
Huffman (bottom-up). Sort; merge the two least probable into a node with the sum; repeat to the root; label 0/1. Optimal among prefix codes and all decodable codes (Huffman Codescharacter-by-character compression needs an injective variable-length code, which prefix codes guarantee; a prefix code is a binary trie with one leaf per character of cost B(T) = sum of f(c) d_T(c), the optimal trie is full with n-1 internal nodes, Huffman repeatedly merges the two lowest-frequency trees using a priority queue (2n-1 extractions, O(n log n)), and optimality follows from the greedy choice (two rarest characters are deepest sibling leaves, by exchange) and substructure B(T) = B(T') + f(x) + f(y).Huffman Codes →). Same source: , , , root 1; e.g. , , , , . = sum of internal-node probabilities . (3 fixed bits: ); 100 symbols/s: 300 down to 223 bit/s vs . Not unique, but is.
- Eight symbols : lengths , , , (fixed 3 bits: ).
- Real case : , lengths , , ; at 8 kHz 24 down to 18.4 kbit/s (information rate 18.27).
Lossy compression. Parameters in conflict: rate (bit/s, bpp), quality (PSNR), complexity, delay, robustness. Only quantization lowers the rate with loss, but multimedia samples are not sparse, so re-quantizing them directly degrades quality fast; a sparse representation (orthogonal transform) allows coarse quantization of unimportant coefficients (Image Coding - DCT and JPEGQuantizing pixels directly is inefficient because they are not sparse, so JPEG applies an orthogonal linear transform on 8x8 blocks (the 2-D DCT, Y = A X A^T) that concentrates energy in few coefficients, quantizes them with a table of steps scaled by a quality factor Q, scans them in zig-zag order, codes the DC coefficient differentially and the AC coefficients as (run, category) pairs with Huffman codes; one worked block shrinks from 512 bits to 49 bits (0.766 bit/pixel) and higher Q gives more bits and higher PSNR.Image Coding - DCT and JPEG →); for audio, masked components are quantized coarsely. Lossless coding of raw images saves little (grey levels almost equiprobable). Quality-vs-rate listening and viewing experiments have no certified source and are not written.
Typical mistakes: entropy depends on probabilities, not symbol values; without independence; vs ; Kraft as proof of decodability; Shannon per symbol instead of per word; prefix = same length; Huffman merging the most likely symbols; efficiency above 1; average length vs rate.
More reminders.
- Optimal-code properties: if then (swapping lowers the average by ); the two longest words differ only in the last symbol.
- Prefix code reading: with , , , , ; a prefix code is a binary tree with words on leaves only.
- Rate bookkeeping: nominal rate after coding ; information rate ; without coding .