Workbench / Information Theory Companion
B1·04
Entropy: the Average Surprise of a Source
Around chapter 4: how entropy ties surprise, probability, questions and codes together; three other ways to see it; what the chapter simplifies (order-0 entropy can't see order, the entropy limit needs blocks to reach, and word entropy keeps rising with more text); how SciPy's entropy function normalises, chooses its units and handles zeros and negatives; four debugging drills; and interview questions.
Understanding it better
Concept map
- Surprise (chapter 1) + expected value (chapter 3) → entropy .
- Bounds: → certainty and uniformity → redundancy .
- Additivity for independent sources → grouping → Shannon's uniqueness theorem → question strategies (chapter 1, chapter 2's trees).
- Entropy as a floor on average code length → Huffman codes within 1 bit (chapter 5) → blocks and arithmetic coding to approach it (chapter 6).
- Order-0 entropy ignores context → conditional entropy and entropy rate (chapter 7) → English at about 1 bit per letter (chapter 10).
- Wrong probabilities cost extra → cross-entropy and KL divergence (chapter 11).
- Estimation from samples → plug-in bias → Miller–Madow → rare events and heavy tails (point 3 below).
Explain it differently
Entropy as the size of a vocabulary. A source with entropy behaves, over long messages, as if it chose uniformly among about equally likely symbols per step. A 90/10 coin (0.469 bits) is like a source with about "effective" outcomes. English letters at 4.19 bits act like 18 equally likely letters, not 26. This "perplexity", , is how language models report their uncertainty.
Entropy as a betting game. A friend tosses a coin and you must guess each result. With a fair coin you're right half the time whatever you do. With the 90/10 coin you're right 90 % of the time by always saying heads. Entropy measures how much the coin resists being guessed: zero for a coin you can always guess, one bit for one you can never beat.
Entropy as a cost of description. Imagine a telegraph company charging per binary digit. If you and the company agree on the probabilities in advance, the best price per symbol you can be charged, on average, is the entropy. A source with high entropy is expensive to describe; a predictable one is cheap. Every compression format is a negotiated price list.
Gaps and misconceptions
What the chapter oversimplifies
1. "Entropy measures how predictable the data is", but order-0 entropy can't see order. Order-0 entropy depends only on how often each symbol appears, not where. Rearranging the same bytes leaves it unchanged:
import lzma, math, random
from collections import Counter
text = open("data/shakespeare.txt", "rb").read()
random.seed(14)
versions = {"the plays as written": text, "the same bytes, shuffled": bytes(random.sample(text, len(text))), "the same bytes, sorted": bytes(sorted(text))}
for name, data in versions.items():
n = len(data)
H = sum(-c / n * math.log2(c / n) for c in Counter(data).values())
print(f"{name:<26} order-0 H = {H:.3f} lzma {8 * len(lzma.compress(data, preset=9)) / n:.3f} bits per byte")
the plays as written order-0 H = 4.779 lzma 2.611 bits per byte
the same bytes, shuffled order-0 H = 4.779 lzma 4.911 bits per byte
the same bytes, sorted order-0 H = 4.779 lzma 0.004 bits per byte
All three files have exactly the same order-0 entropy, 4.779 bits per byte, because they contain the same bytes. But lzma compresses the plays to 2.61, the shuffled bytes to 4.91 (worse than order-0, since lzma looks for repeats that aren't there and doesn't build an order-0 code), and the sorted bytes to 0.004, since a sorted file is just "this many spaces, then this many of the next byte, …". Order-0 entropy is the right limit only for sources that really are independent; for everything else, it's one number from one model.
2. "A code can average close to bits per symbol", but not one symbol at a time. For a very predictable source, every symbol still needs at least one binary digit if it's coded alone:
import math
from itertools import product
p = 0.01 # a source of bits, 1 with probability 0.01
H = -p * math.log2(p) - (1 - p) * math.log2(1 - p)
print(f"entropy {H:.4f} bits per symbol")
for m in (1, 2, 4, 8, 12, 16):
# a code for blocks of m symbols, giving each block ceil(its surprise) binary digits (a Shannon code)
total = 0.0
for ones in range(m + 1):
prob = p ** ones * (1 - p) ** (m - ones)
total += math.comb(m, ones) * prob * math.ceil(-math.log2(prob))
print(f"blocks of {m:>2}: {total / m:.4f} binary digits per symbol")
entropy 0.0808 bits per symbol
blocks of 1: 1.0600 binary digits per symbol
blocks of 2: 0.5601 binary digits per symbol
blocks of 4: 0.3101 binary digits per symbol
blocks of 8: 0.1853 binary digits per symbol
blocks of 12: 0.1439 binary digits per symbol
blocks of 16: 0.1232 binary digits per symbol
A source of bits that are 1 only 1 % of the time has entropy 0.081 bits per symbol, but a code for single symbols spends at least 1 binary digit each (1.06 for the code shown, which gives each block a whole number of digits close to its surprise). Coding blocks helps: 0.56 per symbol in blocks of 2, 0.19 in blocks of 8, 0.12 in blocks of 16, closing in on 0.081 slowly, since the rounding costs under one digit per block. That's why chapter 6's arithmetic coding, which codes a whole message as one block, matters so much for predictable sources.
3. "Miller's correction fixes the bias", which holds for small alphabets, not for words. With words, the alphabet itself keeps growing as you read:
import math, re
from collections import Counter
words = re.findall(r"[a-z]+", open("data/shakespeare.txt", encoding="utf-8").read().lower())
for n in (1_000, 10_000, 50_000, 100_000, len(words)):
c = Counter(words[:n])
H = sum(-k / n * math.log2(k / n) for k in c.values())
print(f"first {n:>7,} words: {len(c):>6,} different, plug-in H = {H:.3f} bits per word, Miller-Madow {H + (len(c) - 1) / (2 * n * math.log(2)):.3f}")
first 1,000 words: 403 different, plug-in H = 7.757 bits per word, Miller-Madow 8.047
first 10,000 words: 2,106 different, plug-in H = 8.959 bits per word, Miller-Madow 9.111
first 50,000 words: 5,356 different, plug-in H = 9.320 bits per word, Miller-Madow 9.398
first 100,000 words: 7,827 different, plug-in H = 9.528 bits per word, Miller-Madow 9.585
first 208,503 words: 11,455 different, plug-in H = 9.620 bits per word, Miller-Madow 9.660
The plug-in word entropy rises from 7.76 bits per word on the first 1,000 words to 9.62 on all 208,503, and the vocabulary from 403 to 11,455, with no sign of levelling off. Miller's correction adds a little, but it assumes the sample has seen every word that matters, and word frequencies have a long tail of rare words (Zipf's law: the th commonest word appears about as often as the commonest), most of which haven't appeared yet. For such "heavy-tailed" sources, entropy estimates from any finite text are too low, and estimators designed for them (Chao–Shen, NSB, coverage-adjusted estimators) are needed.
Common misconceptions
| Misconception | What's actually true | Where it's shown |
|---|---|---|
| "Same entropy means equally compressible." | The plays, shuffled and sorted have equal order-0 entropy; lzma gives 2.61, 4.91 and 0.004 bits. | What the chapter oversimplifies, point 1 |
| "A code for a 0.08-bit source can use 0.08 bits per symbol." | Not one symbol at a time: at least 1 digit each; blocks approach 0.08 slowly. | What the chapter oversimplifies, point 2 |
| "Enough text gives the entropy of words." | The estimate kept rising with all 208,503 words; heavy tails defeat plug-in estimates. | What the chapter oversimplifies, point 3 |
| "scipy.stats.entropy returns bits." | Its default is nats; pass base=2. |
Code walkthrough, drill D1 |
| "Pass counts or probabilities, whichever: same result." | SciPy normalises, but your own function may not. | Drill D2 |
| "An entropy function can just skip zero probabilities." | Only if it's written to: log2(0) raises an error. |
Drill D3 |
| "Output that looks random has high entropy." | Hashes of a counter score 4.0 bits per hex character and are fully predictable. | Drill D4 |
Theoretical gaps: the ideas behind the chapter
- Perplexity. is the effective number of equally likely choices; language models report perplexity per token, and halving it means one bit less surprise per token.
- Concavity. Entropy is a concave function of the probabilities: mixing two distributions gives at least the average of their entropies. It's why mixing sources increases uncertainty, and why maximum-entropy problems have unique answers.
- Zipf's law and heavy tails. George Zipf (1935, 1949) observed that word frequencies fall off like with rank. A strict law over an infinite vocabulary can't be normalised, so real vocabularies are finite but large and keep growing with text length (Heaps' law), which is exactly why point 3's estimates keep rising.
Applying it
Code walkthrough
SciPy's entropy function is how most Python programs compute entropy. Excerpt from scipy/stats/_entropy.py in SciPy 1.18 (on your computer: python3 -c "import scipy.stats._entropy as m; print(m.__file__)"), with the long docstring shortened:
def entropy(pk: np.typing.ArrayLike,
qk: np.typing.ArrayLike | None = None,
base: float | None = None,
axis: int = 0
) -> np.number | np.ndarray:
"""
Calculate the Shannon entropy/relative entropy of given distribution(s).
If only probabilities `pk` are given, the Shannon entropy is calculated as
``H = -sum(pk * log(pk))``.
...
This routine will normalize `pk` and `qk` if they don't sum to 1.
...
"""
if base is not None and base <= 0:
raise ValueError("`base` must be a positive number or `None`.")
xp = array_namespace(pk, qk)
pk, qk = xp_promote(pk, qk, broadcast=True, xp=xp)
with np.errstate(invalid='ignore'):
if qk is not None:
pk, qk = _share_masks(pk, qk, xp=xp)
qk = qk / xp.sum(qk, axis=axis, keepdims=True)
pk = pk / xp.sum(pk, axis=axis, keepdims=True)
if qk is None:
vec = special.entr(pk)
else:
vec = _masked_apply(special.rel_entr, args=(pk, qk), xp=xp)
S = xp.sum(vec, axis=axis)
if base is not None:
S /= math.log(base)
return S
Three design decisions are visible. It normalises pk by its sum, so you can pass raw counts. It computes each term with special.entr, a compiled function defined as for , 0 at (the convention that impossible symbols contribute nothing) and for negative . And it works in natural logarithms unless told otherwise, dividing by at the end: the default unit is the nat. Given a second distribution qk, the same function computes the Kullback–Leibler divergence, chapter 11's subject. Measured:
import numpy as np
from scipy import special
from scipy.stats import entropy
print("entropy([0.9, 0.1], base=2) =", entropy([0.9, 0.1], base=2))
print("entropy([9, 1], base=2) =", entropy([9, 1], base=2), " (counts are normalised first)")
print("entropy([0.9, 0.1]) =", entropy([0.9, 0.1]), " (no base: nats)")
print("entropy([1, 1, 0], base=2) =", entropy([1, 1, 0], base=2), " (entr(0) is 0)")
print("special.entr([0.5, 0, -0.1]) =", special.entr(np.array([0.5, 0.0, -0.1])))
print("entropy([2, -1], base=2) =", entropy([2, -1], base=2))
entropy([0.9, 0.1], base=2) = 0.46899559358928117
entropy([9, 1], base=2) = 0.46899559358928117 (counts are normalised first)
entropy([0.9, 0.1]) = 0.3250829733914482 (no base: nats)
entropy([1, 1, 0], base=2) = 1.0 (entr(0) is 0)
special.entr([0.5, 0, -0.1]) = [0.34657359 0. -inf]
entropy([2, -1], base=2) = -inf
With base=2, the 90/10 coin gives the chapter's 0.469 bits, from probabilities or from the counts 9 and 1 alike. Without a base it gives 0.325, the same entropy in nats (). A zero entry contributes nothing, so gives 1 bit. A negative entry isn't rejected: entr of it is , and the whole entropy comes out .
Read it yourself
Using the code above: what does entropy([2, -1], base=2) return, and why doesn't the function raise an error? Then predict entropy([0, 0]), and say what check you'd add in your own code before calling it.
Debugging drills
D1. A file that "needs" fewer bytes than lzma can manage
A capacity report, using SciPy, claims that a code using only byte frequencies (one that ignores context) could store the plays in 461,884 bytes. Chapter 4 measured their order-0 entropy at 4.78 bits per byte, which says such a code can't go below about 666,000.
from collections import Counter
from scipy.stats import entropy
text = open("data/shakespeare.txt", "rb").read()
H = entropy(list(Counter(text).values()))
print(f"entropy of the plays' bytes: {H:.3f} bits per byte -> a 1,115,394-byte file needs at least {H * 1_115_394 / 8:,.0f} bytes")
entropy of the plays' bytes: 3.313 bits per byte -> a 1,115,394-byte file needs at least 461,884 bytes
D2. Negative entropy from counts
A hand-written entropy function returns −15.6 bits for "abracadabra" and 0 bits for a fair coin.
import math
from collections import Counter
def entropy_bits(counts):
return sum(-c * math.log2(c) for c in counts if c)
print(entropy_bits(Counter("abracadabra").values()))
print(entropy_bits([1, 1]))
-15.60964047443681
0.0
D3. A zero that crashes
An entropy function works on most inputs but crashes on a distribution with an impossible symbol.
import math
def entropy_bits(probs):
return -sum(p * math.log2(p) for p in probs)
print(entropy_bits([0.5, 0.5]))
try:
print(entropy_bits([0.5, 0.5, 0.0]))
except ValueError as e:
print("ValueError:", e)
1.0
ValueError: math domain error
D4. Tokens that pass an entropy test
A security check computes the order-0 entropy of a sample of password-reset tokens, finds 4.0000 bits per hex character, the maximum, and approves the generator. The tokens are the first 16 hex characters of SHA-256 of a counter.
import hashlib, math
from collections import Counter
tokens = [hashlib.sha256(str(i).encode()).hexdigest()[:16] for i in range(100_000)] # "random" reset tokens
chars = "".join(tokens)
n = len(chars)
H = sum(-c / n * math.log2(c / n) for c in Counter(chars).values())
print(f"order-0 entropy of the tokens' characters: {H:.4f} bits per character (maximum for hex: 4)")
print(f"so a 16-character token 'has' {16 * H:.1f} bits")
print("token number 41,337:", tokens[41_337], "| recomputed from the counter:", hashlib.sha256(b"41337").hexdigest()[:16])
order-0 entropy of the tokens' characters: 4.0000 bits per character (maximum for hex: 4)
so a 16-character token 'has' 64.0 bits
token number 41,337: 6000a3826fa71338 | recomputed from the counter: 6000a3826fa71338
Career-oriented
Interview prep
Mid level
Q1. What is the entropy of a distribution, and what does it tell you in practice?
How to get there. Average surprise; the floor for compression; uncertainty.
Q2. Why does a column of mostly "OK" values compress so well, and a column of UUIDs not at all?
How to get there. Entropy per value.
Senior level
Q3. A teammate says "this file has entropy 7.9 bits per byte, so it's already compressed or encrypted". When is that inference sound and when isn't it?
How to get there. Order-0 entropy as a weak test.
Q4. How would you estimate the entropy of user-chosen PINs, and why is the plug-in estimate from a sample of 1,000 PINs misleading?
How to get there. Bias, heavy tails, min-entropy.
Staff level
Q5. Your team proposes to monitor a data pipeline by alerting when the entropy of a column changes by more than 10 %. Evaluate the idea.
How to get there. What entropy changes mean, sample size, and what it can't see.
Q6. A vendor sells a "maximum compression" storage product claiming 10:1 on any data. How would you assess it?
How to get there. Entropy as a floor; what data you have.