Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 1: Math FoundationsInformation Theory

Entropy

P1.E235 min●○○ BeginnerReviewed Dec 1, 2026

Why this matters for machine learning

Entropy turns the spread of a probability distribution into one number: the average surprise, or how many yes/no questions it takes on average to learn the outcome. Machine learning uses it to measure how unsure a model is, how much a question tells you, and how far a model is from the truth.

  • A classifier or language model outputs a probability distribution, and its entropy says how unsure it is. Active learning asks humans to label the examples where the model’s entropy is highest. (P12.2: Data collection and labeling, coming soon)
  • Decision trees choose the split that lowers the entropy of the labels the most, called the information gain. (P3.B3: Decision trees, coming soon)
  • Temperature changes the entropy of a language model’s next-token distribution, which is why a high temperature gives more varied text. (P10.A5: Decoding strategies, coming soon)
  • For a source of independent symbols with known probabilities, entropy is the lowest average number of bits per symbol that lossless compression can use, and it is the baseline that cross-entropy and KL divergence are measured against. (P1.E3: Cross-entropy)

Before this: Information and surprise, Common distributions, Expectation and variance

After this lesson you can

  • Define the entropy of a discrete distribution as the average surprise, H(X)=E[−log⁡p(X)]=−∑xp(x)log⁡p(x)H(X)=\mathbb{E}[-\log p(X)]=-\sum_x p(x)\log p(x), and compute it in bits and in nats, using the convention 0log⁡0=00\log0=0
  • Compute the entropy of a coin, a die and a categorical distribution, sketch the binary entropy curve H(p)H(p), and say when entropy is 00 and when it is largest (log⁡2K\log_2K for the uniform distribution over KK outcomes)
  • Explain entropy as the number of yes/no questions needed on average and as the smallest average length of a lossless code, using the code 1,01,001,0001, 01, 001, 000 for probabilities 12,14,18,18\frac12,\frac14,\frac18,\frac18, and read 2H2^H as the effective number of outcomes
  • Recognise entropy in machine learning: the uncertainty of a prediction, the information gain of a decision-tree split, and the effect of temperature on the next-token distribution

Two coins sit on the table. One is fair. The other lands heads 9999 times out of 100100. 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 −log⁡p-\log p. 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 xx with probability p(x)p(x). The surprise of that outcome is I(x)=−log⁡p(x)I(x)=-\log p(x) (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): E[g(X)]=∑xp(x) g(x)\mathbb{E}[g(X)]=\sum_x p(x)\,g(x), with g(x)=−log⁡p(x)g(x)=-\log p(x). The result is the entropy of XX:

H(X)=E[−log⁡p(X)]=−∑xp(x)log⁡p(x).\begin{aligned} H(X)&=\mathbb{E}\bigl[-\log p(X)\bigr]\\ &=-\sum_x p(x)\log p(x). \end{aligned}

With log⁡2\log_2 the unit is the bit, and with ln⁡\ln it is the nat (P1.E1). The two differ by a constant: Hnats=Hbits×ln⁡2H_{\text{nats}}=H_{\text{bits}}\times\ln2.

A coin with p=0.9p=0.9 for heads. Heads has surprise −log⁡20.9=0.152-\log_2 0.9=0.152 bits and tails has −log⁡20.1=3.322-\log_2 0.1=3.322 bits. Tails is much more surprising, but it happens only one time in ten. Weighting by the probabilities:

H=0.9×0.152+0.1×3.322=0.137+0.332=0.469 bits.\begin{aligned} H&=0.9\times0.152+0.1\times3.322\\ &=0.137+0.332=0.469\text{ bits}. \end{aligned}

For a fair coin both surprises are 11 bit, so H=1H=1 bit. For p=0.99p=0.99, heads costs 0.01450.0145 bits and tails costs 6.6446.644 bits, and H=0.99×0.0145+0.01×6.644=0.0144+0.0664=0.0808H=0.99\times0.0145+0.01\times6.644=0.0144+0.0664=0.0808 bits. That is the number P1.E1 promised.

ppHeadsTailsHH (bits)HH (nats)
0.50.51111110.6930.693
0.90.90.1520.1523.3223.3220.4690.4690.3250.325
0.990.990.01450.01456.6446.6440.08080.08080.05600.0560
1100none0000

