Information TheoryComputer Science, Applied · Book 1
0 / 0

Shelves / Information Theory

IT·07

Joint and Conditional Entropy, Mutual Information

Information about two things at once: joint entropy; conditional entropy, the uncertainty left about one thing once you know another; the chain rule that adds them up; why knowing more can't increase uncertainty on average; mutual information, how much one thing tells you about another, symmetric and zero only for independence; the data processing inequality, why no processing can create information; and entropy rates for sources with memory, measured on Shakespeare with contexts of up to seven letters, including what happens when a model learns its training text too well.

27 topics · ~31 min read · 12-question quiz
Updated Suggest a correction

Start here

What this chapter answers

How much information is there in two related things together? How much uncertainty about one is left once you know the other? Why can learning something never make you more uncertain on average? How do you measure how much one thing tells you about another, and why is that symmetric? Why can no computation on data increase the information it carries about something else? And how much does each extra letter of context tell you about the next letter of English?

Two variables in one picture

Picture two overlapping circles. One circle's area is H(X), the uncertainty about X; the other's is H(Y). Together they cover H(X,Y), the uncertainty about both. The overlap is I(X;Y), the information they share: how much learning one tells you about the other. The part of the X circle outside the overlap is H(X∣Y), what's still uncertain about X after learning Y. Every identity in this chapter can be read off this picture, and every one is also an exact theorem.

H(X | Y)I(X; Y)H(Y | X) H(X)H(Y) all of it: H(X, Y)
The information diagram: two overlapping regions for H(X) and H(Y); the overlap is the mutual information, and the rest of each region is the conditional entropy.

Joint and conditional entropy

Joint entropy

Two random variables X and Y have a joint distribution p(x,y), and the pair is just another random variable, so it has an entropy:

H(X,Y)=∑x,yp(x,y)log21p(x,y).

Chapter 4 showed that for independent variables H(X,Y)=H(X)+H(Y). When they're dependent, the pair is more predictable than that: knowing one helps predict the other, so H(X,Y)<H(X)+H(Y).

Conditional entropy

If you learn that X=x, the uncertainty left about Y is the entropy of the conditional distribution p(y∣x). Averaging over the values of X, weighted by how often each occurs, gives the conditional entropy:

The two extremes are instructive. If Y is completely determined by X (the sum of two dice, given the dice), H(Y∣X)=0. If Y is independent of X, knowing X doesn't help, and H(Y∣X)=H(Y).

The chain rule

Describing a pair is the same as describing the first, then the second given the first:

Interactive diagram: The chain rule and mutual information, in bits. It needs JavaScript; the text around it says the same.

The chain rule is grouping (chapter 4) in another form, and it's how compressors work: code the first symbol, then each next symbol given what came before, and the total cost is the sum of the conditional surprises.

Knowing more can't hurt, on average

This is on average. A particular observation can increase your uncertainty: chapter 3's exercise found that "z" is more surprising after "e" than on its own, and a surprising test result can leave you less sure than before. But averaged over everything you might learn, information never hurts. Chapter 3's exercise C1 measured it: the letter after a known letter carries 3.65 bits on average, against 4.19 without context.

Mutual information

How much one thing tells you about another

The reduction in uncertainty about Y from learning X has a name.

The forms are equal by the chain rule, and they say several things at once. Mutual information is symmetric: X tells you exactly as much about Y as Y tells you about X, even when the relationship looks one-directional (weather predicts umbrellas; umbrellas tell you as much about the weather). It's never negative, and it's zero exactly when the variables are independent. It's at most the smaller of H(X) and H(Y): you can't learn more about X than there is to know. And the last form shows it measures how far the joint distribution is from what independence would give, which chapter 11 will recognise as a Kullback–Leibler divergence.

A sensor that sometimes lies

