Type at least 2 letters. Enter opens the first result, Esc closes.

    Information Theory · Lesson 1 · Surprise and entropy

    Surprise, bits and entropy

    Beginner 50 min 4 interactive figures 4 videos Colab notebook

    Before this lesson: discrete random variables and expectation (the probability track) and the rules of logarithms (Foundations 04). This is the first lesson of the track. Time: about 50 minutes, plus the notebook.


    Why this matters #

    A classifier or a language model is trained with the cross-entropy loss: the average surprisal of the true label (or the next token) under the model. The entropy of the data is the lowest value this loss can reach (lesson 04). Entropy is also the smallest average number of bits per symbol of any lossless compressor (lesson 05). Beyond losses, entropy appears directly in many algorithms: decision trees choose splits that lower the entropy of the labels, active learning asks for labels where the model's prediction has high entropy, soft actor-critic (SAC) rewards policies with high entropy, and the temperature of a language model controls the entropy of the next-token distribution. Every later lesson of this track builds on the definitions here.

    1. Predict first #

    2. The picture #

    Surprise is measured with a logarithm #

    Think of an outcome xx with probability p(x)p(x). If p(x)=1p(x) = 1, seeing xx tells you nothing new. If p(x)p(x) is small, seeing xx is surprising and tells you a lot. The surprisal (also called the information content or self-information) of xx is

    −log⁡2p(x)bits.-\log_2 p(x) \quad \text{bits}.
    Outcome p(x)p(x) Surprisal −log⁡2p(x)-\log_2 p(x)
    a sure event 11 00 bits
    heads with a fair coin 1/21/2 11 bit
    two heads with two fair coins 1/41/4 22 bits
    one card from 8 equally likely cards 1/81/8 33 bits
    a six with a fair die 1/61/6 2.5852.585 bits
    a 1-in-1000 event 1/10001/1000 9.9669.966 bits

    Why a logarithm? Take two independent events, for example two coin flips. Their probabilities multiply: two heads have probability 12⋅12=14\frac12 \cdot \frac12 = \frac14. The information should add: one bit for each flip, two bits in total. The logarithm is the function that turns products into sums:

    −log⁡2(pq)=(−log⁡2p)+(−log⁡2q).-\log_2(pq) = (-\log_2 p) + (-\log_2 q).

    A consequence: halving a probability adds exactly one bit, because −log⁡2(p/2)=−log⁡2p+1-\log_2(p/2) = -\log_2 p + 1.

    Interactive figure: loading…

    Slide pp and watch the yellow point move on the blue curve −log⁡2p-\log_2 p. Press Halve p a few times: each press adds exactly one bit. The faint point at p/2p/2 is always one bit higher. Switch to two independent outcomes: the surprisal of "both happen" (probability pqpq) is the sum of the two surprisals. The log scale axis turns the curve into a straight line.

    The question game #

    A friend picks one of 8 cards, all equally likely. You may ask only yes/no questions. Ask "Is it one of cards 1–4?": the answer removes half of the cards. Two more halving questions find the card. So you need 3=log⁡283 = \log_2 8 questions. In general, finding one of 2n2^n equally likely items takes nn questions. With 20 questions you can find one item among 220≈2^{20} \approx one million.

    Now let the outcomes have different probabilities: aa with 12\frac12, bb with 14\frac14, cc with 14\frac14. Good strategy: ask about the likely outcome first.

    1. Ask "Is it aa?". Half of the time the answer is yes: 1 question.
    2. If no, ask "Is it bb?". This finds bb or cc: 2 questions.

    The average number of questions is 12⋅1+12⋅2=1.5\frac12 \cdot 1 + \frac12 \cdot 2 = 1.5. Look at the surprisals: −log⁡212=1-\log_2 \frac12 = 1 and −log⁡214=2-\log_2 \frac14 = 2. Each outcome needs as many questions as its surprisal. So the average number of questions is the average surprisal. This average is the entropy.

    Interactive figure: loading…

    Press Play once to draw a hidden outcome and follow its path in the question tree (yellow). Then press Play 100 games a few times: the running average settles at the expected number of questions of the tree (grey line). For (12,14,18,18)(\frac12, \frac14, \frac18, \frac18) this equals the entropy H=1.75H = 1.75 bits (blue line). Try the strategy split the list in half: it needs 2 questions. Then try the distribution (0.7,0.2,0.1)(0.7, 0.2, 0.1): even the best tree needs more than HH, because surprisals such as 0.5150.515 bits are not whole numbers.

    When the probabilities are not powers of 12\frac12, the best question tree needs a little more than the entropy, but always less than the entropy plus one question. If you find many outcomes together (for example, ask about 10 die rolls at once), the average per outcome comes as close to the entropy as you want. Lesson 05 proves both facts.

    Entropy is the average surprisal #

    The entropy of a coin with P(heads)=0.9P(\text{heads}) = 0.9:

    H=0.9⋅(−log⁡20.9)⏟0.152+0.1⋅(−log⁡20.1)⏟3.322=0.137+0.332=0.469 bits.H = 0.9 \cdot \underbrace{(-\log_2 0.9)}_{0.152} + 0.1 \cdot \underbrace{(-\log_2 0.1)}_{3.322} = 0.137 + 0.332 = 0.469 \text{ bits}.

    The rare outcome is very surprising (3.3 bits), but it is rare. The common outcome is almost no surprise. On average you learn less than half a bit per flip.

    Interactive figure: loading…

    Drag the tops of the blue bars (the probabilities); the other bars rescale so the total stays 1. The yellow bars below are the contributions −plog⁡2p-p\log_2 p of each outcome; their sum is the entropy HH. Use one-hot and uniform to reach the two extremes H=0H = 0 and H=log⁡2KH = \log_2 K (the dashed line in the meter). Notice that a tiny probability contributes almost nothing, and so does a probability close to 1.

    Quick check

    A fair 8-sided die is rolled. What is the entropy of the result?

    Quick check

    Which distribution on 4 outcomes has the largest entropy?

    3. Definitions and main results #

    Entropy #

    Let XX be a discrete random variable with values in a finite set X\mathcal{X} of size KK, and let p(x)=P(X=x)p(x) = P(X = x).

    • The surprisal of a value xx with p(x)>0p(x) > 0 is −log⁡p(x)=log⁡1p(x)-\log p(x) = \log \frac{1}{p(x)}.
    • The entropy of XX is the expected surprisal:
    H(X)=−∑x∈Xp(x)log⁡p(x)=E[−log⁡p(X)].H(X) = -\sum_{x \in \mathcal{X}} p(x) \log p(x) = \mathbb{E}\big[-\log p(X)\big].
    • Convention: 0log⁡0=00 \log 0 = 0. The reason: tlog⁡t→0t \log t \to 0 as t→0+t \to 0^+. An outcome with probability 0 never happens, so it adds nothing to the average.

    We also write H(p)H(p) for the entropy of a distribution p=(p1,…,pK)p = (p_1, \dots, p_K).

    Entropy depends only on the list of probabilities. The values of XX do not enter the formula. A coin with values {0,1}\{0, 1\} and a variable with values {1,1000}\{1, 1000\}, each with probability 12\frac12, both have entropy 1 bit. Relabeling or reordering the outcomes does not change HH. Adding an outcome with probability 0 does not change HH either.

    Units: bits and nats #

    Changing the base of the logarithm only multiplies HH by a constant, because log⁡2t=log⁡t/log⁡2\log_2 t = \log t / \log 2:

    Hbits=Hnatsln⁡2,1 nat=1ln⁡2=1.443 bits,1 bit=ln⁡2=0.693 nats.H_{\text{bits}} = \frac{H_{\text{nats}}}{\ln 2}, \qquad 1 \text{ nat} = \frac{1}{\ln 2} = 1.443 \text{ bits}, \qquad 1 \text{ bit} = \ln 2 = 0.693 \text{ nats}.

    For example, the distribution (12,14,14)(\frac12, \frac14, \frac14) has entropy 1.51.5 bits =1.5⋅0.693=1.040= 1.5 \cdot 0.693 = 1.040 nats.

    The binary entropy #

    A variable with two outcomes, with probabilities pp and 1−p1 - p, has the binary entropy

    Hb(p)=−plog⁡2p−(1−p)log⁡2(1−p)bits.H_b(p) = -p \log_2 p - (1 - p) \log_2 (1 - p) \quad \text{bits}.

    Its properties, read off the curve below:

    • Hb(0)=Hb(1)=0H_b(0) = H_b(1) = 0: a sure outcome has no uncertainty.
    • Hb(12)=1H_b(\frac12) = 1 bit, the maximum.
    • Hb(p)=Hb(1−p)H_b(p) = H_b(1 - p): swapping the two labels does not change the entropy.
    • The curve is steep near 00 and 11: moving from p=0p = 0 to p=0.1p = 0.1 already gives 0.4690.469 bits. Some values: Hb(0.1)=0.469H_b(0.1) = 0.469, Hb(0.2)=0.722H_b(0.2) = 0.722, Hb(0.3)=0.881H_b(0.3) = 0.881 bits.
    Interactive figure: loading…

    Drag the first bar from 0 to 1. The yellow point runs along the binary entropy curve Hb(p)H_b(p) (blue). Notice the symmetry around p=12p = \frac12 and how fast the curve rises near the ends.

    Quick check

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

    Bounds on the entropy #

    Theorem (bounds on entropy). Let XX take KK values. Then

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

    H(X)=0H(X) = 0 if and only if XX is constant (one value has probability 1). H(X)=log⁡KH(X) = \log K if and only if XX is uniform on all KK values.

    Proof of the lower bound.

    1. Every p(x)p(x) lies in [0,1][0, 1], so log⁡p(x)≤0\log p(x) \le 0, and every term −p(x)log⁡p(x)-p(x) \log p(x) is ≥0\ge 0.
    2. A sum of non-negative terms is non-negative, so H(X)≥0H(X) \ge 0.
    3. H(X)=0H(X) = 0 means every term is 0. The term −tlog⁡t-t \log t is 0 only for t=0t = 0 or t=1t = 1. So every probability is 0 or 1: one value has probability 1. ■\blacksquare

    Intuition for the upper bound. The uniform distribution is the hardest to guess: no outcome is more likely than another, so no question strategy can do better than halving. Any bias makes some outcomes easier to guess, which lowers the average number of questions.

    The proof uses one simple inequality.

    Lemma. ln⁡t≤t−1\ln t \le t - 1 for all t>0t > 0, with equality only at t=1t = 1.

    Proof. Let f(t)=t−1−ln⁡tf(t) = t - 1 - \ln t. Then f′(t)=1−1/tf'(t) = 1 - 1/t, which is negative for t<1t < 1 and positive for t>1t > 1. So ff has its minimum at t=1t = 1, where f(1)=0f(1) = 0. Hence f(t)≥0f(t) \ge 0, with equality only at t=1t = 1. As a picture: the line t−1t - 1 touches the curve ln⁡t\ln t at t=1t = 1 and lies above it everywhere else. ■\blacksquare

    Proof of the upper bound.

    1. Let S={x:p(x)>0}S = \{x : p(x) > 0\} be the support of pp. Terms with p(x)=0p(x) = 0 are 0, so H(X)=∑x∈Sp(x)ln⁡1p(x)H(X) = \sum_{x \in S} p(x) \ln \frac{1}{p(x)}. Work in nats; bits only divide both sides by ln⁡2\ln 2.
    2. Since ∑x∈Sp(x)=1\sum_{x \in S} p(x) = 1, we can write ln⁡K=∑x∈Sp(x)ln⁡K\ln K = \sum_{x \in S} p(x) \ln K. Subtract:
    H(X)−ln⁡K=∑x∈Sp(x)ln⁡1K p(x).H(X) - \ln K = \sum_{x \in S} p(x) \ln \frac{1}{K\,p(x)}.
    1. Apply the lemma with t=1Kp(x)t = \frac{1}{K p(x)} to every term:
    H(X)−ln⁡K≤∑x∈Sp(x)(1K p(x)−1)=∣S∣K−1≤0,H(X) - \ln K \le \sum_{x \in S} p(x) \Big( \frac{1}{K\,p(x)} - 1 \Big) = \frac{|S|}{K} - 1 \le 0,

    because the support has at most KK elements.

    1. Equality needs equality in both steps. The lemma is tight only when 1Kp(x)=1\frac{1}{K p(x)} = 1, that is p(x)=1Kp(x) = \frac1K for every x∈Sx \in S. The last step is tight only when ∣S∣=K|S| = K. Together: p(x)=1Kp(x) = \frac1K for all KK values. ■\blacksquare

    Lesson 03 gives a second view of the same fact: log⁡K−H(p)\log K - H(p) is the KL divergence from pp to the uniform distribution, which is never negative.

    Doubling the number of equally likely outcomes adds one bit: log⁡2(2K)=log⁡2K+1\log_2(2K) = \log_2 K + 1. A uniform choice among 1024 items has 10 bits; among 2048 items, 11 bits.

    Quick check

    XX takes the values 11 and 10001000 with probability 12\frac12 each. YY takes the values 00 and 11 with probability 12\frac12 each. Compare their entropies.

    Why exactly the logarithm?

    Suppose a measure of surprise s(p)s(p) depends only on the probability p∈(0,1]p \in (0, 1], is continuous, and adds for independent events: s(pq)=s(p)+s(q)s(pq) = s(p) + s(q). Put g(u)=s(e−u)g(u) = s(e^{-u}) for u≥0u \ge 0. Then g(u+v)=s(e−ue−v)=g(u)+g(v)g(u + v) = s(e^{-u}e^{-v}) = g(u) + g(v), and a continuous function with this property is linear (Cauchy's functional equation): g(u)=c ug(u) = c\,u. So s(p)=−cln⁡ps(p) = -c \ln p. The constant cc only chooses the unit: s(12)=1s(\frac12) = 1 gives c=1/ln⁡2c = 1/\ln 2, that is, bits. For a positive surprise, c>0c > 0.

    Shannon (1948, Theorem 2) proved a similar statement for the entropy itself: the only continuous function of (p1,…,pK)(p_1, \dots, p_K) that grows with KK for uniform distributions and that obeys a natural "grouping" rule (one question at a time, as in the question game) is −c∑ipilog⁡pi-c\sum_i p_i \log p_i.

    A preview of coding #

    A code writes each outcome as a string of bits. For (12,14,18,18)(\frac12, \frac14, \frac18, \frac18) on a,b,c,da, b, c, d, use a=0a = 0, b=10b = 10, c=110c = 110, d=111d = 111. The bits are the answers in the question game: 0 for "yes", 1 for "no". The average length is 12⋅1+14⋅2+18⋅3+18⋅3=1.75\frac12 \cdot 1 + \frac14 \cdot 2 + \frac18 \cdot 3 + \frac18 \cdot 3 = 1.75 bits, exactly the entropy: each codeword length equals the surprisal of its symbol. No code that can always be decoded does better on average than the entropy; this is the source coding theorem of lesson 05.

    Answers to section 1. (1) Between 2 and 3. The entropy of a fair die is log⁡26=2.585\log_2 6 = 2.585 bits. The best question tree for one die puts 2 faces at depth 2 and 4 faces at depth 3, so it needs 2⋅2+4⋅36=2.667\frac{2 \cdot 2 + 4 \cdot 3}{6} = 2.667 questions on average. Asking about many dice at once brings the average per die close to 2.5852.585 (lesson 05). (2) Less than both: Hb(0.9)=0.469H_b(0.9) = 0.469 bits. (3) No. Every term −p(x)log⁡p(x)-p(x)\log p(x) is ≥0\ge 0, so H(X)≥0H(X) \ge 0.

    4. Worked example #

    (a) A weather forecast. Tomorrow is sunny with probability 12\frac12, cloudy with 14\frac14, rainy with 18\frac18 and snowy with 18\frac18.

    1. Surprisals. −log⁡212=1-\log_2 \frac12 = 1, −log⁡214=2-\log_2 \frac14 = 2, −log⁡218=3-\log_2 \frac18 = 3, −log⁡218=3-\log_2 \frac18 = 3 bits.
    2. Entropy in bits. Weight each surprisal by its probability: H=12⋅1+14⋅2+18⋅3+18⋅3=0.5+0.5+0.375+0.375=1.75H = \frac12 \cdot 1 + \frac14 \cdot 2 + \frac18 \cdot 3 + \frac18 \cdot 3 = 0.5 + 0.5 + 0.375 + 0.375 = 1.75 bits.
    3. In nats. Multiply by ln⁡2=0.693\ln 2 = 0.693: 1.75⋅0.693=1.2131.75 \cdot 0.693 = 1.213 nats.
    4. Compare with the maximum. For K=4K = 4, log⁡24=2\log_2 4 = 2 bits. The forecast is less uncertain than a uniform choice among 4, because "sunny" is likely.
    5. Question tree. Ask "sunny?", then "cloudy?", then "rainy?". The numbers of questions are 1, 2, 3, 3: equal to the surprisals. The average is 1.75 questions =H= H.

    (b) Probabilities that are not powers of 12\frac12. p=(0.7,0.2,0.1)p = (0.7, 0.2, 0.1) on a,b,ca, b, c.

    1. Surprisals. −log⁡20.7=0.515-\log_2 0.7 = 0.515, −log⁡20.2=2.322-\log_2 0.2 = 2.322, −log⁡20.1=3.322-\log_2 0.1 = 3.322 bits.
    2. Entropy. H=0.7⋅0.515+0.2⋅2.322+0.1⋅3.322=0.360+0.464+0.332=1.157H = 0.7 \cdot 0.515 + 0.2 \cdot 2.322 + 0.1 \cdot 3.322 = 0.360 + 0.464 + 0.332 = 1.157 bits.
    3. Best question tree. Ask "Is it aa?", then "Is it bb?". The numbers of questions are 1, 2, 2, so the average is 0.7⋅1+0.3⋅2=1.30.7 \cdot 1 + 0.3 \cdot 2 = 1.3 questions.
    4. Check the bounds. 1.157≤1.3<1.157+11.157 \le 1.3 < 1.157 + 1: the best tree is above the entropy but within one question of it. The maximum for K=3K = 3 is log⁡23=1.585\log_2 3 = 1.585 bits.

    (c) Temperature in a softmax. A model outputs the logits z=(2,1,0)z = (2, 1, 0) for three classes. The probabilities are qi=ezi/T/∑jezj/Tq_i = e^{z_i / T} / \sum_j e^{z_j / T} with the temperature TT.

    1. T=1T = 1: q=(0.665,0.245,0.090)q = (0.665, 0.245, 0.090), H=1.201H = 1.201 bits.
    2. T=0.5T = 0.5 divides by a smaller number, so the gaps between logits grow: q=(0.867,0.117,0.016)q = (0.867, 0.117, 0.016), H=0.636H = 0.636 bits.
    3. T=2T = 2 shrinks the gaps: q=(0.506,0.307,0.186)q = (0.506, 0.307, 0.186), H=1.472H = 1.472 bits.

    Higher temperature, higher entropy, closer to the maximum log⁡23=1.585\log_2 3 = 1.585 bits.

    Quick check

    A source has the distribution (12,14,18,116,116)(\frac12, \frac14, \frac18, \frac1{16}, \frac1{16}). What is its entropy?

    5. In code #

    NumPy computes the entropy of a probability vector. Skipping the zeros implements the convention 0log⁡0=00 \log 0 = 0; writing the terms as plog⁡(1/p)p \log(1/p) makes the result exactly 0.00.0 for a sure outcome.

    import numpy as np
    from scipy.stats import entropy
    
    def H(p, base=2):
        """Entropy of a probability vector; terms with p = 0 are skipped (0 log 0 = 0)."""
        p = np.asarray(p, dtype=float)
        p = p[p > 0]
        return np.sum(p * np.log(1 / p)) / np.log(base)
    
    weather = [1/2, 1/4, 1/8, 1/8]
    print(-np.log2(weather))                    # [1. 2. 3. 3.]   surprisals in bits
    print(H(weather), H(weather, base=np.e))    # 1.75 1.2130075659799042
    print(entropy(weather, base=2))             # 1.75            SciPy agrees
    print(H([0.9, 0.1]), H([0.7, 0.2, 0.1]))    # 0.46899559358928133 1.1567796494470395
    print(H([1, 0, 0]), H(np.ones(8) / 8), H(np.ones(6) / 6))   # 0.0 3.0 2.584962500721156
    
    def softmax(z, T=1.0):
        z = np.asarray(z, dtype=float) / T
        e = np.exp(z - z.max())                 # subtract the max for numerical safety
        return e / e.sum()
    
    for T in [0.5, 1, 2]:
        q = softmax([2, 1, 0], T)
        print(T, q.round(3), round(H(q), 3))
    # 0.5 [0.867 0.117 0.016] 0.636
    # 1 [0.665 0.245 0.09 ] 1.201
    # 2 [0.506 0.307 0.186] 1.472
    

    scipy.stats.entropy(p) normalizes p first and uses nats unless you pass base. A plain np.sum(p * np.log(p)) returns nan when some p is 0, because 0 * log(0) is 0 * (-inf).

    6. Where it shows up #

    • Loss functions. The cross-entropy loss of a classifier is the average surprisal of the true label under the model. It can never go below the entropy of the labels given the inputs (lesson 02 and lesson 04). A language model's loss in bits per token is the average surprisal of the next token.
    • Decision trees. The entropy of the class labels at a node measures how mixed the node is. ID3 and C4.5 choose the split with the largest information gain, the drop in entropy (lesson 02 and the decision-tree lesson of the ML fundamentals track, in preparation).
    • Uncertainty of a prediction. The entropy of a classifier's predicted distribution is a simple uncertainty score. Uncertainty sampling in active learning asks for labels of the inputs with the highest predictive entropy.
    • Reinforcement learning. Soft actor-critic (SAC) maximizes reward plus α\alpha times the entropy of the policy, and PPO often adds an entropy bonus. Both keep the policy random enough to explore (RL 08).
    • Sampling from language models. Dividing the logits by a temperature T>1T > 1 raises the entropy of the next-token distribution (more varied text); T<1T < 1 lowers it (more predictable text) (the decoding lesson of the LLMs track, in preparation).
    • ML for science. In biology, a sequence logo shows, for each position of aligned DNA or protein sequences, the information content log⁡2N−H\log_2 N - H, where NN is the alphabet size (4 for DNA, 20 for proteins) and HH is the entropy of the letters in that column. Conserved positions have low entropy and tall letters. In ecology, the entropy of species proportions is the Shannon diversity index.

    7. Common mistakes #

    • Mixing bits and nats. NumPy, SciPy (by default) and PyTorch use the natural log. Divide by ln⁡2=0.693\ln 2 = 0.693 to get bits.
    • nan from 0log⁡00 \log 0. Skip the zero probabilities, or use scipy.special.xlogy. The convention is 0log⁡0=00 \log 0 = 0.
    • "Entropy measures how spread out the values are." It does not use the values at all. {0,1}\{0, 1\} and {0,1000}\{0, 1000\} with equal probabilities both have 1 bit. Spread of values is the variance.
    • Confusing the average surprisal with the surprisal of the likely outcome. For (0.9,0.1)(0.9, 0.1) the likely outcome has surprisal 0.1520.152 bits, but the entropy is 0.4690.469 bits.
    • Using counts instead of probabilities. The formula needs probabilities that sum to 1. Divide counts by their total first. (scipy.stats.entropy does this for you; a hand-written formula does not.)
    • Expecting entropy to grow like KK. The entropy of a uniform distribution grows like log⁡K\log K: doubling the number of outcomes adds only one bit.

    8. Check yourself #

    1. What is the entropy of a fair six-sided die, in bits and in nats?
      Answerlog⁡26=2.585\log_2 6 = 2.585 bits and ln⁡6=1.792\ln 6 = 1.792 nats.
    2. Which has more entropy: a coin with P(heads)=0.2P(\text{heads}) = 0.2 or a coin with P(heads)=0.7P(\text{heads}) = 0.7?
      AnswerHb(0.2)=0.722H_b(0.2) = 0.722 bits and Hb(0.7)=Hb(0.3)=0.881H_b(0.7) = H_b(0.3) = 0.881 bits. The coin with 0.70.7 is closer to 12\frac12, so it has more entropy.
    3. Someone says a distribution on 5 outcomes has entropy 2.5 bits. Is this possible?
      AnswerNo. The maximum for 5 outcomes is log⁡25=2.322\log_2 5 = 2.322 bits, reached by the uniform distribution.
    4. A uniform distribution has entropy 5 bits. How many outcomes does it have? What is the entropy if you double the number of outcomes?
      Answerlog⁡2K=5\log_2 K = 5 gives K=32K = 32. With 64 equally likely outcomes, H=6H = 6 bits: doubling adds one bit.
    5. Prove that H(X)=0H(X) = 0 implies that one value of XX has probability 1.
      AnswerEach term −p(x)log⁡p(x)-p(x)\log p(x) is ≥0\ge 0. If the sum is 0, every term is 0. The function −tlog⁡t-t\log t is 0 on [0,1][0, 1] only at t=0t = 0 and t=1t = 1. So every p(x)p(x) is 0 or 1, and since they sum to 1, exactly one is 1.
    6. A model gives the probabilities (0.98,0.01,0.01)(0.98, 0.01, 0.01) to three classes. Compute the entropy of its prediction in bits. Is the model confident?
      AnswerH=0.98⋅0.029+2⋅0.01⋅6.644=0.029+0.133=0.161H = 0.98 \cdot 0.029 + 2 \cdot 0.01 \cdot 6.644 = 0.029 + 0.133 = 0.161 bits, far below the maximum log⁡23=1.585\log_2 3 = 1.585. The model is confident (whether it is also right is a different question).
    Recall cardsAnswer in your head first, then reveal. Add the cards to your review deck to see them again just before you would forget.
    1. What is the surprisal of an outcome with probability pp?

    2. Why is surprisal defined with a logarithm?

    3. Define the entropy of a discrete random variable XX.

    4. How do you convert an entropy from nats to bits?

    5. What is the entropy of a uniform distribution on KK outcomes?

    6. When is H(X)=0H(X) = 0?

    7. Compute the entropy of (12,14,14)(\frac12, \frac14, \frac14) in bits.

    8. What is Hb(0.5)H_b(0.5), and what is Hb(0.1)H_b(0.1), in bits?

    9. Why does the convention 0log⁡0=00 \log 0 = 0 make sense?

    10. What does entropy have to do with yes/no questions?

    Open the review →

    9. Interview angle #

    • "What is entropy, intuitively?" — The average surprise of the outcome, or the average number of yes/no questions needed to find it. Zero for a certain outcome, log⁡K\log K for KK equally likely outcomes.
    • "Which distribution on KK outcomes has maximum entropy? Prove it." — The uniform one. Proof with ln⁡t≤t−1\ln t \le t - 1 (section 3), or with log⁡K−H(p)=KL(p ∥ u)≥0\log K - H(p) = \mathrm{KL}(p\,\|\,u) \ge 0 (lesson 03).
    • "Your cross-entropy loss is 0.69. What does that mean?" — PyTorch uses nats, so this is 0.69/0.693≈10.69/0.693 \approx 1 bit per example: the model is as uncertain as a fair coin about the true label, on average.
    • "How does the temperature of a language model change its outputs?" — The logits are divided by TT. A larger TT gives a flatter softmax with higher entropy (more diverse samples); a smaller TT gives a sharper one with lower entropy.
    • "Why does a decision tree use entropy?" — The entropy of the labels at a node measures how mixed they are. A good split lowers the weighted entropy of the children (information gain).

    10. Practice #

    The notebook for this lesson runs in Colab. It has five exercises, each with a check cell and a folded solution:

    1. Write surprisal(p, base) and entropy(p, base) with the convention 0log⁡0=00 \log 0 = 0, and check them against scipy.stats.entropy.
    2. Plot the binary entropy Hb(p)H_b(p) and find its maximum numerically.
    3. Compute the entropy of the letters of a short English text from their counts.
    4. Simulate the question game for (12,14,18,18)(\frac12, \frac14, \frac18, \frac18) and compare the average number of questions with HH.
    5. Compute the entropy of a softmax at several temperatures, and check that it grows with TT.

    11. Watch and read #

    Builds entropy from the question game and from coding, the same path as this lesson.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Surprise as log(1/p) and entropy as expected surprise, with slow small examples.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    Choosing the guess with the largest expected information: the question game in a real puzzle.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play
    MacKay's own lecture on information content, entropy and the weighing problem.
    Open on YouTube · the player loads from youtube-nocookie.com when you press play