In the table, pp 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 11. Under each bar you see its surprise and its share of the entropy, and the meter adds the shares up.

Reshape a distribution, watch the entropy

00.510.5A0.25B0.125C0.125D

Vertical: probability. Letters are the outcomes. Dragging one bar rescales the others so that the probabilities always add up to 1.

Surprise −log₂ p in bits (a bar with p = 0 would be infinitely surprising)
1233
Contribution p × surprise, in bits (these add up to H)
0.50.50.3750.375
Entropy meter, in bits (full width is 3 bits; the line marks the maximum log₂ 4 = 2)
entropy H = 1.75 bits
in nats: 1.213
maximum log₂ K = 2 bits
effective outcomes 2H = 3.36

H = 1.75 bits, which is 88% of the maximum log₂ 4 = 2. The flatter the bars, the closer to the maximum; the more one bar dominates, the closer to 0. Every probability is a power of ½, so each surprise is a whole number of bits and the best code spends exactly H bits per symbol on average.

Drag on the chart (it snaps to 0.01), or Tab to a bar and use the arrow keys (0.01), Page Up and Page Down (0.1), Home (0) and End (1). Raising K adds outcomes with p = 0. Lowering K removes the last ones and rescales the rest. Probabilities and surprises are rounded for display.

Entropy of a distribution over K outcomes. The blue bars are probabilities, which you can drag, and they always add up to 1. Under each bar are its surprise (minus log base 2 of p, in bits) and its contribution p times surprise, which add up to the entropy H. The meter shows H as a sum of those contributions on a fixed scale of 0 to 3 bits, with a dashed line at the largest possible value, log base 2 of K. Also shown are H in nats and 2 to the power H, the effective number of outcomes. The second panel shows the entropy H(p) of a two-outcome coin as p changes.

What to try:

  • Certain. Press “One certain”: one bar has p=1p=1, the others 00, and H=0H=0. Nothing is uncertain.
  • Uniform. Press “Uniform”: all four bars are 0.250.25, each surprise is 22 bits and H=2=log⁡24H=2=\log_2 4, at the dashed line.
  • Coin. Press “Coin 0.9 / 0.1”: H=0.469H=0.469. Then drag the first bar toward 0.50.5 and watch the entropy rise to 11.
  • Halves. Press “Halves”: the probabilities 12,14,18,18\frac12,\frac14,\frac18,\frac18 have surprises 1,2,3,31,2,3,3 and contributions 0.5,0.5,0.375,0.3750.5,0.5,0.375,0.375, which add to 1.751.75 bits.
  • Zeros. Raise KK from 44 to 88 with the halves in place: the new bars have p=0p=0, they add 00 and HH does not change.
  • Open the second panel and drag pp: the entropy of a coin peaks at p=0.5p=0.5, is symmetric around it, and falls to 00 at both ends.

The binary entropy function

For a source with two outcomes, with probabilities pp and 1−p1-p, entropy is a function of one number:

H(p)=−plog⁡2p−(1−p)log⁡2(1−p).\begin{aligned} H(p)&=-p\log_2p\\ &\quad-(1-p)\log_2(1-p). \end{aligned}

Its shape (second panel of the widget) says most of what matters. It is 00 at p=0p=0 and p=1p=1, where the outcome is certain. It rises to a single peak of exactly 11 bit at p=12p=\frac12. And it is symmetric: H(p)=H(1−p)H(p)=H(1-p), because a coin that lands heads 99%99\% of the time is exactly as predictable as one that lands tails 99%99\% of the time. Both have H=0.0808H=0.0808. Calculus (P1.C2) confirms the peak: the slope of H(p)H(p) is log⁡21−pp\log_2\frac{1-p}{p}, which is 00 at p=12p=\frac12, positive before it and negative after it. Each term on its own, −pln⁡p-p\ln p in nats, peaks earlier, at p=1e=0.368p=\frac1{\mathrm{e}}=0.368 (the example in P1.C2); the two terms together peak at 12\frac12. The curve is steep near the ends: moving from p=0.5p=0.5 to p=0.9p=0.9 removes more than half of the entropy (1→0.4691\to0.469).

