Information TheoryComputer Science, Applied · Book 1
0 / 0

Shelves / Information Theory

IT·04

Entropy: the Average Surprise of a Source

Shannon's entropy, H = Σ p log₂(1/p): the expected surprise of a source, measured in bits per symbol; computed for coins, dice and the binary entropy curve; why it's zero only for certainty and largest for equally likely outcomes; how it adds for independent sources and splits by grouping; redundancy; the entropy of Shakespeare's bytes, letters and words; why estimates from small samples come out too low and how to correct them; and what entropy does and doesn't promise about compression.

28 topics · ~26 min read · 12-question quiz
Updated Suggest a correction

Start here

What this chapter answers

How much information does a source produce per symbol, on average? Why is a biased coin less informative than a fair one, and by exactly how much? Why can no source with K symbols have more than log2K bits of entropy? What does it mean for English to be "redundant", and how redundant are Shakespeare's letters? And why do entropy estimates from small samples always come out too low?

Entropy in one picture

A fair coin's toss is worth 1 bit: heads and tails each carry 1 bit of surprise. A coin that lands heads 90 % of the time is different: heads carries only 0.15 bits (−log20.9), tails 3.32 bits (−log20.1). On average, weighting each by how often it happens, a toss carries 0.9×0.15+0.1×3.32≈0.47 bits. That average is the coin's entropy. It's less than 1 because most tosses are predictable: before tossing, you'd bet on heads and usually be right, so the toss tells you less.

Defining entropy

The formula

Some values, computed in the lab:

Source Probabilities Entropy
Fair coin 12,12 1 bit
Biased coin 0.9, 0.1 0.469 bits
Fair die six of 16 log26≈2.585 bits
Chapter 3's four-symbol source 12,14,18,18 1.75 bits
A certain outcome 1 0 bits
"Is it 7?" among a million 10−6, 1−10−6 0.000021 bits

The last line answers chapter 1's question about the bad question "is it 7?": its answer is "yes" with 20 bits of surprise, but so rarely that on average it's worth two hundred-thousandths of a bit.

The binary entropy function

A source with two outcomes, one of probability p, has entropy

h(p)=−plog2p−(1−p)log2(1−p).

It's 0 at p=0 and p=1 (no uncertainty), rises to its maximum of 1 bit at p=12, and is symmetric (h(p)=h(1−p): it doesn't matter which outcome is called "heads"). It comes up everywhere: chapter 6's proof of the source coding theorem, chapter 9's capacity of a noisy channel, and machine learning's loss for yes-or-no predictions.

0101.05
The binary entropy function h(p): a two-outcome source is most uncertain at p = 1/2

With three outcomes the picture is a surface; fixing the probability q of the third outcome and varying the first shows that the entropy is still largest when the probabilities are as equal as allowed:

0101.7
Entropy of three outcomes with probabilities p, q and 1 − p − q, as p varies (q = 0.2)

What entropy obeys

Never negative, zero only for certainty

Every surprise −log2p(x) is at least 0 (since p≤1), so their average is too: H≥0. It's zero only if every symbol that can occur has surprise 0, meaning probability 1: the source always produces the same symbol, and observing it tells you nothing.

Largest when everything is equally likely

So chapter 2's log2K, counting the possibilities, is the most a source can produce, and only a uniform source reaches it. Every other source carries less, and the shortfall is what compression can remove. The lab checks the theorem on 200,000 random distributions over 4 symbols: none exceeds 2 bits.

Independent sources add

If two sources are independent, the pair (X,Y) has probabilities p(x)q(y), and its entropy is

H(X,Y)=H(X)+H(Y).

That's chapter 1's additivity of surprise, averaged: −log2(p(x)q(y)) =−log2p(x)−log2q(y), and expectations add. A biased coin (0.469 bits) and a die (2.585) tossed together carry 3.054 bits. For dependent sources the sum is too much; chapter 7 makes the correction precise.

Grouping

Entropy can be computed in stages. To pick one of three outcomes with probabilities 12,13,16, first decide between "the first" and "one of the other two" (probabilities 12,12), then, half the time, between the other two (probabilities 23,13 within that group):

Interactive diagram: Grouping: entropy computed in stages. It needs JavaScript; the text around it says the same.
H(12,13,16)=h(12)+12H(23,13)≈1+12×0.918=1.459.

Shannon proved that continuity, growth with the number of equally likely outcomes, and this grouping rule together force the formula: entropy is the only measure of uncertainty with these properties (up to the choice of unit). Grouping is also how question strategies work: each question splits the possibilities into groups, and the entropy is the average total information gathered along the way.

