Compression in Practice
Real compressors combine the ideas of this chapter: a transform or dictionary method to expose redundancy, a model to predict symbols, and an entropy coder to turn predictions into bits. This lesson measures Python's three standard compressors on different kinds of data and compares them with entropy estimates, then shows how modelling context lowers the bit rate.
Three designs
| Module | Method | Strength |
|---|---|---|
zlib (DEFLATE) |
LZ77 with a 32 KB window + Huffman | fast, universal, used in zip/gzip/PNG |
bz2 |
Burrows-Wheeler transform + move-to-front + Huffman | text with many repeated contexts |
lzma (xz, 7z) |
LZ77 with a large window + adaptive range coding | best ratio, slower compression |
import numpy as np
import zlib, bz2, lzma
rng = np.random.default_rng(0)
datasets = {
"biased bytes (H=2.0)": rng.choice(4, size=100_000, p=[0.5, 0.25, 0.125, 0.125]).astype(np.uint8).tobytes(),
"sine samples": np.round(100 * np.sin(np.arange(100_000) / 50)).astype(np.int8).tobytes(),
"random walk": np.cumsum(rng.integers(-1, 2, 100_000)).astype(np.int16).tobytes(),
}
for name, data in datasets.items():
rates = {m.__name__: round(8 * len(m.compress(data)) / len(data), 3) for m in (zlib, bz2, lzma)}
print(f"{name:22s} bits/byte: {rates}")biased bytes (H=2.0) bits/byte: {'zlib': 2.243, 'bz2': 2.07, 'lzma': 2.036}
sine samples bits/byte: {'zlib': 0.375, 'bz2': 0.175, 'lzma': 0.134}
random walk bits/byte: {'zlib': 1.9, 'bz2': 0.943, 'lzma': 1.357}
The biased bytes cannot go below their entropy of 2 bits; the sine is highly predictable and compresses enormously; the random walk is in between.
The Burrows-Wheeler transform
The BWT sorts all rotations of the text and outputs the last column. Characters that precede similar contexts end up next to each other, creating long runs that are easy to compress, and the transform is invertible.
def bwt(s):
s = s + "quot;
rotations = sorted(s[i:] + s[:i] for i in range(len(s)))
return "".join(r[-1] for r in rotations)
def inverse_bwt(last):
table = [""] * len(last)
for _ in range(len(last)):
table = sorted(last[i] + table[i] for i in range(len(last)))
return next(r for r in table if r.endswith("quot;))[:-1]
text = "banana bandana banana"
t = bwt(text)
print(repr(t))
print("inverse ok:", inverse_bwt(t) == text)'aaannndnnbbb$ naaaaaa'
inverse ok: True
Transforms before coding
Many formats first transform the data so that the residuals are small and skewed, then entropy-code them. Delta coding (store differences) turns a smooth signal into small numbers:
import numpy as np
import zlib
t = np.arange(50_000)
signal = np.round(1000 * np.sin(t / 200) + 0.5 * t).astype(np.int32)
delta = np.diff(signal, prepend=0).astype(np.int32)
for name, arr in [("raw", signal), ("delta", delta)]:
vals, counts = np.unique(arr, return_counts=True); q = counts / counts.sum()
print(f"{name:5s}: distinct values {len(vals):6d}, empirical entropy {-np.sum(q * np.log2(q)):6.3f} bits, "
f"zlib {8 * len(zlib.compress(arr.tobytes(), 9)) / arr.size:6.3f} bits/sample")raw : distinct values 22239, empirical entropy 14.197 bits, zlib 12.191 bits/sample
delta: distinct values 12, empirical entropy 3.474 bits, zlib 1.123 bits/sample
PNG applies the same idea per row with its filters, FLAC predicts audio samples with linear prediction, and video codecs predict whole blocks from earlier frames.
Context modelling
The best lossless compressors (PPM, context mixing, and neural compressors) predict each symbol from the symbols before it. Each step up in context length lowers the cross-entropy, as long as there is enough data to estimate the statistics:
import numpy as np
from collections import defaultdict
rng = np.random.default_rng(3)
# a source with memory: an order-2 Markov chain over 4 letters
T = rng.dirichlet(np.ones(4) * 0.3, size=16)
s = [0, 1]
for _ in range(200_000):
s.append(rng.choice(4, p=T[4 * s[-2] + s[-1]]))
s = np.array(s)
train, test = s[:150_000], s[150_000:]
for order in [0, 1, 2, 3]:
counts = defaultdict(lambda: np.ones(4)) # add-one smoothing
for i in range(order, len(train)):
counts[tuple(train[i - order:i])][train[i]] += 1
bits = [-np.log2(counts[tuple(test[i - order:i])][test[i]] / counts[tuple(test[i - order:i])].sum())
for i in range(order, len(test))]
print(f"order-{order} model: {np.mean(bits):.4f} bits/symbol on test data")order-0 model: 1.8717 bits/symbol on test data
order-1 model: 1.7144 bits/symbol on test data
order-2 model: 1.0708 bits/symbol on test data
order-3 model: 1.0717 bits/symbol on test data
The source has memory of 2 symbols, so order 2 captures it; order 3 adds nothing but more parameters. An arithmetic coder driven by the order-2 model would compress test data to about that number of bits per symbol (Arithmetic Coding). Language models are the extreme case of this idea (Perplexity).
In software
- Choose
zlibfor speed and compatibility,lzmafor the best ratio on archives, and Zstandard (zstandardpackage) for a tunable middle ground. - Columnar formats (Parquet, Arrow) apply delta, dictionary and run-length encoding per column before a general compressor, because each column has simple statistics.
- Always measure on your own data: ratios vary by orders of magnitude between data types.
Exercises
Exercise 1: Which compressor?
You archive log files once and read them rarely. Which of zlib, bz2, lzma is the natural choice?
Answer
lzma.
Solution
It gives the best ratio, and its slow compression matters little when data are written once. Decompression is still reasonably fast.
Exercise 2: Delta coding
Delta-code the sequence .
Answer
.
Solution
Keep the first value and then store each difference from the previous value. The small differences need far fewer bits than the raw values.
Exercise 3: BWT runs (code)
Apply the BWT to "mississippi" and count the runs (maximal blocks of equal characters) before and after.
Answer
The original has 8 runs; the transform (with the end marker) has 9.
Solution
def bwt(s):
s = s + "quot;
rotations = sorted(s[i:] + s[:i] for i in range(len(s)))
return "".join(r[-1] for r in rotations)
runs = lambda s: 1 + sum(a != b for a, b in zip(s, s[1:]))
t = bwt("mississippi")
print(t, runs("mississippi"), runs(t))ipssm$pissii 8 9
On such a short string there is no gain: the contexts repeat too rarely, and the end marker adds a character. On long texts the BWT output has far fewer runs than the input, as the banana bandana banana example already starts to show.
Test yourself
The Burrows-Wheeler transform helps compression because…
- it groups characters with similar contexts into runs
- it removes redundant characters
- it is lossy
- it computes the entropy
Delta coding works well on…
- smooth signals where consecutive values are close
- random bytes
- encrypted data
- text with no repeats
Increasing the context order of a model beyond the source's memory…
- adds parameters without lowering the true cross-entropy
- always reduces the bit rate
- makes the model lossy
- is required for arithmetic coding