The convention 0log⁡0=00\log0=0. The formula contains plog⁡pp\log p for every outcome, and for p=0p=0 the log is not defined. The convention is to count such a term as 00, and it is not arbitrary. As pp shrinks, −plog⁡2p-p\log_2p goes to 00: it is 0.06640.0664 at p=0.01p=0.01, 0.009970.00997 at p=0.001p=0.001 and 0.000020.00002 at p=10−6p=10^{-6}. An outcome that never happens should not change how uncertain the source is, so adding impossible outcomes leaves HH 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 KK outcomes is the hardest to predict? The one where all outcomes are equally likely. With p=1Kp=\frac1K for every outcome each surprise is log⁡2K\log_2K, so the average is

H=log⁡2K.H=\log_2K.

A fair coin gives log⁡22=1\log_2 2=1 bit, a fair die gives log⁡26=2.585\log_2 6=2.585 bits (the surprise of every face), and a uniform choice among 10241024 items gives 1010 bits, the ten questions of P1.E1. For a finite number KK of outcomes, no distribution does better:

0≤H(X)≤log⁡2K.0\le H(X)\le\log_2K.

The lower end holds because each surprise is not negative, and it is reached only when one outcome has probability 11 (the others have probability 00). 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 0.7,0.2,0.10.7,0.2,0.1. The terms −plog⁡2p-p\log_2p are 0.3600.360, 0.4640.464 and 0.3320.332, so H=1.157H=1.157 bits, below log⁡23=1.585\log_2 3=1.585. In nats it is 0.8020.802.

The effective number of outcomes. A fair choice among NN options has H=log⁡2NH=\log_2N, so N=2HN=2^H. Turn it around: for any distribution, 2H2^H is the size of the uniform distribution with the same entropy. A fair die gives 66. The coin with p=0.9p=0.9 gives 20.469=1.382^{0.469}=1.38, about as unsure as 1.381.38 equally likely options. The categorical (0.7,0.2,0.1)(0.7,0.2,0.1) gives 21.157=2.232^{1.157}=2.23 against 33 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 −log⁡p-\log p is at least 00 when p≤1p\le1.
  • It is 00 exactly when one outcome is certain.
  • For KK outcomes it is at most log⁡2K\log_2K, with equality exactly for the uniform distribution.
  • It depends on the probabilities, not on the values. The outcomes can be heads and tails, 00 and 11, or 00 and 10001000. The entropy is 11 bit for a fair choice in all cases. So entropy is not the variance: the variance of a fair choice between 00 and 10001000 is huge and the variance between 00 and 11 is small, yet their entropies are equal.
  • Outcomes with p=0p=0 change nothing.
  • For independent variables the entropies add. Take the coin with p=0.9p=0.9 and a fair die, independent of each other. The pair has 1212 outcomes with probabilities 0.96=0.15\frac{0.9}{6}=0.15 and 0.16=0.0167\frac{0.1}{6}=0.0167, and H(X,Y)=H(X)+H(Y)=0.469+2.585=3.054H(X,Y)=H(X)+H(Y)=0.469+2.585=3.054 bits. This is the average version of the rule from P1.E1 that surprises of independent events add. A run of nn independent flips of the 0.90.9 coin has 0.469 n0.469\,n bits of entropy.
  • For dependent variables the joint entropy is smaller. Let a fair coin XX be copied exactly into YY. The pair has two equally likely outcomes, so H(X,Y)=1H(X,Y)=1 bit, not 1+1=21+1=2. Let YY instead copy XX but be wrong one time in ten, so the four pairs have probabilities 0.45,0.05,0.05,0.450.45,0.05,0.05,0.45. Then H(X,Y)=1.469<2H(X,Y)=1.469<2. In general H(X,Y)≤H(X)+H(Y)H(X,Y)\le H(X)+H(Y), 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 12,14,18,18\frac12,\frac14,\frac18,\frac18. 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 11 question, B takes 22, and C and D take 33 each. On average,

