Information Theory CompanionInformation Theory · Companion
0 / 0

Workbench / Information Theory Companion

B1·07

Joint and Conditional Entropy, Mutual Information

Around chapter 7: how joint and conditional entropy, mutual information and entropy rates connect the book; three other ways to see them; what the chapter simplifies (information can hide in combinations that no pair shows, information present isn't information easy to use, and estimates of continuous mutual information depend on how you cut the data); how scikit-learn computes mutual information and why its "adjusted" version exists; four debugging drills; and interview questions.

6 topics · ~17 min read
Updated Suggest a correction

Understanding it better

Concept map

  • Conditional probability (chapter 3) + entropy (chapter 4) → conditional entropy H(Y∣X).
  • Chain rule H(X,Y)=H(X)+H(Y∣X) → grouping in another form → compressors code each symbol given the past.
  • Conditioning reduces entropy on average → mutual information I(X;Y) =H(Y)−H(Y∣X)≥0.
  • Mutual information: symmetric, zero iff independent, ≤ min of the entropies → a KL divergence (chapter 11).
  • Data processing inequality → no computation creates information → sufficient statistics, data retention.
  • Entropy rate → the limit of compression for sources with memory → Markov models of text → overfitting → held-out measurement (chapter 11's cross-entropy).
  • Fano's inequality → information limits accuracy → chapter 9's converse.
  • Channels: the lying sensor is a noisy channel; its best mutual information is the capacity (chapter 9).

Explain it differently

A Venn diagram of uncertainty. Draw your uncertainty about the weather as one circle and about my umbrella as another. They overlap because the umbrella hints at the weather. Learning about the umbrella erases the overlap from the weather circle; what's left is how unsure you still are. The overlap is the same size from either side.

Twenty questions with a friend's help. You're playing twenty questions about X, and a friend who knows Y can answer one question of their choice for free. The questions you save, on average, are the mutual information I(X;Y). If the friend's knowledge is unrelated, you save nothing; if it determines X, you save everything.

A photocopier of a photocopy. Each copy of a copy can only lose detail, never add it back: that's the data processing inequality. A "smart" copier that sharpens the image makes it look crisper, but any detail it adds came from its own assumptions about what documents look like, not from the original.

Gaps and misconceptions

What the chapter oversimplifies

1. "Measure the information between variables", but information can live only in combinations. Checking variables two at a time can miss everything:

Python
import random
from info import joint_report
random.seed(2)
rows = []
for _ in range(100_000):
    x, y = random.getrandbits(1), random.getrandbits(1)
    rows.append((x, y, x ^ y))                     # z is the parity of x and y
print(f"I(x; z) = {joint_report([(x, z) for x, y, z in rows])['I(X;Y)']:.4f} bits")
print(f"I(y; z) = {joint_report([(y, z) for x, y, z in rows])['I(X;Y)']:.4f} bits")
print(f"I(x; y) = {joint_report([(x, y) for x, y, z in rows])['I(X;Y)']:.4f} bits")
print(f"I((x, y); z) = {joint_report([((x, y), z) for x, y, z in rows])['I(X;Y)']:.4f} bits")
Text
I(x; z) = 0.0000 bits
I(y; z) = 0.0000 bits
I(x; y) = 0.0000 bits
I((x, y); z) = 1.0000 bits

z is the parity of two fair bits x and y. Each pair of the three shares 0.0000 bits, so a screen of pairwise mutual information would call them unrelated; yet x and y together determine z completely (1 bit). The chapter's worked example with coins showed it in theory; here it is in 100,000 rows. Real data has milder versions (a drug that only works for patients with a particular gene, a failure that only happens when two settings combine). Feature screening by pairwise mutual information is a heuristic: it misses interactions, which is part of why models that learn combinations (trees, neural networks) beat pairwise filters.

2. "Mutual information measures how much X tells you about Y", which isn't how easy it is to use. y=x2 is fully determined by x:

Python
import random, statistics
from collections import Counter, defaultdict
from info import joint_report
random.seed(5)
xs = [random.choice(range(-3, 4)) for _ in range(20_000)]
ys = [x * x for x in xs]
print(f"I(x; y) = {joint_report(list(zip(xs, ys)))['I(X;Y)']:.3f} bits of {joint_report(list(zip(xs, ys)))['H(Y)']:.3f}")
slope, intercept = statistics.linear_regression(xs, ys)
lin = sum((y - (slope * x + intercept)) ** 2 for x, y in zip(xs, ys)) / len(xs)
by_x = defaultdict(list)
for x, y in zip(xs, ys):
    by_x[x].append(y)
table = {x: statistics.mean(v) for x, v in by_x.items()}
look = sum((y - table[x]) ** 2 for x, y in zip(xs, ys)) / len(xs)
print(f"best straight line: y = {slope:.3f} x + {intercept:.3f}, mean squared error {lin:.2f} (the variance of y is {statistics.pvariance(ys):.2f})")
print(f"a lookup table from x: mean squared error {look:.2f}")
Text
I(x; y) = 1.945 bits of 1.945
best straight line: y = -0.014 x + 3.998, mean squared error 11.93 (the variance of y is 11.93)
a lookup table from x: mean squared error 0.00

x carries all 1.945 bits of y's uncertainty, but the best straight line through the data is flat (slope −0.014), and its error equals y's whole variance: a linear model uses none of the information. A lookup table from x predicts y perfectly. Mutual information says the information is there; whether a model can use it depends on the model. That's why high mutual information with a weak model's poor accuracy is a sign to try a more flexible model, not a sign the feature is useless.

3. "Mutual information doesn't depend on units", unless you estimate it by cutting data into bins. For continuous variables the true mutual information is well defined, but plug-in estimates need the data cut into bins, and the number of bins changes the answer:

Python
import math, random
from info import joint_report
random.seed(6)
rho, n = 0.8, 20_000
pts = []
for _ in range(n):
    a, b = random.gauss(0, 1), random.gauss(0, 1)
    pts.append((a, rho * a + math.sqrt(1 - rho * rho) * b))
print(f"two normal variables with correlation {rho}: true mutual information {-0.5 * math.log2(1 - rho * rho):.3f} bits")
for bins in (2, 4, 8, 16, 64, 256, 1024):
    cut = lambda v: min(bins - 1, max(0, int((v + 4) / 8 * bins)))      # equal-width bins over -4 to 4
    est = joint_report([(cut(x), cut(y)) for x, y in pts])["I(X;Y)"]
    print(f"{bins:>5} bins per variable: estimate {est:.3f} bits")
Text
two normal variables with correlation 0.8: true mutual information 0.737 bits
    2 bins per variable: estimate 0.273 bits
    4 bins per variable: estimate 0.352 bits
    8 bins per variable: estimate 0.577 bits
   16 bins per variable: estimate 0.695 bits
   64 bins per variable: estimate 0.798 bits
  256 bins per variable: estimate 1.343 bits
 1024 bins per variable: estimate 3.895 bits

Two normal variables with correlation 0.8 share exactly −12log2(1−0.64)≈0.737 bits. With 2 bins per variable the estimate is 0.27 (coarse bins throw information away: the data processing inequality); with 16 bins, 0.70; with 64, 0.80 (bias creeping in); with 1,024 bins, 3.9 bits, almost all bias, since most of the million cells hold one point or none. There's no right number of bins in general: estimators for continuous data (k-nearest-neighbour estimators such as Kraskov's, from 2004) avoid bins altogether, and any binned figure should come with the bin count and a shuffled baseline.

Common misconceptions

Misconception What's actually true Where it's shown
"If no pair of variables is related, none of them are." Parity: every pair shares 0 bits, the three together are fully dependent. What the chapter oversimplifies, point 1
"High mutual information means a model will predict well." A straight line used none of x's 1.945 bits about x2. What the chapter oversimplifies, point 2
"A binned estimate of continuous mutual information is the value." 2 bins gave 0.27 bits, 1,024 gave 3.9, for a true 0.737. What the chapter oversimplifies, point 3
"scikit-learn's mutual information is in bits." It uses natural logarithms: nats. Code walkthrough
"Raw mutual information compares fairly across label sets." Independent 50-value labels scored 1.65 bits; the adjusted score was about 0. Code walkthrough
"Sorting each column of a table doesn't change its statistics." It invents dependence: 0.02 bits became 2.87. Drill D1
"H(Y given X) is H(Y) minus H(X)." It's H(X, Y) minus H(X); the wrong formula even goes negative. Drill D2
"Add a small count to each symbol" is enough for smoothing. The denominator must add it for every symbol too, or probabilities don't add to 1. Drill D3
"Mutual information functions accept measurements." Given floats, each value is its own label, and the score is log₂ n. Drill D4

Theoretical gaps: the ideas behind the chapter

  • Mutual information as a divergence. I(X;Y) is the Kullback–Leibler divergence between the joint distribution and the product of the marginals: how far the data is from independence. Chapter 11 develops divergence; Sanov's theorem then explains why independent data rarely looks dependent in large samples.
  • The information bottleneck. Naftali Tishby, Fernando Pereira and William Bialek (1999) asked for a compressed representation T of X that keeps as much information about Y as possible: minimise I(X;T)−βI(T;Y). It's a way to state what a good summary is, and it has been used to study how neural networks learn.
  • Interaction information and synergy. The parity example has positive "synergy": information present only in combination. Partial information decomposition tries to split I(X,Y;Z) into redundant, unique and synergistic parts; several incompatible definitions exist.

Applying it

Code walkthrough

scikit-learn's mutual_info_score computes mutual information from a contingency table. Excerpt from sklearn/metrics/cluster/_supervised.py in scikit-learn 1.9 (on your computer: python3 -c "import sklearn.metrics.cluster._supervised as m; print(m.__file__)"), after the inputs have been turned into a table of counts:

Python
    contingency_sum = contingency.sum()
    pi = np.ravel(contingency.sum(axis=1))
    pj = np.ravel(contingency.sum(axis=0))

    # Since MI <= min(H(X), H(Y)), any labelling with zero entropy, i.e. containing a
    # single cluster, implies MI = 0
    if pi.size == 1 or pj.size == 1:
        return 0.0

    log_contingency_nm = np.log(nz_val)
    contingency_nm = nz_val / contingency_sum
    # Don't need to calculate the full outer product, just for non-zeroes
    outer = pi.take(nzx).astype(np.int64, copy=False) * pj.take(nzy).astype(
        np.int64, copy=False
    )
    log_outer = -np.log(outer) + log(pi.sum()) + log(pj.sum())
    mi = (
        contingency_nm * (log_contingency_nm - log(contingency_sum))
        + contingency_nm * log_outer
    )
    mi = np.where(np.abs(mi) < np.finfo(mi.dtype).eps, 0.0, mi)
    return float(np.clip(mi.sum(), 0.0, None))

pi and pj are the row and column totals (the marginal counts), and nz_val are the non-zero cells of the table. Each term is the chapter's p(x,y)logp(x,y)p(x)p(y), rearranged in counts: lognxyN plus logN2nxny. Four details stand out. It uses natural logarithms, so the answer is in nats. It skips zero cells (their terms are 0, the chapter's convention). It returns 0 at once if either labelling has one value, because mutual information can't exceed either entropy. And it clips the final sum at 0, because rounding can make a tiny true value come out slightly negative, and mutual information can't be negative. Measured:

