Shannon entropy
Define entropy as expected surprise and derive its basic properties.
How much uncertainty is in a distribution? A fair coin is more uncertain than a biased one; a uniform die more than a loaded one. Shannon entropy turns this intuition into a number, measured in bits, and it is the floor on how many bits per symbol any lossless code can achieve[1, 2]. It is also the backbone of the cross-entropy loss.
Surprise
The surprise (or information content) of an outcome with probability is
Three requirements force this form. Surprise should decrease in (certain events are unsurprising, ), be nonnegative, and be additive for independent events: seeing two independent outcomes of probability should surprise you by . Since the joint probability is , the function must satisfy , and the logarithm is the function that turns products into sums. With , surprise is in bits.
A good mental hook: surprise measures newsworthiness, how much you learn when one specific outcome actually happens. Some real-world magnitudes:
- The sun rose this morning. , so bits. You learned nothing; nobody reports it.
- A fair coin landed heads. , so bit, the unit itself.
- Two dice came up snake eyes. , so bits. Noteworthy at the table, not in the paper.
- You won a national lottery. (about one in 300 million), so bits. Front-page news, precisely because it was so improbable.
The additivity requirement is easy to sanity-check on the coin: two heads in a row has probability , and your surprise is bits; indeed . And a "bit" itself has an operational reading: an event of probability carries bits because learning it happened is like learning which of equally likely doors opened, which takes exactly three yes/no questions.
Entropy
The entropy of a discrete distribution is the expected surprise[3]:
with the convention (vanishingly rare outcomes contribute nothing). With it is in bits; with natural log, in nats. Entropy is a property of the distribution, not of any particular outcome: it asks not "how surprised am I by this event?" but "how surprised am I on average, draw after draw?"
Compare the weather in two cities. In a desert city, and . Almost every morning you look outside and learn essentially nothing ( bits); once in a hundred days you are quite surprised ( bits), but that almost never happens. The average is
The weather there is boring: low entropy. In a coin-flip city with , every single morning is a genuine coin toss worth one full bit: bit, the most unpredictable a two-outcome source can be.
This averaging resolves a confusion worth naming explicitly: a rare event has huge surprise but contributes almost nothing to entropy, because entropy weights each surprise by how often it occurs, and as (that is exactly the convention at work). The lottery is the extreme case: winning is a 28-bit shock, yet the lottery as a distribution has nearly zero entropy (about bits), because the outcome is almost always the utterly unsurprising "you lost." High surprise describes one outcome; high entropy describes an unpredictable source. They can point in opposite directions.
The binary entropy function
For a Bernoulli() variable,
It is 0 at and (no uncertainty) and peaks at with bit. A fair coin carries exactly one bit; any bias reduces it.
Bounds
Entropy is nonnegative: each term because makes .
Maximum at the uniform distribution. Among all distributions on outcomes, entropy is largest for the uniform , where . This follows from Jensen's inequality applied to the concave :
Equality holds when is constant, i.e. is uniform. Uncertainty is maximized when no outcome is favored.
Differential entropy
For a continuous density , the analogue is the differential entropy . It can be negative and is not invariant under change of variables (a coordinate stretch shifts it by the log-Jacobian), so it behaves differently from discrete entropy. Among densities with a fixed variance , the Gaussian maximizes differential entropy at , a reason the Gaussian is the "least assuming" choice at fixed spread.
Check it on arrays
import numpy as np
# Binary entropy peaks at q = 0.5
def H_bits(p):
p = np.asarray(p, float)
nz = p[p > 0] # skip zero-probability outcomes
return -np.sum(nz * np.log2(nz))
for q in [0.0, 0.1, 0.5, 0.9, 0.99, 1.0]: # 0.99 = the desert city
dist = np.array([q, 1 - q])
print(f"H(Bernoulli({q})) = {H_bits(dist):.4f} bits")
# Uniform over K outcomes has entropy log2(K); it is the maximum
K = 8
uniform = np.full(K, 1 / K)
skewed = np.array([0.5] + [0.5 / (K - 1)] * (K - 1))
print(f"H(uniform_{K}) = {H_bits(uniform):.4f} (log2 {K} = {np.log2(K):.4f})")
print(f"H(skewed) = {H_bits(skewed):.4f} (< uniform)")
# Entropy as expected surprise, estimated from samples
rng = np.random.default_rng(13)
probs = np.array([0.5, 0.25, 0.15, 0.10])
samples = rng.choice(len(probs), size=500_000, p=probs)
surprise = -np.log2(probs[samples])
print("E[surprise] sampled:", round(surprise.mean(), 4),
" true H:", round(H_bits(probs), 4))The binary entropy peaks at one bit for a fair coin, the uniform distribution attains the maximum , and average sampled surprise matches the entropy.
Exercises
Exercise 1. Compute, by hand, the entropy in bits of .
Solution
Step 1. Each outcome contributes . The surprises are , , and bits.
Step 2. Weight each surprise by its probability and sum:
Sanity checks: is below the uniform maximum bits, as the bound requires, and above the bit a fair coin carries, since four outcomes are in play.
Exercise 2. Let and be independent discrete variables. Prove that entropy is additive: , where is the entropy of the pair under the joint distribution.
Solution
Step 1. Write the joint entropy as expected surprise of the pair: .
Step 2. Use independence to factor the joint probability, , so the surprise of the pair splits into a sum (the same additivity that forced the logarithm in the first place):
Step 3. Take expectations and use linearity:
Independent sources stack: two fair coins carry bits jointly.
Exercise 3 (code). Draw 10,000 random distributions on outcomes (normalize positive random vectors). Verify numerically that none exceeds bits, and that the entropy of Exercise 1's distribution is exactly bits.
Solution
import numpy as np
def H_bits(p):
p = np.asarray(p, float)
nz = p[p > 0]
return -np.sum(nz * np.log2(nz))
rng = np.random.default_rng(0)
raw = rng.random((10_000, 4))
dists = raw / raw.sum(axis=1, keepdims=True) # rows sum to 1
ents = np.array([H_bits(d) for d in dists])
assert ents.max() <= 2.0 # Jensen bound: H <= log2 K
assert np.isclose(H_bits([0.5, 0.25, 0.125, 0.125]), 1.75)
print("max sampled H:", round(ents.max(), 4), "of bound", 2.0)The sampled maximum approaches but never crosses bits; only the exactly uniform distribution attains it.
The next lesson compares two distributions instead of summarizing one: the KL divergence.
References
- [1]Shannon, C. E. (1948). "A mathematical theory of communication". Bell System Technical Journal, 27, 379-423. The paper that introduced entropy and the noiseless source coding bound. doi:10.1002/j.1538-7305.1948.tb01338.x↩
- [2]Cover, T. M., & Thomas, J. A. (2006). Elements of Information Theory (2nd ed.). Wiley. Ch. 2, entropy and the source coding theorem. doi:10.1002/047174882X↩
- [3]MacKay, D. J. C. (2003). Information Theory, Inference, and Learning Algorithms. Cambridge University Press. Ch. 2-4, surprise, entropy, and Shannon information.↩