12⋅1+14⋅2+18⋅3+18⋅3=1.75 questions,\begin{aligned} &\tfrac12\cdot1+\tfrac14\cdot2+\tfrac18\cdot3+\tfrac18\cdot3\\ &=1.75\text{ questions}, \end{aligned}

which is exactly the entropy H=1.75H=1.75 bits. Each outcome took as many questions as its surprise (11, 22, 33, 33 bits).

Write the answers as bits (yes is 11 and no is 00) and the questions become a code: A is 11, B is 0101, C is 001001 and D is 000000. 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 22 bits per symbol, so this code saves 0.250.25 bits per symbol. Its average length, 1.751.75, equals HH.

OutcomeppSurprise (bits)CodeCode length
A12\frac12111111
B14\frac1422010122
C18\frac183300100133
D18\frac183300000033

This is a limit, not a coincidence. Shannon’s source coding theorem (1948) says, for symbols drawn independently from the distribution pp: no lossless prefix code can have an average length below HH bits per symbol, and a best possible code has an average length below H+1H+1. Compressing blocks of nn symbols at a time brings the average per symbol within 1n\frac1n bits of HH. So the entropy is the compression limit.

When the probabilities are not powers of 12\frac12, the limit is not met by coding one symbol at a time. The coin with p=0.9p=0.9 has H=0.469H=0.469, but a codeword needs at least one bit, so coding each flip alone costs 11 bit. Code pairs of flips instead: HH has probability 0.810.81, HT and TH have 0.090.09 each and TT has 0.010.01. The code 00, 1010, 110110, 111111 has an average length 0.81+0.18+0.27+0.03=1.290.81+0.18+0.27+0.03=1.29 bits per pair, which is 0.6450.645 per flip. Triples bring it to about 0.5330.533 per flip, still above 0.4690.469 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 qq when the truth is pp, the cost per symbol rises above HH 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 log⁡21p\log_2\frac1p over the outcomes with p>0p>0. Say there are nn of them, with n≤Kn\le K. 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

H=∑p>0plog⁡21p≤log⁡2(∑p>0p⋅1p)=log⁡2n≤log⁡2K.\begin{aligned} H&=\sum_{p>0}p\log_2\frac1p\\ &\le\log_2\Bigl(\sum_{p>0}p\cdot\frac1p\Bigr)\\ &=\log_2n\le\log_2K. \end{aligned}

Equality in the first step needs 1p\frac1p to be the same for every outcome that can happen, so all the nonzero probabilities are equal. Equality in the second step needs n=Kn=K, so none of the probabilities is 00. Both hold only for the uniform distribution. The proof needs a finite number of outcomes. Example: (0.7,0.1,0.1,0.1)(0.7,0.1,0.1,0.1) has H=1.357H=1.357 and (0.4,0.3,0.2,0.1)(0.4,0.3,0.2,0.1) has H=1.846H=1.846, both below log⁡24=2\log_2 4=2.

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 12,14,18,18\frac12,\frac14,\frac18,\frac18 the merges are 18+18=14\frac18+\frac18=\frac14, then 14+14=12\frac14+\frac14=\frac12, then 12+12=1\frac12+\frac12=1, and the number of merges each outcome sits under is its code length: 1,2,3,31,2,3,3. For (0.7,0.2,0.1)(0.7,0.2,0.1) the merges are 0.2+0.1=0.30.2+0.1=0.3 and then 0.7+0.3=10.7+0.3=1, giving lengths 1,2,21,2,2 and an average of 1.31.3 bits, against H=1.157H=1.157 and against 22 bits for a fixed code.