Python
import math, random
from sklearn.metrics import adjusted_mutual_info_score, mutual_info_score
from info import joint_report
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)]
weather, umbrella = [w for w, _ in pairs], [u for _, u in pairs]
mi = mutual_info_score(weather, umbrella)
print(f"sklearn: {mi:.4f} nats = {mi / math.log(2):.4f} bits; info.py: {joint_report(pairs)['I(X;Y)']:.4f} bits")
print("one label everywhere:", mutual_info_score(["a"] * 5, [1, 2, 3, 4, 5]))
random.seed(8)
x = [random.randrange(50) for _ in range(1000)]
y = [random.randrange(50) for _ in range(1000)]           # independent of x
print(f"independent 50-value labels, 1,000 samples: MI {mutual_info_score(x, y) / math.log(2):.3f} bits; adjusted MI {adjusted_mutual_info_score(x, y):+.4f}")
Text
sklearn: 0.1832 nats = 0.2643 bits; info.py: 0.2643 bits
one label everywhere: 0.0
independent 50-value labels, 1,000 samples: MI 1.653 bits; adjusted MI +0.0087

On the umbrella data, scikit-learn gives 0.1832 nats, which is the chapter's 0.2643 bits. A labelling with one value gives exactly 0. And two independent labellings with 50 values each, from 1,000 samples, score 1.653 bits of "mutual information", the exercises' P2 bias; scikit-learn's adjusted_mutual_info_score subtracts the value expected by chance for tables of that shape and scales the result, giving about 0, which is why it's the one to use for comparing labellings.

