Information Theory Exercises
Time to practise the whole course. Each exercise has a starter program that runs but does not do the job yet. Replace the TODO parts, press ▶ Run, and compare your result with the expected output. The output block under each starter shows what the unfinished starter prints.
Tip: Check each function on a case you know by heart: a fair coin has 1 bit of entropy, independent variables have zero mutual information, and a perfect channel has capacity of its alphabet size.
| # | Exercise | Practises |
|---|---|---|
| 1 | An entropy function | entropy, the convention |
| 2 | Mutual information from a table | joint, marginals, KL form |
| 3 | Cross-entropy and KL | coding cost of a wrong model |
| 4 | Huffman code lengths | optimal symbol codes |
| 5 | Capacity with Blahut-Arimoto | channel capacity |
| 6 | Hamming syndrome decoding | linear codes, syndromes |
| 7 | A CRC check | error detection |
| 8 | Perplexity of a bigram model | language models, smoothing |
Exercise 1: An entropy function
Write H(p) in bits so that it ignores zero probabilities (Entropy).
import numpy as np
def H(p):
p = np.asarray(p, float)
return 0.0 # TODO: -sum p log2 p over the non-zero entries
for p in ([0.5, 0.5], [0.25] * 4, [0.9, 0.1, 0.0], [1.0, 0.0]):
print(p, round(H(p), 4))[0.5, 0.5] 0.0
[0.25, 0.25, 0.25, 0.25] 0.0
[0.9, 0.1, 0.0] 0.0
[1.0, 0.0] 0.0
Expected output when solved:
[0.5, 0.5] 1.0
[0.25, 0.25, 0.25, 0.25] 2.0
[0.9, 0.1, 0.0] 0.469
[1.0, 0.0] 0.0Solution
import numpy as np
def H(p):
p = np.asarray(p, float)
p = p[p > 0]
return float(-np.sum(p * np.log2(p))) + 0.0
for p in ([0.5, 0.5], [0.25] * 4, [0.9, 0.1, 0.0], [1.0, 0.0]):
print(p, round(H(p), 4))[0.5, 0.5] 1.0
[0.25, 0.25, 0.25, 0.25] 2.0
[0.9, 0.1, 0.0] 0.469
[1.0, 0.0] 0.0
The + 0.0 turns -0.0 (from a certain outcome) into 0.0.
Exercise 2: Mutual information from a table
Compute in bits from a joint probability table, using the KL form (Mutual Information).
import numpy as np
def mutual_information(P):
Px, Py = P.sum(axis=1), P.sum(axis=0)
return 0.0 # TODO: sum over cells with P > 0
P1 = np.array([[0.4, 0.1], [0.1, 0.4]])
P2 = np.outer([0.3, 0.7], [0.6, 0.4])
P3 = np.diag([0.25, 0.25, 0.25, 0.25])
print(round(mutual_information(P1), 4), round(mutual_information(P2), 4), round(mutual_information(P3), 4))0.0 0.0 0.0
Expected output when solved: the second table is independent, the third is a perfect copy of a 2-bit variable.
0.2781 0.0 2.0Solution
import numpy as np
def mutual_information(P):
Px, Py = P.sum(axis=1), P.sum(axis=0)
Q = np.outer(Px, Py); nz = P > 0
return max(0.0, float(np.sum(P[nz] * np.log2(P[nz] / Q[nz]))))
P1 = np.array([[0.4, 0.1], [0.1, 0.4]])
P2 = np.outer([0.3, 0.7], [0.6, 0.4])
P3 = np.diag([0.25, 0.25, 0.25, 0.25])
print(round(mutual_information(P1), 4), round(mutual_information(P2), 4), round(mutual_information(P3), 4))0.2781 0.0 2.0
Exercise 3: Cross-entropy and KL
Data come from and a compressor uses a code built for . Compute the average code length and the waste (Relative Entropy (KL Divergence)).
import numpy as np
P = np.array([0.6, 0.3, 0.1]); Q = np.array([0.4, 0.4, 0.2])
H_P = float(-np.sum(P * np.log2(P)))
cross = 0.0 # TODO: -sum P log2 Q
kl = 0.0 # TODO: sum P log2 (P / Q)
print(f"H(P) = {H_P:.4f}, H(P,Q) = {cross:.4f}, KL = {kl:.4f}, check: {abs(cross - H_P - kl) < 1e-12}")H(P) = 1.2955, H(P,Q) = 0.0000, KL = 0.0000, check: False
Expected output when solved:
H(P) = 1.2955, H(P,Q) = 1.4219, KL = 0.1265, check: TrueSolution
import numpy as np
P = np.array([0.6, 0.3, 0.1]); Q = np.array([0.4, 0.4, 0.2])
H_P = float(-np.sum(P * np.log2(P)))
cross = float(-np.sum(P * np.log2(Q)))
kl = float(np.sum(P * np.log2(P / Q)))
print(f"H(P) = {H_P:.4f}, H(P,Q) = {cross:.4f}, KL = {kl:.4f}, check: {abs(cross - H_P - kl) < 1e-12}")H(P) = 1.2955, H(P,Q) = 1.4219, KL = 0.1265, check: True
Exercise 4: Huffman code lengths
Complete Huffman's algorithm: repeatedly merge the two lightest nodes, adding one bit to every symbol below them (Huffman Coding).
import heapq
import numpy as np
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]
heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap)
# TODO: pop the second lightest node, add 1 to the length of every symbol in both,
# and push the merged node back with weight w1 + w2
break
return np.array(lengths)
P = np.array([0.3, 0.25, 0.2, 0.1, 0.1, 0.05])
L = huffman_lengths(P)
print("lengths:", L.tolist(), " expected length:", round(float(P @ L), 4), " entropy:", round(float(-np.sum(P * np.log2(P))), 4))lengths: [0, 0, 0, 0, 0, 0] expected length: 0.0 entropy: 2.366
Expected output when solved:
lengths: [2, 2, 2, 4, 3, 4] expected length: 2.4 entropy: 2.366Solution
import heapq
import numpy as np
def huffman_lengths(p):
heap = [(w, i, [i]) for i, w in enumerate(p)]
heapq.heapify(heap)
lengths = [0] * len(p); counter = len(p)
while len(heap) > 1:
w1, _, s1 = heapq.heappop(heap)
w2, _, s2 = heapq.heappop(heap)
for s in s1 + s2:
lengths[s] += 1
heapq.heappush(heap, (w1 + w2, counter, s1 + s2)); counter += 1
return np.array(lengths)
P = np.array([0.3, 0.25, 0.2, 0.1, 0.1, 0.05])
L = huffman_lengths(P)
print("lengths:", L.tolist(), " expected length:", round(float(P @ L), 4), " entropy:", round(float(-np.sum(P * np.log2(P))), 4))lengths: [2, 2, 2, 4, 3, 4] expected length: 2.4 entropy: 2.366
Exercise 5: Capacity with Blahut-Arimoto
Complete the update and compute the capacity of a ternary channel (Computing Capacity: Blahut-Arimoto).
import numpy as np
Q = np.array([[0.7, 0.2, 0.1],
[0.1, 0.8, 0.1],
[0.1, 0.1, 0.8]])
p = np.ones(3) / 3
for _ in range(500):
py = p @ Q
D = np.sum(Q * np.log2(Q / py), axis=1) # KL of each row from the output distribution
# TODO: p = p * 2**D, then normalize
print("capacity:", round(float(p @ D), 4), " input distribution:", np.round(p, 4))capacity: 0.5799 input distribution: [0.3333 0.3333 0.3333]
Expected output when solved:
capacity: 0.5831 input distribution: [0.2933 0.3324 0.3743]Solution
import numpy as np
Q = np.array([[0.7, 0.2, 0.1],
[0.1, 0.8, 0.1],
[0.1, 0.1, 0.8]])
p = np.ones(3) / 3
for _ in range(500):
py = p @ Q
D = np.sum(Q * np.log2(Q / py), axis=1)
p = p * np.exp2(D); p /= p.sum()
print("capacity:", round(float(p @ D), 4), " input distribution:", np.round(p, 4))capacity: 0.5831 input distribution: [0.2933 0.3324 0.3743]
The noisiest input (the first row) is used least.
Exercise 6: Hamming syndrome decoding
Decode received words of the Hamming code: compute the syndrome, find the column of that matches it, and flip that bit (The (7,4) Hamming Code).
import numpy as np
P = np.array([[1, 0, 1], [1, 1, 0], [1, 1, 1], [0, 1, 1]])
H = np.hstack([P.T, np.eye(3, dtype=int)])
def decode(r):
r = r.copy()
z = H @ r % 2
# TODO: if z is not zero, flip the bit j whose column H[:, j] equals z
return r[:4]
for word in ["1001001", "1111111", "0110011"]:
r = np.array([int(c) for c in word])
print(word, "->", "".join(map(str, decode(r))))1001001 -> 1001
1111111 -> 1111
0110011 -> 0110
Expected output when solved:
1001001 -> 1011
1111111 -> 1111
0110011 -> 0110Solution
import numpy as np
P = np.array([[1, 0, 1], [1, 1, 0], [1, 1, 1], [0, 1, 1]])
H = np.hstack([P.T, np.eye(3, dtype=int)])
def decode(r):
r = r.copy()
z = H @ r % 2
if z.any():
j = next(j for j in range(7) if np.array_equal(H[:, j], z))
r[j] ^= 1
return r[:4]
for word in ["1001001", "1111111", "0110011"]:
r = np.array([int(c) for c in word])
print(word, "->", "".join(map(str, decode(r))))1001001 -> 1011
1111111 -> 1111
0110011 -> 0110
The first word is the codeword 1011001 with bit 2 flipped, and the third is 0110001 with a parity bit flipped. 1111111 is a codeword (its syndrome is zero), so nothing is flipped.
Exercise 7: A CRC check
Finish the polynomial division that computes CRC check bits with the generator , then detect a corrupted message (Error Detection and CRCs).
def crc_remainder(bits, poly):
r = len(poly) - 1
work = list(bits) + [0] * r
for i in range(len(bits)):
pass # TODO: if work[i] is 1, XOR poly into work[i : i + len(poly)]
return work[-r:]
g = [1, 0, 1, 1]
msg = [1, 1, 0, 1, 0, 1, 1]
check = crc_remainder(msg, g)
print("check bits:", check)
bad = msg.copy(); bad[2] ^= 1
print("corruption detected:", crc_remainder(bad, g) != check)check bits: [0, 0, 0]
corruption detected: False
Expected output when solved:
check bits: [1, 1, 0]
corruption detected: TrueSolution
def crc_remainder(bits, poly):
r = len(poly) - 1
work = list(bits) + [0] * r
for i in range(len(bits)):
if work[i]:
for j, p in enumerate(poly):
work[i + j] ^= p
return work[-r:]
g = [1, 0, 1, 1]
msg = [1, 1, 0, 1, 0, 1, 1]
check = crc_remainder(msg, g)
print("check bits:", check)
bad = msg.copy(); bad[2] ^= 1
print("corruption detected:", crc_remainder(bad, g) != check)check bits: [1, 1, 0]
corruption detected: True
Exercise 8: Perplexity of a bigram model
Fit an add-one-smoothed bigram model on training text and compute its perplexity on test text (Perplexity). The starter uses a uniform model.
import numpy as np
train = "the cat sat on the mat the cat ate the rat " * 20
test = "the rat sat on the cat "
chars = sorted(set(train + test)); idx = {c: i for i, c in enumerate(chars)}
V = len(chars)
counts = np.ones((V, V)) # add-one smoothing
for a, b in zip(train, train[1:]):
pass # TODO: counts[idx[a], idx[b]] += 1
probs = counts / counts.sum(axis=1, keepdims=True)
logp = [np.log2(probs[idx[a], idx[b]]) for a, b in zip(test, test[1:])]
print(f"cross-entropy {-np.mean(logp):.4f} bits/char, perplexity {2 ** -np.mean(logp):.4f} (alphabet size {V})")cross-entropy 3.4594 bits/char, perplexity 11.0000 (alphabet size 11)
Expected output when solved:
cross-entropy 1.0835 bits/char, perplexity 2.1191 (alphabet size 11)Solution
import numpy as np
train = "the cat sat on the mat the cat ate the rat " * 20
test = "the rat sat on the cat "
chars = sorted(set(train + test)); idx = {c: i for i, c in enumerate(chars)}
V = len(chars)
counts = np.ones((V, V))
for a, b in zip(train, train[1:]):
counts[idx[a], idx[b]] += 1
probs = counts / counts.sum(axis=1, keepdims=True)
logp = [np.log2(probs[idx[a], idx[b]]) for a, b in zip(test, test[1:])]
print(f"cross-entropy {-np.mean(logp):.4f} bits/char, perplexity {2 ** -np.mean(logp):.4f} (alphabet size {V})")cross-entropy 1.0835 bits/char, perplexity 2.1191 (alphabet size 11)
Without training counts the model is uniform and its perplexity equals the alphabet size.
Test yourself
A function returns a slightly negative mutual information such as -1e-17. What is the most likely cause?
- Floating-point rounding; clip it to zero
- The variables are anti-correlated
- The table is not a probability table
- Mutual information can be negative
Which code reaches the entropy exactly for P = (1/2, 1/4, 1/8, 1/8)?
- a Huffman code with lengths (1, 2, 3, 3)
- a fixed 2-bit code
- a repetition code
- no symbol code can
A Hamming-coded word has syndrome zero. The decoder…
- accepts the word as a codeword
- flips the first bit
- requests a retransmission
- flips all bits