What is Shannon entropy?
Entropy measures how uncertain an outcome is before you see it: the average surprise of a distribution, in bits. Claude Shannon defined it in 1948 to found information theory.
- A fair coin has 1 bit: the most any two outcomes can have.
- A certain outcome (one bar at 100%) has 0 bits: nothing to learn.
- n equally likely outcomes have log₂ n bits, the most for n.
Bits you can count
The squares under each bar are a Huffman code for the outcomes: likely ones get short codes, rare ones long. Its average length is never below H, and within one bit of it. Entropy is the limit of how short a code can be.
Try this
- Fair coin: drag Heads toward 100% and watch H fall to 0.
- Fair die, then Loaded die: which has more entropy? How long are the codes?
- Add outcomes and press Uniform. Does H match log₂ n?
- Balls in bag: add balls until H is as large as it can be for three colours.
- In the Sampling tab, draw 1,000: the average surprise settles on H.
Computing entropy
- For each outcome i, with probability pi
- its surprise is −log2 pi bits;
- weight it by how often it happens: −pi log2 pi;
- add them up.
function entropy(probabilities):
H = 0
for p in probabilities:
if p > 0:
H -= p * log2(p)
return H
Why log2?
Base 2 counts in bits: a fair coin flip takes exactly one binary digit to record. Another base only changes the unit (nats for ln).
Why skip p = 0?
An outcome that never happens never surprises anyone: p log p → 0 as p → 0.
Huffman coding
Repeatedly join the two least likely outcomes (or groups) into one, labelling one branch 0 and the other 1. Reading the branches back gives each outcome its code.
Properties
- H(X) ≥ 0, with 0 only when one outcome is certain.
- H(X) ≤ log2 n, with equality only for the uniform distribution.
Draw outcomes from the distribution. Each draw scores its surprise, −log2 p. Over many draws the average surprise settles on the entropy: entropy is the expected surprise (the law of large numbers).