Read it yourself

Using the code above: why does the function compute log(pi.sum()) + log(pj.sum()) rather than 2 * log(contingency_sum), when all three sums are the same number? And why clip at 0 instead of raising an error when the sum is negative?

Debugging drills

D1. Dependence created by sorting

An analyst finds 2.87 bits of mutual information between people's heights and shoe sizes in a survey, far more than expected. The data was generated with the two independent.

Python
import random
from info import joint_report
random.seed(3)
heights = [random.gauss(170, 10) for _ in range(5000)]
shoe = [random.gauss(42, 2) for _ in range(5000)]          # generated independently of height
h_band = [round(h / 5) for h in heights]
s_band = [round(s) for s in shoe]
print("as recorded:              I =", round(joint_report(list(zip(h_band, s_band)))["I(X;Y)"], 3), "bits")
print("after sorting each column: I =", round(joint_report(list(zip(sorted(h_band), sorted(s_band))))["I(X;Y)"], 3), "bits")
Text
as recorded:              I = 0.022 bits
after sorting each column: I = 2.867 bits

D2. A negative conditional entropy

A dashboard reports H(weather∣umbrella) =−0.114 bits.

Python
from collections import Counter
from info import H
pairs = [("rain", "umbrella")] * 50 + [("rain", "none")] * 10 + [("dry", "umbrella")] * 30 + [("dry", "none")] * 275
hx = H(Counter(w for w, _ in pairs)); hy = H(Counter(u for _, u in pairs))
print(f"H(umbrella | weather) = H(umbrella) - H(weather) = {hy - hx:.4f} bits")
print(f"H(weather | umbrella) = H(weather) - H(umbrella) = {hx - hy:.4f} bits")
Text
H(umbrella | weather) = H(umbrella) - H(weather) = 0.1140 bits
H(weather | umbrella) = H(weather) - H(umbrella) = -0.1140 bits

