AnyLearn
All lessons
Computer Scienceintermediate

Entropy: Measuring Information in Bits

Shannon's entropy measures the average surprise of a source, in bits, and it sets a hard floor on compression. Build it up from surprisal through joint and conditional entropy, mutual information, KL divergence and cross-entropy, with every number worked out by hand.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 10

Information is surprise

The everyday word information is about meaning. Shannon's is not. In information theory, the information carried by an event is how surprised you should be to see it.

David MacKay, in Information Theory, Inference, and Learning Algorithms (Cambridge University Press, 2003), defines the Shannon information content of an outcome xx as h(x)=log2(1/P(x))h(x) = \log_2 (1/P(x)), measured in bits.

Probability of the eventInformation content
1 (certain)0 bits
1/21 bit
1/83 bits
1/102410 bits

A certain event tells you nothing. A one-in-a-thousand event carries about 10 bits. The logarithm is the right shape for exactly one reason: independent events multiply their probabilities, and we want their surprises to add. Each halving of the probability costs precisely one more bit.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. Information is surprise

The everyday word information is about meaning. Shannon's is not. In information theory, the information carried by an event is how surprised you should be to see it.

David MacKay, in Information Theory, Inference, and Learning Algorithms (Cambridge University Press, 2003), defines the Shannon information content of an outcome xx as h(x)=log2(1/P(x))h(x) = \log_2 (1/P(x)), measured in bits.

Probability of the eventInformation content
1 (certain)0 bits
1/21 bit
1/83 bits
1/102410 bits

A certain event tells you nothing. A one-in-a-thousand event carries about 10 bits. The logarithm is the right shape for exactly one reason: independent events multiply their probabilities, and we want their surprises to add. Each halving of the probability costs precisely one more bit.

2. Entropy is the average surprisal

Entropy is what you get when you average that surprise over every outcome the source can produce:

H(X)=ipilog2piH(X) = -\sum_i p_i \log_2 p_i

Claude Shannon introduced it in A Mathematical Theory of Communication, published in two parts in the Bell System Technical Journal, vol. 27, pp. 379-423 (July 1948) and pp. 623-656 (October 1948). He did not simply assert the formula. In Theorem 2 he shows it is the only function satisfying three requirements: continuity in the probabilities, monotonic growth in the number of equally likely choices, and consistency when a choice is split into two successive choices.

The unit comes from the same paper. Shannon writes that base 2 gives units that "may be called binary digits, or more briefly bits, a word suggested by J. W. Tukey." Bits are not an implementation detail here. They are the natural currency of binary questions.

3. Worked example: a four-symbol source

Take a source emitting four symbols with probabilities 1/2,1/4,1/8,1/81/2, 1/4, 1/8, 1/8. Term by term:

(1/2) x log2(2) = 0.5 x 1 = 0.500
(1/4) x log2(4) = 0.25 x 2 = 0.500
(1/8) x log2(8) = 0.125 x 3 = 0.375
(1/8) x log2(8) = 0.125 x 3 = 0.375
                        H = 1.750 bits

Exactly 7/4 bits. This is Example 2.1.2 in Cover and Thomas, Elements of Information Theory (Wiley), and the number is not abstract. Assign the codewords 0, 10, 110, 111 and the average length is 0.5(1)+0.25(2)+0.125(3)+0.125(3)=1.750.5(1) + 0.25(2) + 0.125(3) + 0.125(3) = 1.75 bits per symbol. Entropy predicted the best possible code, and the code hit it exactly.

A fixed 2-bit-per-symbol encoding would spend 2.0 bits. The 0.25-bit gap is real, recoverable compression.

4. Uniform is the maximum, and everything else is redundancy

For an alphabet of nn symbols, entropy is maximised when all symbols are equally likely, giving log2n\log_2 n bits. Any skew in the distribution pushes entropy down, and that shortfall is exactly the redundancy a compressor can exploit.

A fair coin: H=1H = 1 bit. A coin biased to 0.9 heads:

-0.9 x log2(0.9) = 0.9 x 0.15200 = 0.13680
-0.1 x log2(0.1) = 0.1 x 3.32193 = 0.33219
                             H = 0.4690 bits

Storing each flip in one literal bit wastes over half a bit per flip.

Shannon measured this for English in Prediction and Entropy of Printed English (Bell System Technical Journal, vol. 30, no. 1, January 1951, pp. 50-64). A 26-letter alphabet chosen uniformly would give 4.70 bits per letter; using real letter frequencies drops it to 4.14; and with 100 letters of preceding context his experiments bracket English between 0.6 and 1.3 bits per letter.