Why the average is below H+1H+1. Give an outcome of probability pp a code length ℓ=⌈−log⁡2p⌉\ell=\lceil-\log_2p\rceil, its surprise rounded up. A prefix code with such lengths exists, because the lengths satisfy the Kraft inequality ∑2−ℓ≤1\sum2^{-\ell}\le1. Since ℓ<−log⁡2p+1\ell<-\log_2p+1, the average length is below ∑p(−log⁡2p+1)=H+1\sum p(-\log_2p+1)=H+1. The lower bound HH 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: (0.9,0.05,0.05)(0.9,0.05,0.05) has H=0.569H=0.569 bits, (0.6,0.3,0.1)(0.6,0.3,0.1) has 1.2951.295 and the uniform (13,13,13)(\frac13,\frac13,\frac13) has the maximum log⁡23=1.585\log_2 3=1.585. 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 1010 examples, 55 positive and 55 negative: H=1H=1 bit. A split into two groups of 55, one with 44 positives and 11 negative and the other with 11 and 44, leaves each group with H(0.8)=0.722H(0.8)=0.722 bits. The average entropy after the split, weighted by group size, is 0.7220.722. The information gain is the entropy before minus the weighted average after: 1−0.722=0.2781-0.722=0.278 bits. A perfect split into pure groups has gain 11 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 zz into probabilities with a softmax (P3.A8). Dividing the logits by a temperature TT first changes the entropy (P1.D9 shows how to sample from such probabilities, and P10.A5 covers decoding in full). For logits (2,1,0)(2,1,0):

TTProbabilitiesHH (bits)
0.50.50.867, 0.117, 0.0160.867,\ 0.117,\ 0.0160.6360.636
110.665, 0.245, 0.0900.665,\ 0.245,\ 0.0901.2011.201
220.506, 0.307, 0.1860.506,\ 0.307,\ 0.1861.4721.472
1001000.337, 0.333, 0.3300.337,\ 0.333,\ 0.3301.5851.585

Low temperature sharpens the distribution (the entropy goes toward 00 and the output is almost always the top token), and high temperature flattens it (the entropy goes toward log⁡2K\log_2K, which is 1.5851.585 here; at T=100T=100 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 00. Label smoothing (P4.17) mixes it with the uniform distribution: with K=10K=10 classes and a smoothing amount ε=0.1\varepsilon=0.1, using the common definition (1−ε)(1-\varepsilon) times the one-hot vector plus ε/K\varepsilon/K on every class, the target becomes 0.910.91 for the true class and 0.010.01 for each other class, with entropy 0.7220.722 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 ff, the same formula with an integral gives the differential entropy h(X)=−∫f(x)log⁡f(x) dxh(X)=-\int f(x)\log f(x)\,dx. 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 σ\sigma, h=12log⁡2(2πe σ2)h=\frac12\log_2(2\pi\mathrm{e}\,\sigma^2) bits, which is 2.0472.047 for σ=1\sigma=1 and −1.275-1.275 for σ=0.1\sigma=0.1 (in nats, 12ln⁡(2πe σ2)=1.419\frac12\ln(2\pi\mathrm{e}\,\sigma^2)=1.419 for σ=1\sigma=1). A uniform density on an interval of length aa has h=log⁡2ah=\log_2a, which is −1-1 for a=12a=\frac12. Multiplying XX by cc adds log⁡2∣c∣\log_2|c|: converting metres to centimetres adds log⁡2100=6.644\log_2100=6.644 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 pp, 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 88 outcomes (true entropy 33 bits), the average estimate from 88 samples was about 2.252.25 bits and from 100100 samples about 2.952.95 bits. So with little data an entropy estimate should be read with care.

Try it

Try it: entropy, average surprise, code lengths and temperature

Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).

The first block prints 11 bit for the fair coin, 0.4690.469 for the 0.90.9 coin, 0.08080.0808 for the 0.990.99 coin, 2.5852.585 for the die and 1.15681.1568 for (0.7,0.2,0.1)(0.7,0.2,0.1), with 2H=1.3842^H=1.384 and 2.2302.230 for two of them. Adding two outcomes with p=0p=0 changes nothing. The average surprise of 100,000100{,}000 simulated flips is 0.4660.466, close to the entropy 0.4690.469 (it differs by chance and gets closer with more flips). The code with lengths 1,2,3,31,2,3,3 averages exactly 1.751.75 bits, and the pair code gives 0.6450.645 bits per flip. The temperature table matches the one above: 0.6360.636, 1.2011.201 and 1.4721.472 bits for T=0.5,1,2T=0.5,1,2, and 1.5851.585 for T=100T=100. The last line prints nan for the naive formula and 1.01.0 with the filter. Challenge: change the coin to p=0.5p=0.5 and check that the average surprise of every flip is exactly 11 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

