Information Theory with Python
Information theory needs only a few tools in code: probability vectors, logarithms in base 2, counting symbols, and random sampling from a seeded generator. This lesson sets up the helpers that later lessons reuse and shows the pitfalls (zero probabilities, floating-point sums, the base of the logarithm).
Probability vectors
A discrete distribution is a NumPy array of non-negative numbers that sum to 1. Estimating one from data means counting:
import numpy as np
text = "abracadabra"
symbols, counts = np.unique(list(text), return_counts=True)
p = counts / counts.sum()
for s, c, q in zip(symbols, counts, p):
print(s, c, round(float(q), 4))
print("sums to 1:", bool(np.isclose(p.sum(), 1)))a 5 0.4545
b 2 0.1818
c 1 0.0909
d 1 0.0909
r 2 0.1818
sums to 1: True
Logarithms and units
Information is measured with logarithms. Base 2 gives bits, base gives nats and base 10 gives hartleys (or bans). They differ by a constant factor: , so 1 nat is about 1.443 bits.
import numpy as np
x = 8.0
print("log2:", np.log2(x), " ln:", round(float(np.log(x)), 4), " log10:", round(float(np.log10(x)), 4))
print("1 nat in bits:", round(1 / np.log(2), 4))log2: 3.0 ln: 2.0794 log10: 0.9031
1 nat in bits: 1.4427
The zero-probability convention
The entropy formula contains , which is undefined at . Since as , information theory defines . In NumPy, 0 * np.log2(0) gives nan with a warning, so the helper masks out zeros:
import numpy as np
def entropy(p, base=2):
p = np.asarray(p, float)
nz = p > 0
return float(-np.sum(p[nz] * np.log(p[nz])) / np.log(base))
print("fair coin:", entropy([0.5, 0.5]))
print("with a zero entry:", round(entropy([0.5, 0.5, 0.0]), 4))
print("abracadabra:", round(entropy([5, 2, 1, 1, 2] / np.array(11.0)), 4), "bits per letter")
print("same in nats:", round(entropy([0.5, 0.5], base=np.e), 4))fair coin: 1.0
with a zero entry: 1.0
abracadabra: 2.0404 bits per letter
same in nats: 0.6931
SciPy's scipy.stats.entropy does the same and also normalizes counts for you:
import numpy as np
from scipy.stats import entropy
print(round(float(entropy([5, 2, 1, 1, 2], base=2)), 4))2.0404
Sampling and simulation
Many results in this course are checked by simulation. Always use a seeded generator, np.random.default_rng(seed), so the numbers are reproducible. Sampling a long message from a distribution and measuring the frequencies shows the law of large numbers at work (The Law of Large Numbers):
import numpy as np
rng = np.random.default_rng(42)
p = np.array([0.5, 0.25, 0.125, 0.125])
msg = rng.choice(4, size=100_000, p=p)
freq = np.bincount(msg, minlength=4) / msg.size
print("frequencies:", np.round(freq, 4))
print("largest deviation:", round(float(np.max(np.abs(freq - p))), 4))frequencies: [0.4974 0.2529 0.1246 0.125 ]
largest deviation: 0.0029
Bits and bytes
Codes in this course are arrays of 0/1 integers. np.packbits and np.unpackbits convert between bit arrays and bytes, which is how we measure real compressed sizes.
import numpy as np
bits = np.array([1, 0, 1, 1, 0, 0, 0, 1, 1, 1], dtype=np.uint8)
packed = np.packbits(bits)
print("bytes:", packed.tolist(), " length:", len(packed))
print("unpacked:", np.unpackbits(packed)[:bits.size].tolist())bytes: [177, 192] length: 2
unpacked: [1, 0, 1, 1, 0, 0, 0, 1, 1, 1]
In software
scipy.stats.entropy(p, q=None, base=None)gives entropy, or KL divergence whenqis given.np.unique(..., return_counts=True)andnp.bincountcount symbols;collections.Counterdoes the same for Python objects.zlib,bz2andlzmain the standard library measure real compression.
Exercises
Exercise 1: Unit conversion
A distribution has entropy 2 nats. How many bits is that?
Answer
About 2.885 bits.
Solution
Multiply by : .
Exercise 2: Why mask zeros?
What does -np.sum(p * np.log2(p)) return for p = [1.0, 0.0], and what should it return?
Answer
It returns nan; the right value is 0.
Solution
0 * log2(0) is 0 * -inf = nan in floating point. With the convention the entropy of a certain outcome is .
Exercise 3: Entropy of a word (code)
Compute the entropy per letter of the word mississippi in bits.
Answer
About 1.823 bits per letter.
Solution
import numpy as np
_, counts = np.unique(list("mississippi"), return_counts=True)
p = counts / counts.sum()
print(counts.tolist(), round(float(-np.sum(p * np.log2(p))), 4))[4, 1, 2, 4] 1.8231
Test yourself
Entropy measured with the natural logarithm is in…
- bits
- nats
- bytes
- hartleys
What value does information theory give to ?
- 0
- 1
- minus infinity
- undefined
Why do the simulations use np.random.default_rng(seed)?
- It is faster than any other method
- It makes the results reproducible
- It avoids zero probabilities
- It is required by SciPy