5. Joint and conditional entropy

Two random variables give three quantities worth naming:

  • Joint entropy H(X,Y)H(X,Y): total uncertainty in the pair.
  • Conditional entropy H(YX)H(Y \mid X): uncertainty left in YY once you already know XX.
  • The chain rule tying them together: H(X,Y)=H(X)+H(YX)H(X,Y) = H(X) + H(Y \mid X).

Cover and Thomas state this as Theorem 2.2.1 in Elements of Information Theory. Shannon derived the same relation in section 6 of his 1948 paper and glossed it plainly: the uncertainty of the joint event is the uncertainty of XX plus the uncertainty of YY when XX is known. He called H(XY)H(X \mid Y) the equivocation, which is still the term used for what a noisy channel destroys.

Conditioning never hurts: H(YX)H(Y)H(Y \mid X) \le H(Y). Knowing something about XX can only leave you less uncertain about YY, or equally uncertain if the two are independent.

6. Mutual information: how much one variable says about another

Mutual information is the drop in uncertainty about XX that you get from observing YY:

I(X;Y)=H(X)H(XY)=H(Y)H(YX)=H(X)+H(Y)H(X,Y)I(X;Y) = H(X) - H(X \mid Y) = H(Y) - H(Y \mid X) = H(X) + H(Y) - H(X,Y)

Shannon wrote all three forms in section 12 of the 1948 paper, calling the quantity the rate of transmission. It is symmetric, always non-negative, and zero exactly when XX and YY are independent.

Worked example. Send a uniform random bit through a binary symmetric channel that flips it with probability 0.1. The receiver's leftover uncertainty is H(0.1)=0.4690H(0.1) = 0.4690 bits, computed exactly as the biased coin was. So

I(X;Y) = 1 - 0.4690 = 0.5310 bits per channel use

You pushed one bit in and roughly half a bit of it survived. That number is not a metaphor; it is the channel's capacity.

7. How the quantities decompose

Joint entropy splits into three non-overlapping pieces, and the entropies of each variable are built from them:

flowchart LR
  J["Joint entropy H(X,Y)"]
  A["H(X given Y): unique to X"]
  M["I(X;Y): shared by both"]
  B["H(Y given X): unique to Y"]
  HX["H(X) = unique to X plus shared"]
  HY["H(Y) = unique to Y plus shared"]
  J --> A
  J --> M
  J --> B
  A --> HX
  M --> HX
  M --> HY
  B --> HY

8. KL divergence: the cost of believing the wrong distribution

Kullback-Leibler divergence measures how far a model qq is from the truth pp:

D(pq)=ipilog2(pi/qi)D(p \parallel q) = \sum_i p_i \log_2 (p_i / q_i)

It comes from Solomon Kullback and Richard Leibler, On Information and Sufficiency, Annals of Mathematical Statistics, vol. 22, no. 1 (March 1951), pp. 79-86.

Worked example. Truth p=(0.5,0.5)p = (0.5, 0.5), model q=(0.8,0.2)q = (0.8, 0.2):

D(p||q) = 0.5 log2(0.5/0.8) + 0.5 log2(0.5/0.2)
        = 0.5(-0.6781) + 0.5(1.3219) = 0.3219 bits

D(q||p) = 0.8 log2(0.8/0.5) + 0.2 log2(0.2/0.5)
        = 0.8(0.6781) + 0.2(-1.3219) = 0.2781 bits

The two disagree. KL divergence is not symmetric and does not obey the triangle inequality, so it is not a distance despite constantly being described as one. Cover and Thomas prove it is always non-negative and zero only when p=qp = q, calling that the information inequality.

9. Cross-entropy: what you actually pay

Cross-entropy is the bill for coding data drawn from pp using a code built for qq:

H(p,q)=ipilog2qi=H(p)+D(pq)H(p,q) = -\sum_i p_i \log_2 q_i = H(p) + D(p \parallel q)

Goodfellow, Bengio and Courville state this identity in Deep Learning (MIT Press, 2016, section 3.13). Continuing the example above:

H(p,q) = -0.5 log2(0.8) - 0.5 log2(0.2)
       = 0.1610 + 1.1610 = 1.3219 bits
check:   H(p) + D(p||q) = 1.0 + 0.3219 = 1.3219  OK

You pay 1.3219 bits where 1.0 would do. The excess is the KL divergence.