Chapter 1's exercises asked how much a sensor's reading tells you about the real value when the sensor is sometimes wrong. Mutual information answers exactly. Suppose the true state is one of 8, equally likely (3 bits), and the sensor reports it correctly with probability q, otherwise one of the other 7 at random. The lab finds: a perfect sensor gives the full 3 bits; one that's right 90 % of the time gives 2.25 bits; 70 %, 1.28 bits; 50 %, 0.60 bits; and one that's right only 18 of the time, as often as a random guess, gives exactly nothing. A sensor's value as an instrument is its mutual information with the truth, and it drops off much faster than its accuracy. This is also, exactly, a noisy channel: chapter 9's capacity is the largest mutual information a channel allows.

The data processing inequality

If Z is computed from Y alone, and Y depends on X, then X→Y→Z form a Markov chain: once Y is known, Z has nothing more to do with X.

No processing of data, however clever, can increase the information it carries about something else: summarising, filtering, compressing lossily, or running it through a model can only keep or lose information. The lab's dice show it: the pair of dice carries 5.17 bits about itself; their sum keeps 3.27 bits about the pair; "is the sum above 7?", computed from the sum, keeps 0.98. In practice this is the reason to keep raw data when you can: every summary is a bet that you know which information you'll need.

Sources with memory

Entropy rate

Chapter 4's entropy treated symbols as independent. Real sources have memory: a letter depends on the letters before it. For such a source, the chain rule says the information in n symbols is the sum of each symbol's conditional entropy given those before. The entropy rate is the information per symbol in the long run:

H∞=limn→∞1nH(X1,…,Xn)=limn→∞H(Xn∣X1,…,Xn−1),

and it's the true limit of compression for sources with memory (the source coding theorem holds with H∞ in place of H, as McMillan and Breiman proved). Because conditioning reduces entropy, the conditional entropies H(Xn∣last k symbols) can only fall as k grows, and they fall towards the entropy rate.

Markov models of text

A Markov model of order k predicts each symbol from the k symbols before it. The lab measures, on the plays reduced to 26 letters and a space, the conditional entropy given the last k symbols, estimated from counts in 90 % of the text: 4.09 bits with no context, 3.32 with one symbol, 2.68 with two, 2.14 with three, falling to 0.97 with seven. Each letter of context removes some uncertainty, as the theory says.

Interactive diagram: More context, better prediction, until it overfits. It needs JavaScript; the text around it says the same.

But the lab also tests each model on the unseen last 10 % of the text, and there the story changes: 4.07, 3.34, 2.81, 2.42, 2.29 with four symbols of context, and then worse: 2.50 with five, 3.34 with seven. Long contexts are mostly unique in the training text, so the counts "predict" the training text perfectly and generalise badly: the plug-in estimate of chapter 4, biased low, made dramatically worse by having millions of contexts to estimate. This is overfitting, and it's the central problem of building predictive models from data. Good compressors and language models handle it by mixing predictions from contexts of several lengths, backing off to shorter contexts when a long one has rarely been seen (chapter 10), and chapter 11 explains why the held-out figure, a cross-entropy, is the honest one.

Lab: two variables at a time

Python
import math
from collections import Counter
def H(counts):
    """Entropy in bits of a distribution given as counts (a Counter or dict)."""
    n = sum(counts.values())
    return sum(-c / n * math.log2(c / n) for c in counts.values() if c)
def joint_report(pairs):
    """H(X), H(Y), H(X,Y), H(Y|X), H(X|Y) and I(X;Y) from a list of (x, y) pairs."""
    hx, hy, hxy = H(Counter(x for x, _ in pairs)), H(Counter(y for _, y in pairs)), H(Counter(pairs))
    return {"H(X)": hx, "H(Y)": hy, "H(X,Y)": hxy, "H(Y|X)": hxy - hx, "H(X|Y)": hxy - hy, "I(X;Y)": hx + hy - hxy}

joint_report estimates every quantity in the chapter from a list of pairs, using the chain rule: the conditional entropies and mutual information all follow from three entropies.