H(X)=−∑xp(x)log⁡p(x)=E[−log⁡p(X)]\begin{aligned} H(X)&=-\sum_x p(x)\log p(x)\\ &=\mathbb{E}\bigl[-\log p(X)\bigr] \end{aligned}

Key values and bounds:

H(p)=−plog⁡2p−(1−p)log⁡2(1−p)0≤H(X)≤log⁡2KHnats=Hbits×ln⁡2\begin{aligned} H(p)&=-p\log_2p\\ &\quad-(1-p)\log_2(1-p)\\ 0&\le H(X)\le\log_2K\\ H_{\text{nats}}&=H_{\text{bits}}\times\ln2 \end{aligned}

Facts to remember:

  • H(X,Y)=H(X)+H(Y)H(X,Y)=H(X)+H(Y) when XX and YY are independent

  • H=0H=0 exactly when one outcome is certain, and H=log⁡2KH=\log_2K exactly for the uniform distribution

  • 0log⁡00\log0 counts as 00, so outcomes with p=0p=0 add nothing

  • a lossless prefix code has an average length of at least HH bits, and an optimal code has less than H+1H+1

  • 2H2^H 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 bits

Common mistakes

Check your understanding

  1. A coin lands heads with probability 0.90.9. What is its entropy?

  2. Which distribution over four outcomes has the largest entropy?

  3. Symbols A, B, C, D appear independently with probabilities 12,14,18,18\frac12,\frac14,\frac18,\frac18. What is the smallest possible average length, in bits per symbol, of a lossless prefix code for them?

  4. A distribution over 44 outcomes has entropy HH. A fifth outcome with probability 00 is added and the rest are kept. What happens to the entropy?

  5. The logits of a language model are divided by a temperature before the softmax. What does raising the temperature from 11 to 22 do to the entropy of the next-token distribution?

Exercises

  1. Find the entropy, in bits and in nats, of a coin with P(heads)=0.8P(\text{heads})=0.8.
    Show answer−0.8log⁡20.8−0.2log⁡20.2=0.258+0.464=0.722-0.8\log_2 0.8-0.2\log_2 0.2=0.258+0.464=0.722 bits, which is 0.722×ln⁡2=0.5000.722\times\ln2=0.500 nats.
  2. A source has three outcomes with probabilities 12,14,14\frac12,\frac14,\frac14. Find its entropy and its effective number of outcomes.
    Show answerH=12⋅1+14⋅2+14⋅2=1.5H=\frac12\cdot1+\frac14\cdot2+\frac14\cdot2=1.5 bits. The effective number is 21.5=2.832^{1.5}=2.83, a little below the 33 outcomes.
  3. Find the entropy of a fair 2020-sided die and of a uniform random choice among 1,000,0001{,}000{,}000 items.
    Show answerlog⁡220=4.322\log_2 20=4.322 bits and log⁡2106=19.93\log_2 10^6=19.93 bits. The second is the twenty questions of P1.E1.
  4. Two independent fair coins and an independent fair die are rolled together. What is the entropy of the three results?
    Show answerEntropies of independent variables add: 1+1+2.585=4.5851+1+2.585=4.585 bits, which is also log⁡2(2⋅2⋅6)=log⁡224\log_2(2\cdot2\cdot6)=\log_2 24.
  5. A source has probabilities 0.7,0.2,0.10.7,0.2,0.1. Find HH, then the average length of the prefix code 0,10,110,10,11 and of a fixed two-bit code.
    Show answerH=1.157H=1.157 bits. The code 0,10,110,10,11 has lengths 1,2,21,2,2 and an average of 0.7+0.4+0.2=1.30.7+0.4+0.2=1.3 bits. The fixed code uses 22 bits. The average length 1.31.3 is above HH and less than H+1H+1, as the theorem says.
  6. A group of 88 emails has 44 spam and 44 not spam. A word splits it into one group with 33 spam and 11 not spam, and another with 11 spam and 33 not spam. Find the information gain.
    Show answerThe group entropy before is 11 bit. Each part has probabilities 0.750.75 and 0.250.25, so H=0.811H=0.811 bits. The parts are the same size, so the weighted average is 0.8110.811 and the gain is 1−0.811=0.1891-0.811=0.189 bits.
  7. A model has logits (3,0)(3,0) for two tokens. Find the entropy of the softmax at T=1T=1 and at T=3T=3.
    Show answerAt T=1T=1 the probabilities are 0.9530.953 and 0.0470.047 and H=0.275H=0.275 bits. At T=3T=3 the logits are (1,0)(1,0), the probabilities are 0.7310.731 and 0.2690.269, and H=0.840H=0.840 bits. The higher temperature has the higher entropy.
  8. Label smoothing with K=4K=4 classes and amount ε=0.2\varepsilon=0.2 turns a one-hot target into (1−ε)⋅one-hot+ε/K(1-\varepsilon)\cdot\text{one-hot}+\varepsilon/K. Find the new target and its entropy.
    Show answerThe true class gets 0.8+0.05=0.850.8+0.05=0.85 and each other class gets 0.050.05. H=0.85log⁡210.85+3⋅0.05log⁡210.05=0.199+0.648=0.848H=0.85\log_2\frac1{0.85}+3\cdot0.05\log_2\frac1{0.05}=0.199+0.648=0.848 bits (the one-hot target has 00).
  9. Why are a coin with P(heads)=0.99P(\text{heads})=0.99 and one with P(heads)=0.01P(\text{heads})=0.01 equally unpredictable?
    Show answerBoth have probabilities 0.990.99 and 0.010.01, only with the labels swapped. Entropy depends on the probabilities and not on which outcome carries which, so both have H=0.0808H=0.0808 bits and H(p)=H(1−p)H(p)=H(1-p).
  10. Find the differential entropy in bits of a Gaussian with σ=0.5\sigma=0.5 and of one with σ=0.1\sigma=0.1, and say why a negative answer is possible here but not for a discrete variable.
    Show answer12log⁡2(2πeσ2)\frac12\log_2(2\pi\mathrm{e}\sigma^2) gives 1.0471.047 bits for σ=0.5\sigma=0.5 (the value 2.0472.047 for σ=1\sigma=1 minus 11) and −1.275-1.275 bits for σ=0.1\sigma=0.1. A narrow density can be larger than 11, so −log⁡f-\log f can be negative, while a probability is at most 11, 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.

