Information Theory Intro
Every time you zip a file, stream a video, send a message over Wi-Fi or train a language model, you rely on ideas from information theory. Claude Shannon created the field in 1948 with one question: how many bits does it take to describe a message, and how many bits per second can a noisy wire carry reliably? His answers are two theorems that still set the limits for every compressor and every modem.
This course is information theory for programmers. Every definition is computed in NumPy, every theorem is checked by simulation, and every code is implemented and tested.
The two central questions
| Question | Answer | Where |
|---|---|---|
| How short can a description of data be? | about bits per symbol, the entropy | The Source Coding Theorem |
| How fast can we send data reliably over a noisy channel? | up to bits per use, the capacity | The Noisy-Channel Coding Theorem |
The surprising part of the second answer is that the error probability can be made as small as we like without the rate going to zero, as long as we stay below capacity.
The reference book
The topic order follows one book, used only as a map of topics:
- Information Theory, Inference, and Learning Algorithms by David J. C. MacKay (Cambridge University Press, 2003). MacKay made the whole book freely available at inference.org.uk/mackay/itila. Its order (entropy, data compression with typical sets and symbol codes, noisy channels, error-correcting codes up to sparse-graph codes) is the order of this course.
Thanks to the late David MacKay for this book and for making it free to read. All explanations, numbers, code and exercises here are original, written for programmers, with runnable Python.
What is in the course
| Part | Topics |
|---|---|
| 1. Measuring information | surprise, entropy, joint and conditional entropy, mutual information, KL divergence, cross-entropy, Jensen and Gibbs, data processing, Fano |
| 2. Data compression | counting and typical sets, the source coding theorem, prefix codes, Kraft, Huffman, arithmetic coding, Lempel-Ziv, real compressors |
| 3. Noisy channels | channel models, the binary symmetric channel, capacity, Blahut-Arimoto, erasure and Z channels, the coding theorem and its converse |
| 4. Error-correcting codes | repetition and Hamming codes, linear codes, syndromes, distance bounds, CRCs, LDPC codes and their decoders |
| 5. Continuous information | differential entropy, the Gaussian channel, rate-distortion, quantization |
| 6. Machine learning | cross-entropy loss, perplexity, information gain, feature selection, maximum entropy, the information bottleneck |
What you should know first
- Probability for random variables, expectation, independence and Bayes' theorem. Probability Review for Information Theory recaps what we need.
- Calculus Essentials for logarithms and derivatives, and Linear Algebra & Matrix Theory for the matrices of the coding chapter.
- NumPy for arrays.
- Math for Deep Learning & LLMs covers entropy and KL, cross-entropy as maximum likelihood and perplexity from the deep-learning side; this course links there instead of repeating it.
Here is the whole course in miniature. A biased source emits a 70% of the time and b, c 15% each. Its entropy is about 1.18 bits per symbol, less than the 1.58 bits needed to label one of three symbols, and a real compressor gets close to that limit:
import numpy as np
import zlib
p = np.array([0.7, 0.15, 0.15])
H = -np.sum(p * np.log2(p))
print(f"entropy: {H:.3f} bits/symbol (log2 3 = {np.log2(3):.3f})")
rng = np.random.default_rng(0)
msg = "".join(rng.choice(list("abc"), size=100_000, p=p))
packed = zlib.compress(msg.encode(), 9)
print(f"zlib: {8 * len(packed) / len(msg):.3f} bits/symbol")entropy: 1.181 bits/symbol (log2 3 = 1.585)
zlib: 1.519 bits/symbol
No lossless compressor can beat the entropy on average. zlib is general purpose and needs about 1.52 bits here, well above the limit; Arithmetic Coding gets within a fraction of a percent.
Now the other half: a noisy channel that flips each bit with probability 0.1. Sending each bit three times and taking a majority vote lowers the error rate, at the cost of a third of the speed:
import numpy as np
rng = np.random.default_rng(1)
bits = rng.integers(0, 2, 100_000)
noisy = bits ^ (rng.random(bits.size) < 0.1)
print("uncoded bit error rate:", round(float(np.mean(noisy != bits)), 4))
sent = np.repeat(bits, 3)
received = sent ^ (rng.random(sent.size) < 0.1)
decoded = (received.reshape(-1, 3).sum(axis=1) >= 2).astype(int)
print("repetition-3 bit error rate:", round(float(np.mean(decoded != bits)), 4), " rate: 1/3")uncoded bit error rate: 0.0984
repetition-3 bit error rate: 0.0278 rate: 1/3
Shannon showed that much better trade-offs exist: this channel can carry about 0.53 bits per use with error rate as small as we like. Chapters 3 and 4 show how close real codes get.
In software
scipy.stats.entropycomputes entropy and KL divergence;sklearn.metrics.mutual_info_scorecomputes mutual information from labels.- Python's
zlib,bz2andlzmamodules are real compressors you can measure against the entropy. - Every deep-learning framework's cross-entropy loss is an information-theoretic quantity (Cross-Entropy as a Loss).
Exercises
Exercise 1: Bits for a label
How many bits does a fixed-length binary code need to label one of 26 letters? One of 1000 items?
Answer
5 bits and 10 bits.
Solution
A fixed-length code with bits has codewords, so we need : and .
Exercise 2: Which is more compressible?
Which compresses better: a file of fair coin flips or a file of flips of a coin with heads probability 0.9? Why?
Answer
The biased coin.
Solution
Fair flips have entropy 1 bit per flip, so no compressor can shrink them. The biased coin has entropy about 0.47 bits per flip, so a good compressor needs fewer than half the bits.
Exercise 3: Repetition-5 (code)
Repeat the second example with each bit sent five times and a majority of 3 out of 5. What error rate do you get?
Answer
About 0.0085, at rate 1/5 (the exact value is 0.00856).
Solution
import numpy as np
rng = np.random.default_rng(1)
bits = rng.integers(0, 2, 100_000)
received = np.repeat(bits, 5) ^ (rng.random(500_000) < 0.1)
decoded = (received.reshape(-1, 5).sum(axis=1) >= 3).astype(int)
print("repetition-5 bit error rate:", round(float(np.mean(decoded != bits)), 4))repetition-5 bit error rate: 0.0085
More repetition lowers the error rate but also the rate. Repetition Codes computes these numbers exactly.
Test yourself
Shannon's source coding theorem says that a source can be compressed to about…
- its entropy in bits per symbol
- half its size
- the logarithm of its alphabet size
- zero bits
Below channel capacity, the noisy-channel theorem promises…
- error probability as small as desired at a fixed positive rate
- zero errors with no coding
- rate that grows without limit
- nothing for binary channels
Which book sets the topic order of this course?
- MacKay, Information Theory, Inference, and Learning Algorithms
- Knuth, The Art of Computer Programming
- Boyd and Vandenberghe, Convex Optimization
- Feller, An Introduction to Probability Theory