Experiment 1: weather and umbrellas

Python
from info import joint_report
# A year of days: (weather, did I carry an umbrella?), as counts
table = {("rain", "umbrella"): 50, ("rain", "none"): 10, ("dry", "umbrella"): 30, ("dry", "none"): 275}
pairs = [k for k, c in table.items() for _ in range(c)]
for name, value in joint_report(pairs).items():
    print(f"{name:<7} = {value:.4f} bits")
Text
H(X)    = 0.6447 bits
H(Y)    = 0.7587 bits
H(X,Y)  = 1.1391 bits
H(Y|X)  = 0.4944 bits
H(X|Y)  = 0.3804 bits
I(X;Y)  = 0.2643 bits

The weather alone has 0.645 bits of uncertainty; knowing whether I carried an umbrella leaves 0.380, so the umbrella tells you 0.264 bits about the weather. Symmetrically, the weather tells you 0.264 bits about the umbrella (0.759 down to 0.494). The pair has 1.139 bits, less than the 1.403 the two would have if they were independent: the difference is exactly the mutual information.

Experiment 2: context in English, and overfitting

Python
import math
from collections import Counter, defaultdict
text = open("data/shakespeare.txt", encoding="utf-8").read().lower()
letters = "".join(c if "a" <= c <= "z" else " " for c in text).split()
s = " ".join(letters)                                     # 27 symbols: letters and a single space between words
cut = int(len(s) * 0.9)
train, test = s[:cut], s[cut:]
def plug_in(k):
    """H(next | previous k symbols), from counts of (k+1)-grams in the training text."""
    ctx, full = Counter(), Counter()
    for i in range(k, len(train)):
        ctx[train[i - k:i]] += 1; full[train[i - k:i + 1]] += 1
    n = sum(full.values())
    return sum(-c / n * math.log2(c / ctx[g[:-1]]) for g, c in full.items())
def held_out(k, alpha=0.5, K=27):
    """Bits per symbol on the unseen 10 %, predicting each symbol from its k-symbol context (counts + alpha)."""
    table = defaultdict(Counter)
    for i in range(k, len(train)):
        table[train[i - k:i]][train[i]] += 1
    bits = 0.0
    for i in range(k, len(test)):
        c = table.get(test[i - k:i], Counter())
        bits -= math.log2((c[test[i]] + alpha) / (sum(c.values()) + alpha * K))
    return bits / (len(test) - k)
print(f"{len(s):,} symbols (26 letters and a space); train on the first 90 %, test on the last 10 %")
for k in range(0, 8):
    print(f"context of {k} symbol{'s' if k != 1 else ' '}: H(next | context) from the training counts {plug_in(k):.3f}; on the unseen text {held_out(k):.3f} bits per symbol")
Text
1,059,580 symbols (26 letters and a space); train on the first 90 %, test on the last 10 %
context of 0 symbols: H(next | context) from the training counts 4.086; on the unseen text 4.071 bits per symbol
context of 1 symbol : H(next | context) from the training counts 3.319; on the unseen text 3.340 bits per symbol
context of 2 symbols: H(next | context) from the training counts 2.683; on the unseen text 2.805 bits per symbol
context of 3 symbols: H(next | context) from the training counts 2.137; on the unseen text 2.422 bits per symbol
context of 4 symbols: H(next | context) from the training counts 1.796; on the unseen text 2.291 bits per symbol
context of 5 symbols: H(next | context) from the training counts 1.526; on the unseen text 2.497 bits per symbol
context of 6 symbols: H(next | context) from the training counts 1.249; on the unseen text 2.901 bits per symbol
context of 7 symbols: H(next | context) from the training counts 0.972; on the unseen text 3.344 bits per symbol