Key takeaways

  • The entropy of a discrete random variable is the average surprise: H(X)=E[−log⁡p(X)]=−∑xp(x)log⁡p(x)H(X)=\mathbb{E}[-\log p(X)]=-\sum_x p(x)\log p(x). It is a property of the whole distribution, not of one outcome, and it is measured in bits (log⁡2\log_2) or nats (ln⁡\ln). Outcomes with p=0p=0 add 00 (the convention 0log⁡0=00\log0=0).
  • A fair coin has H=1H=1 bit. A coin with p=0.9p=0.9 has 0.4690.469 bits and one with p=0.99p=0.99 has 0.08080.0808 bits, because the likely outcome is rarely surprising. The binary entropy H(p)=−plog⁡2p−(1−p)log⁡2(1−p)H(p)=-p\log_2p-(1-p)\log_2(1-p) is 00 at p=0p=0 and p=1p=1 and peaks at 11 bit at p=12p=\frac12.
  • For KK outcomes, 0≤H≤log⁡2K0\le H\le\log_2K. H=0H=0 exactly when one outcome is certain, and H=log⁡2KH=\log_2K exactly when all KK are equally likely. The entropy depends only on the probabilities, not on the labels or values of the outcomes. For independent variables the entropies add; for dependent ones the joint entropy is smaller.
  • Entropy is the limit of lossless compression. For symbols drawn independently from pp, no prefix code has an average length below HH bits per symbol, and an optimal code comes within 11 bit of it (Shannon's source coding theorem). When every probability is a power of 12\frac12 the limit is reached exactly: 12,14,18,18\frac12,\frac14,\frac18,\frac18 gives 1.751.75 bits.
  • 2H2^H is the effective number of outcomes: the size of the uniform distribution with the same entropy. In machine learning, entropy measures the uncertainty of a prediction, drives decision-tree splits (information gain), grows with the temperature of a softmax, and is the baseline for cross-entropy (P1.E3) and KL divergence (P1.E4).
Found a mistake? Tell us