TExcelTAD
Home › Information Theory › Information Theory with Python

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:

python · try it yourself
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 ee gives nats and base 10 gives hartleys (or bans). They differ by a constant factor: log⁡2x=ln⁡xln⁡2\log_2 x = \frac{\ln x}{\ln 2}, so 1 nat is about 1.443 bits.

python · try it yourself
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 plog⁡pp \log p, which is undefined at p=0p = 0. Since plog⁡p→0p \log p \to 0 as p→0p \to 0, information theory defines 0log⁡0=00 \log 0 = 0. In NumPy, 0 * np.log2(0) gives nan with a warning, so the helper masks out zeros:

python · try it yourself
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:

python · try it yourself
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):

python · try it yourself
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.

python · try it yourself
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 when q is given.
  • np.unique(..., return_counts=True) and np.bincount count symbols; collections.Counter does the same for Python objects.
  • zlib, bz2 and lzma in 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 1ln⁡2≈1.4427\frac{1}{\ln 2} \approx 1.4427: 2×1.4427=2.8852 \times 1.4427 = 2.885.

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 0log⁡0=00 \log 0 = 0 the entropy of a certain outcome is −1⋅log⁡21=0-1 \cdot \log_2 1 = 0.

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
python · try it yourself
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…

  1. bits
  2. nats
  3. bytes
  4. hartleys

What value does information theory give to 0log⁡00 \log 0?

  1. 0
  2. 1
  3. minus infinity
  4. undefined

Why do the simulations use np.random.default_rng(seed)?

  1. It is faster than any other method
  2. It makes the results reproducible
  3. It avoids zero probabilities
  4. It is required by SciPy