Measured on the text the counts came from, more context always helps, down to 0.97 bits per symbol with seven symbols of context. Measured honestly on unseen text, context helps up to four symbols (2.29 bits, against 4.07 with none) and then hurts, reaching 3.34 bits with seven. The training figures for long contexts aren't the entropy rate of English; they're the model memorising its training text. The best figure on unseen text, 2.29 bits per symbol, comes from a model that's nothing but counts; it isn't directly comparable with lzma's 2.6 bits per character in chapter 1, since this text has no capitals, punctuation or line breaks, but it shows how much of English's information sits in the last few letters.

Experiment 3: how much a noisy sensor tells you

Python
import math
from info import joint_report
# A sensor reports the true state (one of 8, equally likely) correctly with probability q, otherwise a random other state
for q in (1.0, 0.9, 0.7, 0.5, 0.125):
    pairs, scale = [], 7000
    for t in range(8):
        for r in range(8):
            w = q if r == t else (1 - q) / 7
            pairs += [(t, r)] * round(w * scale)
    rep = joint_report(pairs)
    print(f"correct {q:>5.1%} of the time: H(true) {rep['H(X)']:.3f}, H(true | reading) {rep['H(X|Y)']:.3f}, I(true; reading) {rep['I(X;Y)']:.3f} bits")
Text
correct 100.0% of the time: H(true) 3.000, H(true | reading) 0.000, I(true; reading) 3.000 bits
correct 90.0% of the time: H(true) 3.000, H(true | reading) 0.750, I(true; reading) 2.250 bits
correct 70.0% of the time: H(true) 3.000, H(true | reading) 1.723, I(true; reading) 1.277 bits
correct 50.0% of the time: H(true) 3.000, H(true | reading) 2.404, I(true; reading) 0.596 bits
correct 12.5% of the time: H(true) 3.000, H(true | reading) 3.000, I(true; reading) 0.000 bits

A sensor that's right 90 % of the time tells you 2.25 of the 3 bits; one right 70 % of the time, 1.28; at 50 %, 0.60. Accuracy falls linearly but information falls faster, because each error doesn't just lose a reading: it spreads probability over seven wrong answers. A sensor right only 12.5 % of the time, the rate of guessing, is worthless: zero mutual information.

Experiment 4: processing can't add information

Python
from info import joint_report
pairs = [(a, b) for a in range(1, 7) for b in range(1, 7)]
for name, f in (("the pair itself", lambda a, b: (a, b)), ("the sum", lambda a, b: a + b), ("the sum's parity", lambda a, b: (a + b) % 2),
                ("is the sum above 7?", lambda a, b: a + b > 7), ("the first die", lambda a, b: a)):
    rep = joint_report([((a, b), f(a, b)) for a, b in pairs])
    print(f"I(pair; {name:<20}) = {rep['I(X;Y)']:.4f} bits")
