Information entropy
信息熵
Measure expected surprisal, connect probabilities to code lengths, and distinguish low uncertainty from correct or useful predictions.
entropyShorter names for common messages
Imagine a protocol with five message types. In a teaching model, “repeat” occurs half the time; “add,” “replace,” “delete,” and “inspect” each occur one eighth of the time. A fixed-width binary code needs 3 bits per message because 2 bits distinguish only four types.
Assign codes 0, 100, 101, 110, and 111 instead. None is a prefix of another, so a receiver can identify where each codeword ends. The common message uses 1 bit and the others use 3. The average is bits per message. Unequal probabilities create a compression opportunity.
Average the surprise, not the probabilities
For a positive-probability outcome, define its information content or surprisal as . An outcome with probability contributes 3 bits of surprisal; a certain outcome contributes 0. The logarithm makes surprisals add for independent events because their probabilities multiply.
Shannon entropy is the expected surprisal of a discrete distribution:
The zero-probability contribution is defined as zero using the limit of as . Entropy depends on a probability model and alphabet. It does not directly quantify how meaningful a message is to a person. Shannon’s paper develops this quantity and its communication-theoretic consequences. Shannon, Section 6
On an alphabet of symbols, . A point mass attains the lower bound; the uniform distribution attains the upper bound. For positive probabilities on supported symbols, concavity of logarithm gives a short upper-bound derivation:
Concavity means that the average logarithm cannot exceed the logarithm of the average. Uniform probabilities make the arguments equal and attain equality. The protocol distribution has entropy 2 bits, while five equally likely messages have entropy bits.
Entropy bounds the average length of lossless binary prefix coding for a known discrete source. Integer codeword lengths may prevent a single-symbol code from attaining the bound; for independent repetitions of a finite source, an -symbol block has entropy , and block coding can make the overhead per symbol approach zero. Dependent sources require their joint block entropy instead. Our chosen dyadic probabilities attain it exactly with the displayed prefix code. This does not mean every individual message must occupy exactly its entropy in bits. Shannon, Sections 9–10
Compute entropy and check an actual code
The following complete program validates a finite probability vector, skips zero terms, and checks prefix decodability independently of the entropy calculation.
import math
def entropy(probabilities):
if not probabilities or any(not math.isfinite(p) or p < 0 or p > 1 for p in probabilities):
raise ValueError("finite probabilities in [0,1] required")
if not math.isclose(sum(probabilities), 1, rel_tol=0, abs_tol=1e-12):
raise ValueError("probabilities must sum to one")
return -sum(p*math.log2(p) for p in probabilities if p > 0)
def prefix_free(codes):
return all(not b.startswith(a) for i,a in enumerate(codes)
for j,b in enumerate(codes) if i != j)
p = [.5,.125,.125,.125,.125]
codes = ['0','100','101','110','111']
assert prefix_free(codes)
assert not prefix_free(['0','01'])
assert sum(q*len(c) for q,c in zip(p,codes)) == entropy(p) == 2
assert math.isclose(entropy([.2]*5), math.log2(5))
assert entropy([1,0]) == 0 and entropy([.5,.5]) == 1
assert entropy(p+[0]) == entropy(p)
unconditional = entropy([.95,.05])
conditional_average = .9*entropy([1,0])+.1*entropy([.5,.5])
assert math.isclose(unconditional, .28639695711595625)
assert conditional_average < unconditional < 1
Entropy requires arithmetic and logarithm evaluations with constant additional working storage. This small prefix check compares all codeword pairs, costing character work for maximum codeword length . A trie can check a large codebook more efficiently.
Confidence is not correctness
A model predicting one class with probability 1 has zero predictive entropy. It can still be confidently wrong on every example. Evaluating predictions against observed labels requires an appropriate loss such as cross-entropy, plus calibration and task metrics. Entropy alone is not a score for factual accuracy. D2L, Section 4.1.3
Conditioning reduces discrete entropy on average, not necessarily for each particular observed condition. Suppose a rare case occurs with probability 0.1 and makes a flag equally likely to be 0 or 1; otherwise the flag is always 0. Its unconditional entropy is about 0.2864 bits. Learning that the rare case occurred raises the flag’s entropy to 1 bit, even though average conditional entropy is only 0.1 bits.
Changing logarithm base changes units: base 2 gives bits, base gives nats, with one nat equal to bits. Changing tokenization or the symbol alphabet also changes what “per symbol” measures. Differential entropy for continuous densities is a different quantity: it can be negative and changes under rescaling, so the discrete nonnegative bound cannot be reused unchanged. Deep Learning, Section 3.13
Make the comparison explicit
- What is the entropy of a fair binary flag? Answer: 1 bit.
- What happens if a zero-probability symbol is appended? Answer: entropy is unchanged; its contribution is zero.
- Does a symbol’s codeword length of 3 mean the whole distribution has entropy 3? Answer: no. Entropy averages surprisal over all outcomes.
- Can temperature sampling that increases predictive entropy prove an answer became more accurate? Answer: no. It changes the sampling distribution, not the evidence supporting the answer.
Which uncertainty is being measured?
Decision trees use class entropy to compare partitions; language modeling uses cross-entropy against data; information theory studies coding limits and entropy rates of dependent sequences. These uses share mathematics but ask different questions. State the distribution, logarithm base, unit of observation, and conditioning information before comparing reported values.
Make a prediction, then check
A model always assigns probability 1 to one class and has zero predictive entropy. What follows?
Learning objectives
- Calculate discrete entropy and its upper bound, and check average lengths using a prefix code.
- Distinguish predictive certainty, factual correctness, average conditional entropy, and entropy under a particular condition.
Prerequisites & connections
Explore related knowledge →References
- A Mathematical Theory of Communication (reprint)
Claude E. Shannon · 1948 - Deep Learning — Chapter 3: Probability and Information Theory
Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016 - Dive into Deep Learning — Softmax Regression
Aston Zhang; Zachary C. Lipton; Mu Li; Alexander J. Smola · 2023
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.
- Recomputed entropy 2 bits and prefix-code mean length 2 for the original five-symbol example, and log₂5 for a uniform alphabet; checked the concavity bound and zero terms.
- Checked rare-condition entropy 1, unconditional entropy about 0.2864, and average conditional entropy 0.1; tested 30 vectors’ entropy bounds and independent-product additivity, with block-independence and differential-entropy limits stated.
- Compared arguments, modeling assumptions, numbers, and exercise answers across languages; structural checks separately compare display formulas, code, references, and main sections. No independent human peer review.
Source locations checked:
- A Mathematical Theory of Communication (reprint) · Reprint §6 and §9–10: entropy and coding, with reprint provenance retained
- Deep Learning — Chapter 3: Probability and Information Theory · §3.13: information theory
- Dive into Deep Learning — Softmax Regression · §4.1.3: entropy, surprisal, and cross-entropy
Related topics