Exercise: information, entropy and entropy codes
Before this unit: Day 7: Wavelets.
See also: Day 3: Bit depth and noise; Day 46: Colour; Day 18: Moments.
Goal
By the end of this exercise you should be able to:
- compute the information of an outcome and the entropy of a histogram by hand,
- say what entropy measures and what it ignores (neighbours),
- run-length encode a binary row,
- build a Huffman code by hand, check that it is prefix-free, and compare its average length with the entropy,
- explain why a Huffman code needs at least one bit per symbol and how arithmetic coding gets around that.
Do the pen-and-paper part first, then the demo. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.
Background
| Idea | What it means |
|---|---|
| Information | I = -\log_2 p bits for an outcome of probability p |
| Entropy | H = -\sum_k p_k \log_2 p_k, the average information per symbol |
| Bounds | 0 \le H \le \log_2 K for K symbols; flat histogram: \log_2 K; constant: 0 |
| Shannon | no lossless code of independent symbols averages fewer than H bits per symbol |
| Fixed-length code | \lceil \log_2 K \rceil bits per symbol |
| Run-length coding | runs of equal values as (value, length) |
| Huffman | merge the two least probable trees until one is left; 0/1 on the branches |
| Prefix-free | no code word is the beginning of another: decoding needs no separators |
| Average length | \bar L = \sum_k p_k L_k; Huffman: H \le \bar L < H + 1 |
| Arithmetic coding | the message narrows [0, 1) to width \prod p: about \sum I bits in total |
Useful values: \log_2 3 = 1.585, \log_2 5 = 2.322, \log_2 10 = 3.322.
By hand
B1. How many bits of information are in: (a) heads of a fair coin, (b) a six on a fair die, (c) one grey level drawn from 256 equally likely ones, (d) a background pixel that is white with probability 0.9, (e) the rare case that it is not white? Which of (d) and (e) should get the shorter code word?
B2. A source has five symbols A–E with p = (0.4, 0.2, 0.2, 0.1, 0.1). (a) Compute H. (b) How many bits per symbol does a fixed-length code need?
B3. Build a Huffman code for the source of B2. When two trees have the same probability, take the one that was created first (leaves before merged trees). (a) Draw the tree, write the code word of each symbol and check that the code is prefix-free. (b) Compute \bar L and compare with H and the fixed-length code. (c) Encode the message CAD and decode the bit string 0011100 (with your code).
B4. Build the Huffman tree of B2 again, but now among equal probabilities take the tree created last. (a) Give the code lengths and \bar L. (b) Both codes are optimal. Which one has the larger spread of code lengths? For the 16-symbol message CCADACAACDAAABAB, how many bits does each code need?
B5. Run-length encode the binary row 0000000111100000 as (value, run) pairs and as plain run lengths starting with a run of zeros. What happens to the row 0101010101010101?
B6. A 4 × 4 image has the rows 10 10 20 20, 10 10 20 20, 30 30 40 40, 30 30 40 40. (a) Compute the entropy of its grey-level histogram. (b) Now shuffle the 16 pixels randomly. What is the entropy of the shuffled image? Which of the two images is easier to describe in words, and why does H not show it?
B7. A binary mask is 95% background (0) and 5% object (1). (a) Compute H and the average Huffman code length per pixel. Why can Huffman not do better? (b) Suggest two ways to get below 1 bit per pixel.
B8. Arithmetic coding with p(A) = 0.6, p(B) = 0.3, p(C) = 0.1 (in this order on [0, 1)). Narrow the interval for the message AAB step by step. How wide is the final interval, and about how many bits are needed? Compare with a Huffman code for the same three symbols.
B1. (a) -\log_2 \tfrac12 = 1 bit. (b) \log_2 6 = 2.585 bits. (c) \log_2 256 = 8 bits. (d) -\log_2 0.9 = 0.152 bits. (e) -\log_2 0.1 = 3.32 bits. The common outcome (d) should get the short code word: it carries little information.
B2. (a) H = 0.4 \cdot 1.322 + 2 \cdot 0.2 \cdot 2.322 + 2 \cdot 0.1 \cdot 3.322 = 0.529 + 0.929 + 0.664 = 2.122 bits. (b) 5 symbols need \lceil \log_2 5 \rceil = 3 bits.
B3. (a) Merge D + E (0.2). Now B, C and DE all have 0.2: take B and C (created first): BC (0.4). Now DE (0.2) is the smallest, then A and BC tie at 0.4: take A (a leaf, created first): A–DE (0.6). Finally BC + A–DE (1.0). With 0 for the first tree taken in each merge: B = 00, C = 01, D = 100, E = 101, A = 11. No code word begins another one: prefix-free. (b) \bar L = 0.4 \cdot 2 + 0.2 \cdot 2 + 0.2 \cdot 2 + 0.1 \cdot 3 + 0.1 \cdot 3 = 2.2 bits: H = 2.122 \le 2.2 < 3. (c) CAD → 01 11 100 = 0111100. 0011100 → 00 B, 11 A, 100 D: BAD. (A different 0/1 assignment gives different code words but the same lengths; that is fine.)
B4. (a) After D + E, take the newest tree DE together with C (newer than B): CDE (0.4). Then B (0.2) with the newest 0.4-tree, CDE: BCDE (0.6). Then A + BCDE. Lengths A 1, B 2, C 3, D 4, E 4; \bar L = 0.4 + 0.4 + 0.6 + 0.4 + 0.4 = 2.2 bits, the same. (b) The second code has the larger spread (lengths 1 to 4; variance of the length 1.36 against 0.16). The message has 8 A, 2 B, 4 C, 2 D: the first code needs 8 \cdot 2 + 2 \cdot 2 + 4 \cdot 2 + 2 \cdot 3 = 34 bits, the second 8 \cdot 1 + 2 \cdot 2 + 4 \cdot 3 + 2 \cdot 4 = 32 bits. On average over many messages they are equal; on one message either can win.
B5. (0, 7) (1, 4) (0, 5), or run lengths 7 4 5: three numbers instead of 16 bits. The alternating row has 16 runs of length 1: 16 numbers, more than the 16 bits of the row itself. RLE helps only when runs are long.
B6. (a) Four grey levels, 4 pixels each: H = \log_2 4 = 2 bits/pixel. (b) Still 2 bits: shuffling does not change the histogram. The original is “four 2 × 2 squares”, a very short description; the shuffled image has no such structure. H of the histogram treats the pixels as independent and does not see the neighbours.
B7. (a) H = -0.95 \log_2 0.95 - 0.05 \log_2 0.05 = 0.070 + 0.216 = 0.286 bits. Huffman gives the two symbols the code words 0 and 1: \bar L = 1 bit, 3.5 times H. A Huffman code gives every symbol a whole number of bits, at least 1. (b) Run-length coding (code the lengths of the long background runs), coding blocks of several pixels as one symbol (e.g. 4 pixels: 16 symbols, and the all-background block gets a short code), or arithmetic coding, which spends -\log_2 0.95 = 0.074 bits on a background pixel.
B8. Start [0, 1): A = [0, 0.6), B = [0.6, 0.9), C = [0.9, 1). After A: [0, 0.6). After A again: [0, 0.36). After B: the B part of [0, 0.36) is [0.216, 0.324), width 0.108 = 0.6 \cdot 0.6 \cdot 0.3. About -\log_2 0.108 = 3.21 bits = 2 \cdot 0.737 + 1.737 (the information of the three symbols). A Huffman code for p = (0.6, 0.3, 0.1) has lengths 1, 2, 2: AAB costs 1 + 1 + 2 = 4 bits. (Over long messages Huffman averages 1.4 bits per symbol here, arithmetic coding approaches H = 1.295.)
Math questions
B9. (math) Show that H \le \log_2 K for a histogram of K symbols, with equality only for the flat histogram. (Hint: Jensen’s inequality for the concave \log, or Gibbs’ inequality with q_k = 1/K.)
B10. (math) (a) Prove the Kraft inequality \sum_k 2^{-L_k} \le 1 for the code word lengths of a prefix code. (b) Using Gibbs’ inequality -\sum_k p_k \log_2 q_k \ge -\sum_k p_k \log_2 p_k, show that every prefix code has \bar L \ge H.
B11. (math) Show that the lengths L_k = \lceil -\log_2 p_k \rceil satisfy the Kraft inequality, and that their average is below H + 1. Why does this prove \bar L < H + 1 for the Huffman code?
B12. (math) When is \bar L = H for a Huffman code? Show that it happens for p = (\tfrac12, \tfrac14, \tfrac18, \tfrac1{16}, \tfrac1{16}).
B9. H = \sum_k p_k \log_2 \frac{1}{p_k} \le \log_2 \sum_k p_k \frac{1}{p_k} = \log_2 K by Jensen (the sum runs over the K symbols with p_k > 0, at most K of them). Equality in Jensen needs 1/p_k constant, i.e. the flat histogram. With Gibbs: H \le -\sum_k p_k \log_2 \frac1K = \log_2 K, equality iff p = q.
B10. (a) Let L = \max_k L_k. A code word of length L_k is the start of exactly 2^{L - L_k} of the 2^L binary words of length L. For a prefix code these sets are disjoint (if two overlapped, one code word would start the other), so \sum_k 2^{L - L_k} \le 2^L. (b) Let S = \sum_j 2^{-L_j} \le 1 and q_k = 2^{-L_k}/S. Then \bar L = \sum_k p_k L_k = -\sum_k p_k \log_2 (q_k S) = -\sum_k p_k \log_2 q_k - \log_2 S \ge H - \log_2 S \ge H.
B11. L_k \ge -\log_2 p_k gives 2^{-L_k} \le p_k, so \sum_k 2^{-L_k} \le \sum_k p_k = 1: a prefix code with these lengths exists. L_k < -\log_2 p_k + 1, so \sum_k p_k L_k < H + 1. The Huffman code has the smallest average length of all prefix codes, so its \bar L is at most that of this code, hence < H + 1.
B12. By B10 equality needs S = 1 and q_k = p_k, i.e. p_k = 2^{-L_k}: every probability a power of \tfrac12 (dyadic). For p = (\tfrac12, \tfrac14, \tfrac18, \tfrac1{16}, \tfrac1{16}) Huffman merges the two sixteenths, then \tfrac18 with \tfrac18, and so on: lengths 1, 2, 3, 4, 4 = -\log_2 p_k, and \bar L = \tfrac12 + \tfrac12 + \tfrac38 + \tfrac14 + \tfrac14 = 1.875 = H.
Explore: build a Huffman code
The demo shows a histogram of up to 12 symbols (drag a bar to change its count; + and − add or remove a symbol), the Huffman tree, the code table with p, the information -\log_2 p, the code word and its length, and bars comparing the entropy H, the Huffman average length \bar L and the fixed-length code. next merge adds one merge: the two lightest trees (green, dashed) become one (orange). build all finishes the tree, restart removes all merges. ties chooses which tree is taken first among equal counts. Below, a 16-symbol message drawn from the histogram is encoded with the code (code words in alternating colours) and decoded by walking the tree; new message draws another one.
E1. Preset worked example (counts 8, 4, 4, 2, 2). Press next merge four times and compare each merge with your tree from B3. Then switch ties to newer first and compare with B4. Do the code lengths and \bar L match?
E2. Preset flat: no gain and preset dyadic: L = H. Note H, \bar L and the fixed-length code for both. Why is there nothing to gain in the first, and why is \bar L exactly H in the second?
E3. Preset one dominant symbol and preset binary mask. Note H and \bar L. How far is \bar L above H in each case? Relate it to B7.
E4. Preset prediction residuals: the histogram of the differences between neighbouring pixels of a smooth image (next unit), and preset cell grey levels: the grey levels of the cell micrograph in 12 bins. Compare H, \bar L and the fixed length for the two. Then try both tie rules on the residuals: what changes, and what does not?
E5. Start from worked example, remove one symbol with − and drag the bars to make counts 8, 4, 2, 2. Predict H and the code lengths before you look. Then make a two-symbol histogram where H is about 0.5 bits: what is \bar L?
E6. Back to worked example with older first. Read the 16-symbol message and its bit count. Count the symbols in the message and check the bit count with the code table. Switch to newer first: why does the same message now need a different number of bits although \bar L is the same?
E1. Older first: D + E (4), B + C (8), DE + A (12), then the root (20); lengths 2, 2, 2, 3, 3, \bar L = 2.200. Newer first: D + E, then C with DE (8), then B with CDE (12), then A: lengths 1, 2, 3, 4, 4, also \bar L = 2.200. Both match B3 and B4 (H = 2.122, fixed 3 bits).
E2. Flat (8 symbols of count 5): H = \bar L = 3 = fixed length. Every symbol is equally likely, so no symbol deserves a shorter word. Dyadic (16, 8, 4, 2, 2, i.e. p = \tfrac12, \tfrac14, \tfrac18, \tfrac1{16}, \tfrac1{16}): H = \bar L = 1.875 bits against 3 fixed: every -\log_2 p is a whole number, and Huffman uses exactly those lengths (B12).
E3. One dominant symbol (p = 0.9, 0.05, 0.025, 0.025): H = 0.619, \bar L = 1.150, 0.53 bits above H (almost twice H). Binary mask (47 : 3, p = 0.94): H = 0.327, \bar L = 1, three times H. In both a single symbol has p \gg 0.5 but cannot get a code word shorter than 1 bit. This is the gap of B7; run lengths or arithmetic coding close it.
E4. Residuals: H = 3.237, \bar L = 3.288, fixed 4 bits. Cell grey levels: H = 3.279, \bar L = 3.323, fixed 4. Both are close to H (within 0.05 bits): with many symbols and no very large p, Huffman is nearly ideal. With the other tie rule the residual code lengths change (e.g. the 0 residual gets 2 bits instead of 3 and the extreme ones 6 instead of 5), but \bar L stays 3.288. (Remember the residuals here are only the central part of the histogram; the next unit computes the full entropy of the residuals.)
E5. p = (0.5, 0.25, 0.125, 0.125) is dyadic: H = \bar L = 1.75, lengths 1, 2, 3, 3. A two-symbol histogram always gets \bar L = 1; H \approx 0.5 for p \approx 0.89 : 0.11 (e.g. counts 9 : 1 give H = 0.469, counts 8 : 1 give 0.503). One bit per symbol is twice the entropy.
E6. The message is CCADACAACDAAABAB with 34 bits (fixed code: 48): it has 8 A, 2 B, 4 C, 2 D, so 8 \cdot 2 + 2 \cdot 2 + 4 \cdot 2 + 2 \cdot 3 = 34. With newer first the same message needs 32 bits (8 \cdot 1 + 2 \cdot 2 + 4 \cdot 3 + 2 \cdot 4). \bar L is an average over the probabilities; this message has more A (8 of 16 = 0.5 instead of 0.4) and no E, and the second code favours A. (B4 again.)
Code
Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in compression/src/entropy/exercise.rs.
C1. histogram(img): how many pixels have each of the 256 grey levels (the grey value v in [0, 1] is level \operatorname{round}(255\,v)).
C2. entropy(counts): the entropy of a histogram in bits per symbol:
total = sum of all counts
H = 0
for every count c > 0:
p = c / total
H = H − p · log2(p)
The checks are your answers to B2, B6(a) and B7(a).
C3. huffman_lengths(counts): the code word length of every symbol. You never need the shape of the tree, only which symbols are in each tree:
trees = one tree (count, its symbol) for every symbol with count > 0
while more than one tree is left:
take out the tree with the smallest count # ties: the one created first
take out the next smallest tree
add 1 to the length of every symbol in the two
put back one tree: (the summed count, all their symbols)
The checks are B3 (lengths 2, 2, 2, 3, 3 and \bar L = 2.2) and B12, and that \sum_k 2^{-L_k} = 1 (a Huffman tree is full).
C4. run_lengths(row): the run lengths of a binary row, starting with a run of zeros. The check is B5.
C5. arithmetic_interval(p, message): the interval that a message narrows [0, 1) to:
low = 0, width = 1
for every symbol s of the message:
low = low + width · (p[0] + ... + p[s−1])
width = width · p[s]
the interval is [low, low + width)
The check is B8.
Then cargo run -p compression -- entropy and open the pictures in out/entropy/. The program prints the entropy and the Huffman code of the micrograph and of the same pixels shuffled (cell-shuffled.png). Then it codes a binary mask of six nuclei (mask.png) in three ways: pixel by pixel, in blocks of 2 × 2 pixels, and as Huffman-coded run lengths of its rows.
C6. Compare the entropy of the micrograph with that of its shuffled copy, and the Huffman code with the 8 bits of the raw file. What does the entropy of the grey-level histogram fail to see? (B6.)
C7. For the mask, compare H with the three codes. One of them goes far below H. How can it, when H is a lower bound?
The model solution is compression/src/entropy/solution.rs in the download.
C6. Both have H = 7.678 bits per pixel, and the Huffman code needs 7.702, only 0.02 bits more, against 8 bits raw: a gain of 4 %. Shuffling keeps the histogram, so it keeps H. But the micrograph is made of smooth regions and edges, and the shuffled image is noise. The entropy of the histogram treats the pixels as independent and does not see the neighbours.
C7. 4.8 % of the mask’s pixels are object: H = 0.276 bits per pixel. Huffman on single pixels needs 1.000 bit per pixel, 3.6 times H, because every code word has at least one bit (B7). Blocks of 2 × 2 pixels need 0.271 bits per pixel. The 560 run lengths of the rows, Huffman-coded, need only 0.048 bits per pixel, almost 6 times below H. H is a lower bound only for independent pixels. The pixels of a mask are not independent: a pixel is almost always equal to its neighbour, so the long runs say much more than the histogram. This is the inter-pixel redundancy that the next unit removes with prediction.
Where this leads
Entropy is the yardstick for the rest of the day: the next unit, prediction (lossless coding), turns an image into residuals whose histogram has a much smaller entropy; the DCT unit does the same with a change of basis; JPEG ends with exactly the Huffman coding built here, with run lengths of zeros. Entropy also comes back outside compression: information gain in decision trees (random forests), texture entropy (texture features), the cross-entropy loss of neural networks (backpropagation) and mutual information for aligning images with different contrast (non-rigid registration).