Because H(p)H(p) does not depend on qq, minimising cross-entropy over models is identical to minimising KL divergence, which is why cross-entropy over next-token prediction is literally the training loss for language models (Kaplan et al., Scaling Laws for Neural Language Models, 2020, describe optimising "the autoregressive log-likelihood, i.e. cross-entropy loss"). Perplexity is just that loss exponentiated: 21.3219=2.52^{1.3219} = 2.5.

10. Four quantities, and three ways to misread them

QuantityQuestion it answersZero when
H(X)H(X)How uncertain is this source?One outcome is certain
H(XY)H(X \mid Y)What is left after seeing YY?YY determines XX
I(X;Y)I(X;Y)How much do they share?They are independent
D(pq)D(p \parallel q)How wrong is my model?The model is exact

Three traps worth avoiding:

  • Entropy is a property of the distribution, not of a string. "The entropy of this file" is shorthand for the entropy of a model you fitted to it. Change the model and the number changes.
  • KL divergence is not a distance. The worked example gave 0.3219 one way and 0.2781 the other. Which argument goes first matters, and the two directions penalise different failures.
  • Bits versus nats. Base 2 gives bits, natural log gives nats, and 11 nat is about 1.44271.4427 bits. Machine learning code defaults to nats; compression literature defaults to bits.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. A source emits four symbols with probabilities 1/2, 1/4, 1/8, 1/8. What is its entropy?
    • 2.00 bits, because there are four symbols
    • 1.75 bits
    • 1.00 bit, because the most likely symbol has probability 1/2
    • 4.00 bits, one per symbol times four symbols
  2. Why does information content use a logarithm rather than, say, 1/P(x) directly?
    • Because logarithms are faster to compute than division
    • Because it keeps the answer between 0 and 1
    • So that the information from independent events adds while their probabilities multiply
    • Because Shannon needed the formula to match thermodynamic entropy exactly
  3. A binary symmetric channel flips each bit with probability 0.1, and the input is a uniform random bit. Given H(0.1) = 0.4690 bits, what is the mutual information between input and output?
    • 0.5310 bits
    • 0.4690 bits
    • 0.9000 bits, since 90% of bits arrive intact
    • 1.4690 bits
  4. With truth p = (0.5, 0.5) and model q = (0.8, 0.2), the KL divergence is 0.3219 bits one way and 0.2781 bits the other. What does that show?
    • One of the two calculations must contain an arithmetic error
    • KL divergence is asymmetric, so it is not a true distance
    • KL divergence can be negative depending on argument order
    • The distributions are independent of each other
  5. Cross-entropy H(p,q) decomposes as H(p) + D(p||q). Why does this make it a sensible training loss?
    • Because H(p) shrinks as the model improves, giving a smooth gradient
    • Because cross-entropy is symmetric in p and q, unlike KL divergence
    • Because it is bounded above by 1 bit for any model
    • Because H(p) is a constant with respect to the model, so minimising cross-entropy is exactly minimising the KL divergence

Related lessons

Computer Science
intermediate

Channel Capacity and Error-Correcting Codes

Shannon proved that a noisy channel still has a rate at which errors vanish. This lesson works a Hamming code by hand, follows Reed-Solomon into CDs, QR codes and deep space, reaches the capacity-approaching codes inside 5G, and ends on erasure coding versus replication in distributed storage.

12 steps·~18 min
Computer Science
intermediate

Source Coding: Huffman, Arithmetic Coding and ANS

Entropy is a hard floor on lossless compression, and this lesson shows how coders approach it. Build a Huffman tree by hand, see exactly where it wastes bits on skewed sources, then follow the fix through arithmetic coding to asymmetric numeral systems, the entropy stage inside Zstandard.

11 steps·~17 min
Computer Science
intermediate

Lossy Compression and the Rate-Distortion Tradeoff

Lossy compression is not lossless compression done badly. It is a deliberate trade of fidelity for rate, governed by a curve Shannon derived in 1959. This lesson covers rate-distortion theory, transform coding and the DCT, where JPEG actually discards information, perceptual coding in audio, motion compensation in video, and learned codecs.

11 steps·~17 min
AI
intermediate

LLM Pretraining: Data, Loss, and What Actually Happens

A deep dive into how large language models learn from raw text: the next-token prediction objective, cross-entropy loss, the messy reality of web data curation (Common Crawl, dedup, quality filters), and the lineage from The Pile to FineWeb.

12 steps·~18 min