D3. A model that's better than it should be

An order-3 letter model scores 2.332 bits per symbol on unseen text, better than the chapter's 2.422 for the same model.

Python
import math
from collections import Counter, defaultdict
text = open("data/shakespeare.txt", encoding="utf-8").read().lower()
s = " ".join("".join(c if "a" <= c <= "z" else " " for c in text).split())
cut = int(len(s) * 0.9); train, test = s[:cut], s[cut:]
k, alpha, K = 3, 0.5, 27
table = defaultdict(Counter)
for i in range(k, len(train)):
    table[train[i - k:i]][train[i]] += 1
def p(ctx, ch):
    c = table.get(ctx, Counter())
    return (c[ch] + alpha) / (sum(c.values()) + alpha)
bits = -sum(math.log2(p(test[i - k:i], test[i])) for i in range(k, len(test))) / (len(test) - k)
print(f"order-3 model on unseen text: {bits:.3f} bits per symbol")
rare = next(c for c, v in table.items() if sum(v.values()) == 1)
for ctx in ("the", rare):
    print(f"after '{ctx}' (seen {sum(table[ctx].values()):,} times) the 27 probabilities add up to {sum(p(ctx, ch) for ch in ' abcdefghijklmnopqrstuvwxyz'):.3f}")
Text
order-3 model on unseen text: 2.332 bits per symbol
after 'the' (seen 10,730 times) the 27 probabilities add up to 1.001
after 'pa ' (seen 1 times) the 27 probabilities add up to 9.667

D4. Mutual information of 11 bits between independent measurements

Two independent sensor readings, given straight to mutual_info_score, share 10.966 bits.

Python
import math, random, warnings
from sklearn.metrics import mutual_info_score
random.seed(4)
a = [random.gauss(0, 1) for _ in range(2000)]
b = [random.gauss(0, 1) for _ in range(2000)]               # independent of a
with warnings.catch_warnings(record=True) as w:
    warnings.simplefilter("always")
    mi = mutual_info_score(a, b)
print("warning:", str(w[0].message)[:60] if w else "none")
print(f"mutual_info_score on raw measurements: {mi / math.log(2):.3f} bits (log2 2000 = {math.log2(2000):.3f})")
Text
warning: Clustering metrics expects discrete values but received cont
mutual_info_score on raw measurements: 10.966 bits (log2 2000 = 10.966)

Career-oriented

Interview prep

Mid level

Q1. What's the difference between mutual information and correlation? When would you use each?

How to get there. Linear against any dependence; data needs.

Q2. Explain conditional entropy and the chain rule with an example.

How to get there. Dice, or weather and umbrellas.

Senior level

Q3. How would you select features for a model using mutual information, and what are the pitfalls?

How to get there. Ranking by I(feature;label), then the companion's points.

Q4. A team reports that their new model has lower cross-entropy on the training set than the old one, and wants to ship. What do you ask?

How to get there. Training figures are biased; held-out data.

Staff level

Q5. Your company wants to reduce storage costs by keeping only daily aggregates of event data after 7 days. Product teams worry about losing future analyses. How do you frame the decision?

How to get there. The data processing inequality, and what each aggregate keeps.

Q6. A vendor claims their AI can "recover the missing detail" in low-resolution security camera footage for use as evidence. How do you assess the claim?

How to get there. Data processing inequality, and where added detail comes from.