Two coins sit on the table. One is fair. The other lands heads times out of . You must guess the next flip of each. The fair coin is a pure guess, and the second one is easy: say heads and you are almost always right. The first coin is more uncertain.
P1.E1 gave every single outcome a number, its surprise . This lesson averages those surprises over a whole source and calls the result entropy. It is one number for how hard the source is to predict. It also has a practical meaning: it is the fewest bits per symbol that lossless compression can use on average for a source of independent symbols, and the same average shows up in decision trees, in model confidence and in the temperature knob of a language model.
From one surprise to the average
A source produces an outcome with probability . The surprise of that outcome is (P1.E1). Some outcomes are likely and barely surprising, and others are rare and very surprising. To describe the source with one number, average the surprise over the outcomes, weighting each by how often it happens. That is an expectation (P1.D4): , with . The result is the entropy of :
With the unit is the bit, and with it is the nat (P1.E1). The two differ by a constant: .
A coin with for heads. Heads has surprise bits and tails has bits. Tails is much more surprising, but it happens only one time in ten. Weighting by the probabilities:
For a fair coin both surprises are bit, so bit. For , heads costs bits and tails costs bits, and bits. That is the number P1.E1 promised.
| Heads | Tails | (bits) | (nats) | |
|---|---|---|---|---|
| none |
In the table, is the probability of heads, and the Heads and Tails columns give the surprise of each result in bits. The entropy is the number you would get by flipping the coin many times and averaging the surprise of each flip (the law of large numbers, P1.D9). The code cell at the end does exactly that.
Reshape a distribution
Drag the bars to change the probabilities. The other bars rescale so that the total stays . Under each bar you see its surprise and its share of the entropy, and the meter adds the shares up.
What to try:
- Certain. Press “One certain”: one bar has , the others , and . Nothing is uncertain.
- Uniform. Press “Uniform”: all four bars are , each surprise is bits and , at the dashed line.
- Coin. Press “Coin 0.9 / 0.1”: . Then drag the first bar toward and watch the entropy rise to .
- Halves. Press “Halves”: the probabilities have surprises and contributions , which add to bits.
- Zeros. Raise from to with the halves in place: the new bars have , they add and does not change.
- Open the second panel and drag : the entropy of a coin peaks at , is symmetric around it, and falls to at both ends.
The binary entropy function
For a source with two outcomes, with probabilities and , entropy is a function of one number:
Its shape (second panel of the widget) says most of what matters. It is at and , where the outcome is certain. It rises to a single peak of exactly bit at . And it is symmetric: , because a coin that lands heads of the time is exactly as predictable as one that lands tails of the time. Both have . Calculus (P1.C2) confirms the peak: the slope of is , which is at , positive before it and negative after it. Each term on its own, in nats, peaks earlier, at (the example in P1.C2); the two terms together peak at . The curve is steep near the ends: moving from to removes more than half of the entropy ().
The convention . The formula contains for every outcome, and for the log is not defined. The convention is to count such a term as , and it is not arbitrary. As shrinks, goes to : it is at , at and at . An outcome that never happens should not change how uncertain the source is, so adding impossible outcomes leaves the same. Code needs care here: 0 * np.log2(0) is nan, so filter out the zero probabilities first (the code cell does).
The most uncertain distribution
Which distribution over outcomes is the hardest to predict? The one where all outcomes are equally likely. With for every outcome each surprise is , so the average is
A fair coin gives bit, a fair die gives bits (the surprise of every face), and a uniform choice among items gives bits, the ten questions of P1.E1. For a finite number of outcomes, no distribution does better:
The lower end holds because each surprise is not negative, and it is reached only when one outcome has probability (the others have probability ). The upper end is reached only by the uniform distribution. A short proof is in the Go-deeper box “Why the uniform distribution has the largest entropy” below.
A distribution in between, a categorical example (P1.D3): probabilities . The terms are , and , so bits, below . In nats it is .
The effective number of outcomes. A fair choice among options has , so . Turn it around: for any distribution, is the size of the uniform distribution with the same entropy. A fair die gives . The coin with gives , about as unsure as equally likely options. The categorical gives against outcomes. It need not be a whole number. P1.E5 calls this quantity the perplexity, and uses it to score language models.
Properties of entropy
- It is not negative, for a discrete variable, since every surprise is at least when .
- It is exactly when one outcome is certain.
- For outcomes it is at most , with equality exactly for the uniform distribution.
- It depends on the probabilities, not on the values. The outcomes can be heads and tails, and , or and . The entropy is bit for a fair choice in all cases. So entropy is not the variance: the variance of a fair choice between and is huge and the variance between and is small, yet their entropies are equal.
- Outcomes with change nothing.
- For independent variables the entropies add. Take the coin with and a fair die, independent of each other. The pair has outcomes with probabilities and , and bits. This is the average version of the rule from P1.E1 that surprises of independent events add. A run of independent flips of the coin has bits of entropy.
- For dependent variables the joint entropy is smaller. Let a fair coin be copied exactly into . The pair has two equally likely outcomes, so bit, not . Let instead copy but be wrong one time in ten, so the four pairs have probabilities . Then . In general , with equality exactly when the variables are independent. P1.E5 develops this as mutual information.
Entropy as questions and as code length
P1.E1 turned bits into yes/no questions. Entropy gives the average count. Take four outcomes A, B, C, D with probabilities . The fastest way to find one is to ask about the likely ones first: “is it A?”, then “is it B?”, then “is it C?”. A takes question, B takes , and C and D take each. On average,
which is exactly the entropy bits. Each outcome took as many questions as its surprise (, , , bits).
Write the answers as bits (yes is and no is ) and the questions become a code: A is , B is , C is and D is . No codeword is the beginning of another one (a prefix code), so a stream of symbols can be split into codewords without any separators. A fixed code with two bits per symbol would cost bits per symbol, so this code saves bits per symbol. Its average length, , equals .
| Outcome | Surprise (bits) | Code | Code length | |
|---|---|---|---|---|
| A | ||||
| B | ||||
| C | ||||
| D |
This is a limit, not a coincidence. Shannon’s source coding theorem (1948) says, for symbols drawn independently from the distribution : no lossless prefix code can have an average length below bits per symbol, and a best possible code has an average length below . Compressing blocks of symbols at a time brings the average per symbol within bits of . So the entropy is the compression limit.
When the probabilities are not powers of , the limit is not met by coding one symbol at a time. The coin with has , but a codeword needs at least one bit, so coding each flip alone costs bit. Code pairs of flips instead: HH has probability , HT and TH have each and TT has . The code , , , has an average length bits per pair, which is per flip. Triples bring it to about per flip, still above and moving toward it.
Two cautions. First, the theorem is about the average over a source. It says nothing against a short code for one particular message that you happen to know in advance. Second, real data such as text is not made of independent symbols, so compressors work with a model of the data. If the model assigns probability when the truth is , the cost per symbol rises above to the cross-entropy (P1.E3), and the extra amount is the KL divergence (P1.E4).
Go deeper Why the uniform distribution has the largest entropy
Write the entropy as an average of over the outcomes with . Say there are of them, with . The logarithm is a concave function: its graph bends downward, so the average of a log is at most the log of the average (Jensen’s inequality, P1.D4). Therefore
Equality in the first step needs to be the same for every outcome that can happen, so all the nonzero probabilities are equal. Equality in the second step needs , so none of the probabilities is . Both hold only for the uniform distribution. The proof needs a finite number of outcomes. Example: has and has , both below .
Go deeper How a best code is built, and why it stays within one bit of the entropy
Huffman’s method. In 1952 David Huffman described a way to build a best prefix code for given probabilities. Repeat: take the two least likely items and merge them into one item whose probability is their sum. For the merges are , then , then , and the number of merges each outcome sits under is its code length: . For the merges are and then , giving lengths and an average of bits, against and against bits for a fixed code.
Why the average is below . Give an outcome of probability a code length , its surprise rounded up. A prefix code with such lengths exists, because the lengths satisfy the Kraft inequality . Since , the average length is below . The lower bound for every prefix code follows from the non-negativity of the KL divergence (P1.E4).
Where entropy shows up in machine learning
The uncertainty of a prediction. A classifier outputs a distribution over classes, and its entropy measures how spread out that distribution is. For three classes: has bits, has and the uniform has the maximum . Uncertainty sampling in active learning sends the examples with the highest entropy to a human for labelling (P12.2). Entropy measures how unsure the model is, not whether it is right. A confident wrong model has low entropy, and the probabilities of many neural networks are not well calibrated.
Decision trees (P3.B3). A tree splits the data to make the labels in each group more predictable. Take examples, positive and negative: bit. A split into two groups of , one with positives and negative and the other with and , leaves each group with bits. The average entropy after the split, weighted by group size, is . The information gain is the entropy before minus the weighted average after: bits. A perfect split into pure groups has gain bit. An entropy-based tree picks the split with the largest gain (many libraries use the Gini index by default instead, P3.B3).
Temperature. A language model turns logits into probabilities with a softmax (P3.A8). Dividing the logits by a temperature first changes the entropy (P1.D9 shows how to sample from such probabilities, and P10.A5 covers decoding in full). For logits :
| Probabilities | (bits) | |
|---|---|---|
Low temperature sharpens the distribution (the entropy goes toward and the output is almost always the top token), and high temperature flattens it (the entropy goes toward , which is here; at it already agrees to three decimals). The ranking of the tokens does not change, and the entropy does.
Regularization and exploration. A one-hot label has entropy . Label smoothing (P4.17) mixes it with the uniform distribution: with classes and a smoothing amount , using the common definition times the one-hot vector plus on every class, the target becomes for the true class and for each other class, with entropy bits. A related idea is the maximum-entropy principle: when you know only some constraints, choose the highest-entropy distribution that satisfies them. With no constraint it is the uniform distribution. Some reinforcement-learning methods add an entropy bonus so that the policy keeps trying different actions (reinforcement learning is Part 9).
Compression. The code lengths above are the link between probabilities and storage: a good model of the data is a good compressor.
Go deeper Entropy of a continuous variable
For a variable with a density , the same formula with an integral gives the differential entropy . It is not the limit of the discrete entropy and it behaves differently. It can be negative, and it changes when you change the units. For a Gaussian with standard deviation , bits, which is for and for (in nats, for ). A uniform density on an interval of length has , which is for . Multiplying by adds : converting metres to centimetres adds bits. The reason is that a density is not a probability (P1.D2). Among all distributions with a given variance, the Gaussian has the largest differential entropy. Differences between densities, such as the KL divergence, do not have the units problem (P1.E4).
Go deeper Estimating entropy from data
If you do not know , you can count outcomes in a sample and plug the frequencies into the formula. That estimate is on average too low, because a small sample misses rare outcomes and looks more predictable than the source. In a seeded simulation of a uniform choice among outcomes (true entropy bits), the average estimate from samples was about bits and from samples about bits. So with little data an entropy estimate should be read with care.
Try it
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The first block prints bit for the fair coin, for the coin, for the coin, for the die and for , with and for two of them. Adding two outcomes with changes nothing. The average surprise of simulated flips is , close to the entropy (it differs by chance and gets closer with more flips). The code with lengths averages exactly bits, and the pair code gives bits per flip. The temperature table matches the one above: , and bits for , and for . The last line prints nan for the naive formula and with the filter. Challenge: change the coin to and check that the average surprise of every flip is exactly bit.
Intuition, math and code at a glance
Intuition
Entropy is how unpredictable a source is, on average. Take each outcome’s surprise, weight it by how often it happens and add. Among two-outcome sources a fair coin is the hardest to predict, and a certain outcome is no trouble at all. Entropy is also the number of yes/no questions you need on average, and the fewest bits per symbol a lossless code can use.
Math
Key values and bounds:
Facts to remember:
-
when and are independent
-
exactly when one outcome is certain, and exactly for the uniform distribution
-
counts as , so outcomes with add nothing
-
a lossless prefix code has an average length of at least bits, and an optimal code has less than
-
is the effective number of outcomes
Code
Compute the entropy of a distribution with NumPy, skipping zeros.
import numpy as np
def entropy_bits(p):
p = np.asarray(p, dtype=float)
p = p[p > 0]
return -(p * np.log2(p)).sum()
print(entropy_bits([0.9, 0.1])) # about 0.469 bits
print(entropy_bits([0.25] * 4)) # 2.0 bitsCommon mistakes
Check your understanding
A coin lands heads with probability . What is its entropy?
Entropy is the average surprise: bits. The value is the surprise of heads alone, and is the surprise of tails alone, so each leaves out the other outcome and the weights. The value bit is the entropy of a fair coin, which is the most unpredictable two-outcome source and so has higher entropy than this skewed coin.
Which distribution over four outcomes has the largest entropy?
With a finite number of outcomes the uniform distribution has the largest entropy, bits. The distribution has bits and has . The distribution with all the probability on one outcome has bits, because nothing is uncertain.
Symbols A, B, C, D appear independently with probabilities . What is the smallest possible average length, in bits per symbol, of a lossless prefix code for them?
The entropy is bits and the code reaches it, so nothing shorter is possible. A fixed code with bits per symbol works but is not the shortest. The values and are below the entropy, so no lossless code can reach them on average.
A distribution over outcomes has entropy . A fifth outcome with probability is added and the rest are kept. What happens to the entropy?
The term goes to as goes to , so a zero-probability outcome adds nothing, and the other terms are unchanged. The bound is only reached by a uniform distribution over five outcomes, and this one is not uniform. The surprise of the new outcome is infinite, but it is multiplied by a probability of and the product counts as . The probabilities of the other outcomes are not changed by adding it.
The logits of a language model are divided by a temperature before the softmax. What does raising the temperature from to do to the entropy of the next-token distribution?
Dividing by a larger temperature makes the logits closer together, so the distribution flattens toward uniform and the entropy rises (for logits from to bits). The top token does get less likely, but that is the flattening, and flatter means more entropy, not less. The ranking stays the same, but entropy depends on the probabilities and not on the ranking. A single token with all the probability is what happens as the temperature goes toward .
Exercises
- Find the entropy, in bits and in nats, of a coin with .
Show answer
bits, which is nats. - A source has three outcomes with probabilities . Find its entropy and its effective number of outcomes.
Show answer
bits. The effective number is , a little below the outcomes. - Find the entropy of a fair -sided die and of a uniform random choice among items.
Show answer
bits and bits. The second is the twenty questions of P1.E1. - Two independent fair coins and an independent fair die are rolled together. What is the entropy of the three results?
Show answer
Entropies of independent variables add: bits, which is also . - A source has probabilities . Find , then the average length of the prefix code and of a fixed two-bit code.
Show answer
bits. The code has lengths and an average of bits. The fixed code uses bits. The average length is above and less than , as the theorem says. - A group of emails has spam and not spam. A word splits it into one group with spam and not spam, and another with spam and not spam. Find the information gain.
Show answer
The group entropy before is bit. Each part has probabilities and , so bits. The parts are the same size, so the weighted average is and the gain is bits. - A model has logits for two tokens. Find the entropy of the softmax at and at .
Show answer
At the probabilities are and and bits. At the logits are , the probabilities are and , and bits. The higher temperature has the higher entropy. - Label smoothing with classes and amount turns a one-hot target into . Find the new target and its entropy.
Show answer
The true class gets and each other class gets . bits (the one-hot target has ). - Why are a coin with and one with equally unpredictable?
Show answer
Both have probabilities and , only with the labels swapped. Entropy depends on the probabilities and not on which outcome carries which, so both have bits and . - Find the differential entropy in bits of a Gaussian with and of one with , and say why a negative answer is possible here but not for a discrete variable.
Show answer
gives bits for (the value for minus ) and bits for . A narrow density can be larger than , so can be negative, while a probability is at most , so a discrete surprise is never negative.
Next: P1.E3 averages the surprise of the true labels under a model’s probabilities and gets cross-entropy, the classification loss, which equals the entropy when the model is exactly right. P1.E4 measures the extra cost of using the wrong model, and P1.E5 covers mutual information, joint and conditional entropy, and perplexity.