Text
I(pair; the pair itself     ) = 5.1699 bits
I(pair; the sum             ) = 3.2744 bits
I(pair; the sum's parity    ) = 1.0000 bits
I(pair; is the sum above 7? ) = 0.9799 bits
I(pair; the first die       ) = 2.5850 bits

Every summary of a pair of dice carries less information about the pair than the pair itself (5.17 bits): the first die 2.585, the sum 3.27, "is the sum above 7?" 0.98, the parity of the sum exactly 1. Since "above 7" is computed from the sum, the data processing inequality guarantees it can carry no more about the pair than the sum does, and it carries far less.

Worked examples

Reading off the diagram

A deterministic relationship

Independence

Exercises

Practice

  1. H(X)=1.5, H(Y∣X)=0.8. Find H(X,Y).
  2. X and Y are independent with H(X)=2, H(Y)=1. Find H(X∣Y), H(X,Y) and I(X;Y).
  3. Y=X2 where X is equally likely to be −2,−1,1,2. Find H(X), H(Y), H(Y∣X), H(X∣Y) and I(X;Y).
  4. Can I(X;Y) be larger than H(X)? Explain.
  5. A source has H(Xn)=4 bits per symbol and H(Xn∣Xn−1)=3.2. Is its entropy rate more or less than 3.2?
  6. A model's average surprise on its training text is 1.0 bit per symbol and on new text 2.5. What does that suggest?
  7. Name the inequality that says a summary of data can't carry more information about a third variable than the data does.
Answers
  1. 2.3 bits.
  2. 2; 3; 0.
  3. H(X)=2; Y is 1 or 4, each with probability 12: H(Y)=1; H(Y∣X)=0; H(X∣Y)=1 (the sign); I=1.
  4. No: I(X;Y) =H(X)−H(X∣Y)≤H(X).
  5. At most 3.2: conditioning on more of the past can only lower it further.
  6. Overfitting: the model has memorised its training text and generalises poorly; the 2.5 bits is the honest figure.
  7. The data processing inequality.

Harder

  1. Prove that H(X,Y)≥H(X), and say when they're equal.
  2. Show that I(X;Y)=0 implies H(X,Y)=H(X)+H(Y), and the converse.
  3. A test for a condition with 1 % prevalence has 99 % sensitivity and 99 % specificity. Compute the mutual information between the condition and the result, and compare with the 0.081 bits of uncertainty about the condition.
  4. Explain why the conditional entropies H(Xn∣last k) estimated from training counts must keep falling as k grows, even if the true entropy rate has been reached.
  5. Give an example where H(Y∣X=x)>H(Y) for some particular x, even though H(Y∣X)≤H(Y).
Answers
  1. By the chain rule, H(X,Y)=H(X)+H(Y∣X), and H(Y∣X)≥0. Equal when Y is determined by X.
  2. I=H(X)+H(Y)−H(X,Y), so I=0 exactly when H(X,Y)=H(X)+H(Y); and I=0 exactly when X and Y are independent.
  3. P(positive) =0.01×0.99+0.99×0.01 =0.0198. H(result) =h(0.0198)≈0.1403. Given the condition, the result is wrong 1 % of the time either way, so H(result∣condition) =h(0.01)≈0.0808. I≈0.1403−0.0808 =0.0595 bits, out of the 0.0808 bits of uncertainty about the condition: the test removes about three quarters of it, though a positive result is still only 50 % likely to be right (Bayes: 0.0099/0.0198).
  4. With more context, each context appears fewer times in the training text, and with few observations the plug-in estimate of each conditional distribution is biased low (chapter 4): in the extreme, a context seen once predicts its single following symbol with probability 1 and surprise 0. So training estimates keep falling towards 0 as k grows, whatever the true rate.
  5. Y is "will it rain today?" with P=0.1 (H≈0.469), and X is the forecast; on the rare days the forecast says "50 % chance", H(Y∣X =that) =1 bit, more than H(Y). Other forecasts ("clear skies") lower the uncertainty, and on average it falls.

Challenge

  1. Fano's inequality says that if you estimate X (with K possible values) from Y and are wrong with probability Pe, then H(X∣Y)≤h(Pe)+Pelog2(K−1). Explain why it must hold, using grouping, and use it to show that a sensor with H(true∣reading) =1.723 bits (8 states) can't be used to guess the true state correctly more than about 70 % of the time.
Discussion

Let E be the event "the guess is wrong". Knowing Y, the uncertainty about X can be split (grouping) into the uncertainty about whether the guess is right, at most h(Pe), plus, when it's wrong, the uncertainty about which of the other K−1 values is true, at most log2(K−1), weighted by Pe. (When the guess is right, X is known.) So H(X∣Y)≤h(Pe)+Pelog2(K−1). For 8 states, find the smallest Pe with h(Pe)+Pelog27≥1.723: at Pe=0.3, h(0.3)+0.3×2.807≈0.881+0.842 =1.723. So any guessing rule errs at least 30 % of the time: right at most 70 %, which is exactly the sensor of the lab that produced this conditional entropy. Fano's inequality turns an information measure into a hard limit on accuracy, and chapter 9 uses it to prove the converse of the channel coding theorem.

In real life

Misconceptions and limits

The model to keep

Common misconceptions

Misconception What's actually true Where it's shown
"Learning something can make you less certain." On average it can't; a single observation can. Knowing more can't hurt, on average; harder exercise 12
"X tells you about Y more than Y tells you about X." Mutual information is symmetric. Mutual information; Experiment 1
"Zero correlation means no relationship." Mutual information catches any dependence; correlation only linear. In real life
"Each variable on its own shows whether it's informative." Two coins each tell nothing about "they match"; together they determine it. Worked example, independence
"A clever enough algorithm can extract more information than the data has." Processing can only lose it (data processing inequality). Experiment 4
"More context always predicts better." On unseen text, 7 letters of context did worse than 4. Experiment 2
"A model's surprise on its training data measures it." It's biased low; held-out surprise is the honest measure. Markov models of text
"A sensor that's right 70 % of the time gives 70 % of the information." It gave 1.28 of 3 bits, about 43 %. Experiment 3

Limits and trade-offs

  • Estimating mutual information is hard. With many values or continuous variables, plug-in estimates are biased (chapter 4), and the bias is worse for mutual information because it combines three entropies. Specialised estimators exist, and every estimate needs an uncertainty.
  • Mutual information says how much, not how. It measures dependence of any kind without describing its form; a large value says "these are related", not "this is how to predict one from the other".
  • More than two variables get complicated. With three or more, the information diagram's regions can be negative (the coins example: I(X;Y)=0 but I(X;Y∣Z)=1), and "how much information is shared by all three" has no single good definition.

Revision sheet

Key ideas

  • Joint entropy H(X,Y): entropy of the pair; ≤H(X)+H(Y), equal iff independent.
  • Conditional entropy H(Y∣X) =∑xp(x)H(Y∣X =x): average uncertainty left.
  • Chain rule: H(X,Y)=H(X)+H(Y∣X); for sequences, the sum of each symbol given the past.
  • Conditioning reduces entropy on average: H(Y∣X)≤H(Y).
  • Mutual information I(X;Y) =H(Y)−H(Y∣X) =H(X)+H(Y)−H(X,Y): symmetric, ≥0, =0 iff independent, ≤min(H(X),H(Y)).
  • Data processing inequality: X→Y→Z gives I(X;Z)≤I(X;Y).
  • Entropy rate H∞ =limH(Xn∣X1…Xn−1); the limit of compression for sources with memory.
  • Markov model of order k: predict from the last k symbols; on unseen text, longer isn't always better (overfitting).
  • Fano's inequality: H(X∣Y)≤h(Pe)+Pelog2(K−1) limits how well X can be guessed from Y.

Glossary

  • Joint entropy: the entropy of two (or more) random variables taken together, H(X,Y).
  • Conditional entropy: H(Y∣X), the average uncertainty about Y remaining once X is known.
  • Chain rule (entropy): H(X,Y)=H(X)+H(Y∣X): the information in a pair is the first plus the second given the first.
  • Mutual information: I(X;Y), how much knowing one variable reduces uncertainty about the other; symmetric and zero only for independent variables.
  • Information diagram: a picture of entropies as overlapping regions, with mutual information as the overlap.
  • Equivocation: Shannon's name for the uncertainty about the sent message that remains after receiving, H(X∣Y).
  • Data processing inequality: the theorem that processing data can't increase the information it carries about a third variable.
  • Markov chain (information): a sequence of variables in which each depends on the past only through the one before it; X→Y→Z.
  • Entropy rate: the long-run information per symbol of a source with memory, the limit of the conditional entropy of the next symbol given the past.
  • Markov model of order k: a model that predicts each symbol from the k symbols before it.
  • Overfitting: a model fitting the accidents of its training data so closely that it predicts new data worse.
  • Fano's inequality: a bound relating the conditional entropy H(X∣Y) to the best possible probability of error in guessing X from Y.