Entropy, questions and codes

Chapter 1 asked how many yes-or-no questions it takes to find out what a source produced. Entropy is the answer on average, for the best strategy, and up to rounding:

  • No strategy, and no code, can average fewer than H questions or binary digits per symbol. (Chapter 5 proves it.)
  • A strategy can get within 1 of H for a single symbol, and within as little as you like of H by asking about long blocks of symbols at once. (Chapters 5 and 6.)

Chapter 3's four-symbol source showed it exactly: the codewords 0, 10, 110, 111 have lengths equal to the surprises 1, 2, 3, 3, so their average is the entropy, 1.75. When the probabilities are all powers of 12 a code can match the entropy exactly; otherwise it can only approach it. That's the content of the source coding theorem, the first of Shannon's two great theorems.

Redundancy

A source with K symbols could carry log2K bits per symbol. If its entropy is H, it carries less, and the fraction it "wastes" is its redundancy:

R=1−Hlog2K.

Shakespeare's letters, treated one at a time, have H=4.19 bits against log226=4.70: a redundancy of 10.8 %. That's only the redundancy visible in letter frequencies. Letters depend on their neighbours (chapter 3's "th" and "qu"), on the word, the sentence and the meaning, and when all of that is counted, English is far more redundant: Shannon estimated in 1951 that it carries about 1 bit per letter, a redundancy of around 75 %. Redundancy isn't waste in the everyday sense: it's what lets you read a smudged page or a message full of typos. Compression removes it; error correction (chapters 8 and 9) adds a designed kind back.

Entropy of real data

Bytes, letters and words

The lab measures the entropy of the plays three ways. As bytes (65 symbols: letters in both cases, punctuation, spaces and line breaks), H=4.78 bits per byte. As letters only, 4.19 bits. As words, treating each of the 11,455 different words as one symbol, 9.62 bits per word, which is 1.89 bits per character (counting a space after each word). Bigger symbols capture more structure: a word model "knows" that "q" is followed by "u" and that "the" is common, without being told. The catch is the size of the model: a word-level code must describe 11,455 words and their probabilities, a cost that comes back in chapter 6 and in the capstone.

These are all order-0 entropies: each symbol is treated as independent of the ones before. They measure how well a code could do if it used only symbol frequencies. Real compressors use context too, and chapter 7 defines the conditional entropy that measures what context is worth.

Estimating entropy from a sample

The plug-in estimate puts the observed frequencies into the formula. It's natural and consistent (it converges to the true entropy as the sample grows), but it's biased low: rare symbols are often missing from a small sample, and the frequencies of the ones that are present vary in a way that makes the sample look more predictable than the source. The lab measures it: 10 rolls of a fair die give an average estimate of 2.14 bits against the true 2.585. A simple correction from George Miller (1955) adds K−12nln2 bits for K symbols and n samples, and fixes most of the bias. For text, with a huge number of rare words, entropy estimation is a research problem in itself; chapter 10 returns to it.

Lab: entropy measured

Experiment 1: the entropy of simple sources

Python
import math
def entropy(probs):
    """Average surprise in bits; terms with p = 0 contribute nothing."""
    return sum(-p * math.log2(p) for p in probs if p > 0) + 0.0
sources = [("fair coin", [1 / 2, 1 / 2]), ("coin that lands heads 90 % of the time", [0.9, 0.1]),
           ("fair die", [1 / 6] * 6), ("A, B, C, D with 1/2, 1/4, 1/8, 1/8", [1 / 2, 1 / 4, 1 / 8, 1 / 8]),
           ("certain outcome", [1.0]), ("'is it 7?' among a million", [1e-6, 1 - 1e-6])]
for name, ps in sources:
    print(f"{name:<40} H = {entropy(ps):.6f} bits   (log2 of the number of outcomes: {math.log2(len(ps)):.3f})")
Text
fair coin                                H = 1.000000 bits   (log2 of the number of outcomes: 1.000)
coin that lands heads 90 % of the time   H = 0.468996 bits   (log2 of the number of outcomes: 1.000)
fair die                                 H = 2.584963 bits   (log2 of the number of outcomes: 2.585)
A, B, C, D with 1/2, 1/4, 1/8, 1/8       H = 1.750000 bits   (log2 of the number of outcomes: 2.000)
certain outcome                          H = 0.000000 bits   (log2 of the number of outcomes: 0.000)
'is it 7?' among a million               H = 0.000021 bits   (log2 of the number of outcomes: 1.000)

A fair coin is 1 bit and a fair die log26: uniform sources reach log2K. The biased coin carries 0.469 bits, under half of a fair one's. The four-symbol source has 1.75 bits against log24=2. The certain outcome carries nothing, and "is it 7?" carries 0.000021 bits on average. (Adding 0.0 turns a negative zero into a plain zero for the certain source.)

Experiment 2: Shakespeare by bytes, letters and words

Python
import lzma, math, re
from collections import Counter
def entropy_of_counts(counts):
    n = sum(counts.values())
    return sum(-c / n * math.log2(c / n) for c in counts.values())
raw = open("data/shakespeare.txt", "rb").read()
text = raw.decode().lower()
letters = [c for c in text if "a" <= c <= "z"]
words = re.findall(r"[a-z]+", text)
H_bytes = entropy_of_counts(Counter(raw))
print(f"bytes:   {len(set(raw)):>6} symbols, H = {H_bytes:.3f} bits per byte (log2 K = {math.log2(len(set(raw))):.3f}); lzma: {8 * len(lzma.compress(raw, preset=9)) / len(raw):.3f}")
H_letters = entropy_of_counts(Counter(letters))
print(f"letters: {26:>6} symbols, H = {H_letters:.3f} bits per letter (log2 26 = {math.log2(26):.3f}), redundancy {1 - H_letters / math.log2(26):.1%}")
Hw = entropy_of_counts(Counter(words))
avg_len = sum(len(w) for w in words) / len(words)
print(f"words:   {len(set(words)):>6} symbols, H = {Hw:.3f} bits per word = {Hw / (avg_len + 1):.3f} per character (with a space; {avg_len:.2f} letters per word)")
Text
bytes:       65 symbols, H = 4.779 bits per byte (log2 K = 6.022); lzma: 2.611
letters:     26 symbols, H = 4.194 bits per letter (log2 26 = 4.700), redundancy 10.8%
words:    11455 symbols, H = 9.620 bits per word = 1.893 per character (with a space; 4.08 letters per word)

The order-0 entropy of the plays' bytes is 4.78 bits per byte, against 6.02 for 65 equally likely bytes and the 2.61 lzma achieved: lzma beats the order-0 entropy because it uses context, which this entropy ignores. Letters alone have 10.8 % redundancy. Treating words as symbols gives 1.89 bits per character, already below lzma, but only if the 11,455-word vocabulary and its probabilities are known to both ends; and these figures leave out capitals, punctuation and line breaks, so they aren't directly comparable with lzma's whole-file number.

Experiment 3: small samples underestimate entropy

Python
import math, random
random.seed(4)
def plug_in(sample, K):
    n = len(sample)
    counts = [sample.count(k) for k in range(K)]
    return sum(-c / n * math.log2(c / n) for c in counts if c)
K, true = 6, math.log2(6)
print(f"true entropy of a fair die: {true:.4f} bits")
for n in (10, 30, 100, 1000, 10_000):
    ests = [plug_in([random.randrange(K) for _ in range(n)], K) for _ in range(400)]
    mean = sum(ests) / len(ests)
    mm = mean + (K - 1) / (2 * n * math.log(2))
    print(f"n = {n:>6}: average plug-in estimate {mean:.4f} (low by {true - mean:.4f}); with the Miller-Madow correction {mm:.4f}")
Text
true entropy of a fair die: 2.5850 bits
n =     10: average plug-in estimate 2.1447 (low by 0.4402); with the Miller-Madow correction 2.5054
n =     30: average plug-in estimate 2.4643 (low by 0.1206); with the Miller-Madow correction 2.5846
n =    100: average plug-in estimate 2.5487 (low by 0.0362); with the Miller-Madow correction 2.5848
n =   1000: average plug-in estimate 2.5810 (low by 0.0039); with the Miller-Madow correction 2.5846
n =  10000: average plug-in estimate 2.5846 (low by 0.0004); with the Miller-Madow correction 2.5850

Averaged over 400 samples at each size, the plug-in estimate is low by 0.44 bits with 10 rolls, 0.12 with 30, 0.036 with 100 and 0.0004 with 10,000: the bias shrinks roughly like 1n. Miller's correction removes almost all of it from 30 rolls on. Whenever you see an entropy measured from a small sample (a short text, a handful of passwords), expect it to be too low.

Experiment 4: the maximum, grouping and independence

Python
import math, random
H = lambda ps: sum(-p * math.log2(p) for p in ps if p > 0)
random.seed(5)
best = 0
for _ in range(200_000):
    w = [random.random() for _ in range(4)]
    best = max(best, H([x / sum(w) for x in w]))
print(f"largest entropy among 200,000 random distributions on 4 outcomes: {best:.6f} (log2 4 = 2)")
left = H([1 / 2, 1 / 3, 1 / 6])
right = H([1 / 2, 1 / 2]) + 1 / 2 * H([2 / 3, 1 / 3])
print(f"grouping: H(1/2, 1/3, 1/6) = {left:.6f};  h(1/2) + 1/2 H(2/3, 1/3) = {right:.6f}")
two = H([a * b for a in (0.9, 0.1) for b in (1 / 6,) * 6])
print(f"independent coin (0.9/0.1) and die together: {two:.6f} = {H([0.9, 0.1]):.6f} + {math.log2(6):.6f}")
Text
largest entropy among 200,000 random distributions on 4 outcomes: 1.999967 (log2 4 = 2)
grouping: H(1/2, 1/3, 1/6) = 1.459148;  h(1/2) + 1/2 H(2/3, 1/3) = 1.459148
independent coin (0.9/0.1) and die together: 3.053958 = 0.468996 + 2.584963

Of 200,000 random distributions on 4 outcomes, the most uncertain had entropy 1.99997 bits, just under the theorem's ceiling of 2, reached only by the uniform distribution. Grouping gives the same 1.459148 bits whether computed directly or in two stages. And a biased coin and a die, independent, carry 3.053958 bits together: exactly the sum of their entropies.

Worked examples

Computing entropy

The binary entropy function

Redundancy

Exercises

Practice

  1. Find the entropy of a source with probabilities 0.5, 0.25, 0.25.
  2. What's the entropy of a fair 8-sided die? Of a fair 10-sided die?
  3. A coin lands heads with probability 0.99. What's its entropy? How many tosses carry 1 bit of information on average?
  4. Which has more entropy: a fair coin, or a source with probabilities 0.4, 0.4, 0.2? Explain without computing, then compute.
  5. What's the redundancy of a source with 4 symbols and entropy 1.5 bits?
  6. Two independent sources have entropies 2.3 and 1.7 bits. What's the entropy of the pair?
  7. A sample of 20 symbols from a 26-symbol source gives a plug-in entropy of 3.9 bits. Is the true entropy likely higher or lower? Estimate Miller's correction.
Answers
  1. 0.5+2×0.25×2 =1.5 bits.
  2. 3 bits; log210≈3.32 bits.
  3. h(0.99)≈0.0808 bits; about 1/0.0808≈12.4 tosses per bit.
  4. The three-symbol source can have up to log23≈1.585 bits and its probabilities aren't extreme, so probably more: 2×0.4×1.322+0.2×2.322≈1.522 bits, more than the coin's 1.
  5. 1−1.5/2=25%.
  6. 4.0 bits.
  7. Higher: plug-in estimates are biased low. Correction 252×20×0.693≈0.90 bits, suggesting about 4.8 bits, though with 20 samples the estimate is very uncertain either way.

Harder

  1. Show that h(p)=h(1−p), and that h is largest at p=12 using the chapter's theorem.
  2. Prove that if one outcome has probability at least 1−ε, the entropy is small, by bounding it in terms of h(ε) and εlog2(K−1). (This is Fano's inequality in disguise.)
  3. A source's symbols are mapped to fewer symbols by a function (for example, a die's face to "even" or "odd"). Explain why the entropy can't increase.
  4. Use grouping to compute the entropy of the probabilities 14,14,14,18,18 in two stages.
  5. Explain why the word-level entropy of the plays (1.89 bits per character) doesn't mean a word-based compressor would beat lzma.
Answers
  1. Swapping p and 1−p swaps the two terms of the formula. A two-outcome source has H≤log22=1, with equality only for equal probabilities, so the maximum is at p=12.
  2. Group into "the likely outcome" (probability 1−δ, with δ≤ε) and "one of the other K−1" (probability δ). Grouping gives H =h(δ)+δH(others)≤h(δ)+δlog2(K−1). When δ≤ε≤12, h(δ)≤h(ε), so H≤h(ε)+εlog2(K−1): small when ε is small.
  3. Grouping: the entropy of the face equals the entropy of its parity plus the average uncertainty about the face once the parity is known, and that second part is at least 0. So the coarser description has at most the original entropy (here 1 bit against 2.585). Processing can't create information, only lose it: chapter 7's data processing inequality.
  4. Group as {14,14,14} and {18,18}, with probabilities 34 and 14: h(14)+34log23+14×1≈0.811+1.189+0.25 =2.25 bits; directly, 3×14×2+2×18×3 =1.5+0.75 =2.25.
  5. The figure assumes both ends already know the 11,455 words and their probabilities; sending that dictionary costs tens of kilobytes. It also leaves out capital letters, punctuation and line breaks. And it's measured on the same text the probabilities came from (stage 3 of the capstone met the same trap). A fair comparison counts everything the decoder needs.

Challenge

  1. Shannon estimated the entropy of English with a game: a person guesses the next letter of a text until right, and the number of guesses is recorded. Explain why the distribution of the number of guesses gives bounds on the entropy, and why this estimate depends on the person.
Discussion

If the guesser knows English well, their guesses are in order of probability: the first guess is the letter they think likeliest. The sequence of guess counts is then an encoding of the text (a reader with the same "model" could recover each letter by asking for the kth guess), so the entropy of the guess counts bounds the entropy of the text from above, and Shannon derived a lower bound from the same data. In his 1951 paper, guessers needed one guess about 80 % of the time with long contexts, giving estimates around 0.6 to 1.3 bits per letter. The estimate depends on the person because the "probabilities" are the guesser's model of English: a better reader has lower surprise. Today, large language models play the same game and achieve lower figures, which is a measure of how well they model text (chapter 11).

In real life

Misconceptions and limits

The model to keep

Common misconceptions

Misconception What's actually true Where it's shown
"Entropy measures the information in a particular message." It's the average surprise of a source; a particular message has a surprise. Defining entropy
"More symbols always means more entropy." A 1,000-symbol source with one dominant symbol can have far less entropy than a fair coin. Experiment 1
"A biased coin is half as informative if it lands heads 75 % of the time." Entropy isn't linear in the bias: h(0.75)≈0.81 bits. The binary entropy function
"English has about 4.2 bits per letter." That's letter frequencies only; with context it's around 1 bit. Redundancy
"An entropy measured from data is the source's entropy." Small samples underestimate it; 10 die rolls gave 2.14 bits instead of 2.585. Experiment 3
"Word-level entropy shows a word compressor beats lzma." Not until the vocabulary's cost and everything left out are counted. Experiment 2; harder exercise 12
"Redundancy is waste." It's what lets readers and receivers recover from errors. Redundancy
"Entropy here is the physicist's entropy." Same form, different setting; the connection is real but needs care. Why this exists

Limits and trade-offs

  • Entropy belongs to a model. "The entropy of a file" only means something relative to a model of the source that produced it: order-0 bytes, order-1, words, or a language model. A better model gives a lower entropy and a better compressor.
  • It's an average. A code that meets the entropy on average still produces long codewords for surprising messages; for worst-case guarantees (fixed-size buffers, real-time limits), averages aren't enough.
  • It assumes the probabilities are known. In practice they're estimated, at a cost: describing the model, or learning it as you go (chapter 6's universal codes, chapter 11's cross-entropy).

Revision sheet

Key ideas

  • Entropy H =∑xp(x)log21p(x): expected surprise, bits per symbol.
  • Binary entropy h(p) =−plog2p−(1−p)log2(1−p): 0 at the ends, 1 at 12, symmetric.
  • 0≤H≤log2K; H=0 only for certainty; H=log2K only for uniform.
  • Independent sources: H(X,Y)=H(X)+H(Y).
  • Grouping: decide the group, then within it; entropy adds up the stages, weighted.
  • Coding: no code averages fewer than H digits per symbol; good codes come within 1, or less with blocks.
  • Redundancy R=1−H/log2K; English letters 10.8 % on frequencies, about 75 % with context.
  • Plug-in estimates are biased low; Miller's correction adds (K−1)/(2nln2).

Glossary

  • Entropy (information): the expected surprise of a source, ∑plog21p bits per symbol; the average information it produces.
  • Binary entropy function: h(p), the entropy of a two-outcome source with probabilities p and 1−p.
  • Uniform distribution: one in which every possible value is equally likely; it has the largest entropy, log2K.
  • Grouping property: the rule that entropy can be computed in stages, first choosing a group and then a member, weighting each stage by its probability.
  • Redundancy (of a source): 1−H/log2K, the fraction of its symbols' capacity a source doesn't use.
  • Order-0 entropy: the entropy computed from symbol frequencies alone, ignoring any dependence on earlier symbols.
  • Plug-in estimate: an entropy computed by putting observed frequencies into the formula; biased low for small samples.
  • Miller–Madow correction: adding (K−1)/(2nln2) bits to a plug-in entropy estimate to reduce its bias.