Asymptotic equipartition, typical sets and entropy rate
Apply the law of large numbers to −(1/n) log p(Xⁿ) to show that nearly all probability concentrates on about 2^(nH) typical sequences. Prove the fixed-length block source-coding theorem, then extend entropy to processes with memory. A language model’s loss upper-bounds the entropy rate.
After this lesson you can
- State and prove the AEP for i.i.d. sources using the weak law of large numbers.
- Prove that the typical set has probability tending to 1 and size between (1−ε)2^(n(H−ε)) and 2^(n(H+ε)).
- Prove achievability and the converse of the fixed-length source-coding theorem.
- Compute the entropy rate of a stationary Markov chain.
- Explain why the most probable sequence need not be typical and what this means for sampling from generative models.
Before you start
Motivation: count sequences, not symbols
A coin yields 1 with probability and 0 with probability . Its entropy is bits per toss. With 100 tosses there are possible sequences and a naive code spends 100 bits naming one. But almost all these sequences practically never occur: probability piles up on about of them, fraction of the total. Reserving labels only for that small set costs about 47 bits to name a sequence, not 100.
This idea, Shannon’s (1948), explains why entropy limits compression without constructing a specific code: count sequences deserving a label. It also underlies three constantly useful facts:
- Entropy is not just a mean: it is an exponent. is the “effective” number of source outcomes, and that of length- sequences. A language model’s perplexity, 2 raised to mean loss in bits, is the same effective choice count per token measured using the model instead of the source.
- What happens is typical, not most probable. The individually most probable sequence (100 zeros here) almost never appears. Text generation seeking the maximum-probability sequence produces something the model’s own sampling almost never would.
- Entropy rate sets a language model’s loss floor. For processes with memory, what is compressed and predicted is entropy rate, not isolated-symbol entropy.
The lesson begins by counting in the visible binary case. It then states and proves the asymptotic equipartition property, generalizing counting to any memoryless source. Typical sets and the source coding theorem (with converse) follow. Then the most-probable versus typical paradox and finally processes with memory. Unless stated otherwise, is base-2 logarithm and quantities are in bits.
Counting versus weighing
Let , with . Sequence with ones has probability , depending only on . Two things compete:
- How many sequences have ones: (the combinatorial count).
- How much each weighs: , with the fraction of ones and
the per-symbol cost of each sequence in that class. It is a straight line in .
The first factor has exponential size bounded without approximations.
Proof
Upper bound. With , the binomial theorem gives , and . Rearranging gives the bound. Cases are trivial ().
Lower bound. In distribution the most probable value is : the ratio of consecutive terms exceeds 1 if and only if , and since with , terms rise to and fall afterward. There are possible values summing to 1, so that term is at least : . Rearranging gives the other inequality.
∎(Stirling’s formula gives the same result with precise correction , but the bounds above suffice for the exponential argument and hold for every .)
Combining both factors, total mass of the class of sequences with ones is
Exponent is minus a divergence: expanding gives , Kullback–Leibler divergence. The two bounds give : class mass decays exponentially with its divergence from . The figure shows it: curve counts, line weighs, and their vertical gap is divergence. The line is tangent to the curve exactly at , where almost all mass lives.
Three readings of the figure proved generally in the rest of the lesson:
- Concentration. Mass concentrates in classes with near , and that region’s width shrinks as . This is a law of large numbers.
- Equipartition. All sequences in classes near have per-symbol cost near : they weigh almost the same on exponential scale, .
- The most probable does not count. All zeros has minimum cost (0.152 bits per symbol for , versus ), but class mass is “number of sequences times weight of each”, and that class has one. Individually most probable and almost-sure behavior differ.
The asymptotic equipartition property
For binary sources a tangent line sufficed. Generally a sequence’s per-symbol cost is the average of symbol surprises, and iid averages concentrate.
Let be iid random variables with distribution on finite alphabet , and . By independence is a sum of iid variables, each with surprise and common mean entropy .
Proof
Variables are iid, functions of iid variables. Each takes finitely many values ( with probability 1, and the alphabet is finite), so has finite mean and variance: and . Since , the weak law of large numbers gives in probability (convergence in probability). The quantitative bound is Chebyshev’s inequality applied to , with mean and variance .
∎The name comes from concentration: sequences actually appearing have almost identical probability on exponential scale, : probability is “equipartitioned” among them. Notice how little was used: only finite surprise variance and independent identically distributed observations. In the next figure verify this and especially see what happens when an assumption fails.
With initial iid source (), bits and ; at tosses standard deviation of is about bits, and almost all lines are within band . With the figure’s Markov chain (each symbol changes with probability from the previous), 0 and 1 are equally likely and bit, but converges to : not each symbol’s entropy, but how surprising each symbol is given its predecessor. This is entropy rate in later sections. The mixture shows there need not even be one limit: without ergodicity classical AEP fails (revisited at the end).
The typical set
AEP says which sequences to expect. To count them define the set satisfying the property.
It is a set of sequences ( possible), defined by each one’s probability, not “typical values”. Look at the earlier figure’s lower part: for Bernoulli, is typical exactly when cost falls in band , and since is linear this means (for ). With and this is the figure’s window .
Proof
-
By definition, if and only if . Complement probability is, by quantitative AEP, . For this is below .
-
Each has and total mass is at most 1:
- Each has , so by part 1,
Part 2 uses nothing asymptotic (only probabilities summing to 1), while 1 needs large . With fixed , combining gives : the typical set has about elements on exponential scale. For the coin and exact calculation gives (reproduced in implementation):
| 10 | 0.387 | 0.332 | 4.7 |
| 100 | 0.759 | 0.529 | 46.9 |
| 300 | 0.934 | 0.545 | 140.7 |
| 1000 | 0.999 | 0.556 | 469.0 |
| 2000 | 1.000 | 0.559 | 938.0 |
Two points deserve attention. First, AEP is asymptotic: at the typical set retains only 76% mass, and Chebyshev requires to ensure 90% when reality achieves it for all . Bounds are true but very conservative for small , and mass does not even grow monotonically: with the window contains only class and retains , less than . Second, ratio does not tend to : with fixed the typical set includes classes costing more than , which are more numerous, and count is dominated by the window’s largest class at edge . The limit is , below exactly at : that class’s cost is , and its count is cost minus divergence. To approach let as grows, or use the minimum set of given probability studied next.
The typical set is a tiny fraction of full space: if is nonuniform,
with uniform (lesson 2 showed ). For that fraction tends to 0 exponentially even as set probability tends to 1. This enables compression.
The source coding theorem
A block of symbols is encoded with a fixed number of bits. A block code of rate and length is a pair of functions: encoder with labels (i.e. bits, bits per source symbol) and decoder . Its error probability is . If there are far fewer labels than sequences () and the code must give some up; which rates allow negligible error?
Proof
Achievability. Let , so . By property 2, , less than whenever , i.e. always (with exponentially growing slack). Number typical-set elements with labels and map remaining sequences to any label. The decoder returns the numbered sequence. Failure occurs only outside the typical set:
Converse. Let . A code with labels correctly decodes at most a set of sequences. Success probability is therefore at most
The last summand is . Thus success tends to 0 and .
∎The theorem says that entropy is the compression threshold for block codes: above it, error vanishes; below it, error becomes almost certain (a “strong” converse, stronger than the weak version saying only that error cannot be small). The figure computes the error probability of the best possible code, exactly for a Bernoulli source: with labels, the optimum indexes the most probable sequences, and error is one minus the mass of that set.
The figure illustrates two subtleties. First, the step has width: the transition occupies a band of width around (at and , about bits), and exactly at error tends neither to 0 nor to 1. A classical refinement (Strassen, 1962; Kontoyiannis and Verdú, 2014) gives the minimum size of a set of probability : , where is the inverse normal tail. With , and it gives bits, versus the exact value shown by the minimum-set reading in the first figure. Second, the best code is not the one in the proof, but the proof suffices for the limit.
This theorem concerns fixed length and small error. The variable-length, zero-error version needs prefix codes (Kraft inequality, Huffman) and yields average length per symbol between and when encoding blocks of symbols; lesson 5 develops it. Arithmetic coding in lesson 7 achieves this without enumerating anything. All of this returns from another angle in the method of types (lesson 16), which gives the exact exponent of the error probability.
The most probable sequence is not typical
Return to the coin with and . Three different sequences:
| Sequence | Ones | Cost per symbol | Probability | Typical ()? |
|---|---|---|---|---|
| 100 zeros | 0 | bits | no (it is the most probable) | |
| one with 10 ones | 10 | bits | yes | |
| one with 20 ones | 20 | bits | no |
The all-zero sequence is times more probable than any sequence with 10 ones. Even so, you will not see it: its total probability is , while the sequences with exactly 10 ones account for of the mass. The reason is counting: each weighs a lot, but there is only one. In the figure’s notation, the most probable sequence has , the lowest cost on the line, while its class has bits per symbol of multiplicity.
The proof is short. The cost per symbol of is the surprise of , the minimum of the surprises on the support. is the average of those surprises weighted by , and an average of numbers that are not all equal is strictly greater than their minimum; hence and lies outside the band if is less than the gap. The ratio to typical sequences follows because their probability is at most , whereas .
What this means for text generation
An autoregressive language model defines a distribution over token sequences, and generating means choosing a sequence. There are two radically different ways to do so:
- Sampling (at temperature 1) produces sequences distributed according to : by the AEP, their surprise per token concentrates around the entropy of . These are typical sequences for the model.
- Searching for the mode (greedy decoding, beam search) attempts to maximize . It produces sequences with abnormally low surprise per token, which the model would almost never generate itself. And because repeating what the model already considers probable minimizes surprise, text falls into loops. It is the same phenomenon as = “all zeros”, in a much larger space.
The implementation below shows this with a toy character language model. It also explains the design of many techniques: temperature, top- sampling by Holtzman et al. (2020), and “locally typical sampling” by Meister et al. (2022) can be understood as ways to stay in the typical set (or nearby), trimming the absurd tail without falling into the mode. In the last case, the rule chooses tokens at each step whose surprise resembles that step’s conditional entropy.
Processes with memory: entropy rate
Text, a time series or a DNA strand is not iid: each symbol depends on previous ones. The entropy of each symbol, , no longer governs compression, as the AEP figure showed. It must be replaced by a quantity measuring how much each symbol adds to what has already been seen. First, the framework: a process is stationary if, for every and , and have the same joint distribution.
For an iid process both equal , by the chain rule. For a stationary process they always exist and coincide.
Proof
Let . Conditioning reduces entropy (the difference is the conditional mutual information , an average of Kullback-Leibler divergences and, by Gibbs’ inequality, ) and stationarity shifts the indices, so
The sequence is nonincreasing and bounded below by 0, so it converges to a limit : exists. By the chain rule, is the Cesàro mean of a sequence converging to and therefore also converges to . Since the are nonincreasing, the mean satisfies , so : it too is nonincreasing, and .
∎The last sentence is useful in practice: always overestimates the rate, as does . Each new context observation can only lower the cost. The more memory a model uses, the closer it approaches the rate from above.
Markov chains
The tractable case is a Markov chain with states and transition matrix (). It is assumed stationary: its initial law is a stationary distribution , with . By the Markov property, , and by stationarity that value is .
It is simple and its proof is already done: , and given , has distribution . For two states with and , the balance equation gives , and hence .
Shannon–McMillan–Breiman and ergodicity
The AEP of the previous sections extends: for stationary and ergodic processes, converges to the entropy rate almost surely. This is the Shannon–McMillan–Breiman theorem (Shannon 1948 for Markov chains, McMillan 1953 in , Breiman 1957 almost surely). The general proof is difficult; the one for Markov chains is not.
Proof
By the Markov property, . The first term is a finite random constant and divided by tends to 0. The second is a sum of , a function of the pair chain , which is irreducible on the pairs with and has stationary distribution . By the ergodic theorem for Markov chains, almost surely. This is the rate.
∎The ergodicity assumption matters. Consider a process that initially chooses a coin with bias or , each with probability , and uses it forever. It is stationary, and its entropy rate is the average bits (because : what is “unknown” about the coin choice costs at most one bit). But no sequence converges to 0.720: each converges to or , depending on the coin chosen. The process is not ergodic (one realization does not explore everything the process can do), and although the entropy rate is well defined, it is no longer what is observed. This is the mixture shown in the AEP figure.
What a language model’s loss measures
An autoregressive language model assigns text probability . Its mean loss per token on unseen text, , is : the same quantity as in the AEP, now using the model instead of the truth. Suppose texts come from a stationary process . Its expectation is a cross entropy (lesson 6 studies it in depth), and adding and subtracting inside the expectation separates it into entropy plus divergence:
where and are the distributions of the first tokens and the theorem above has been used. A model’s loss on unseen text is an upper bound on the text’s entropy rate, with a gap equal to the per-token divergence between truth and model. The better the model, the tighter the bound. Three consequences:
- No one goes below the floor. No architectural or scale improvement can give mean loss below the entropy rate (in expectation). The constant term obtained when fitting scaling laws is often interpreted this way: as an estimate of that floor, the irreducible loss (it is an interpretation, since the fit is empirical and the value depends on the assumed functional form).
- The reference scale. Shannon (1951), using a human text prediction experiment, bounded the rate of English (27-symbol alphabet) between 0.6 and 1.3 bits per character. Every language model now provides a concrete upper bound; lesson 8 formalizes it as bits per byte.
- -gram models are estimators. A fixed-context model (order- Markov assumption) estimates , which decreases toward the rate as increases. But with finite data, increasing produces unseen contexts, and then estimation error increases. This is the exercise in the second implementation.
Implementation from scratch
First, the exact computation of a Bernoulli typical set. There is no need to enumerate sequences: the class with ones has elements, all with the same probability, and the logarithm of that number is computed with gammaln. The cell reproduces the table above and simulates sequences of to check that surprise per symbol concentrates where the AEP predicts.
import numpy as np
from math import log2
from scipy.special import gammaln, logsumexp
p, eps = 0.1, 0.1
q = 1 - p
H = -(p * log2(p) + q * log2(q))
def coste(k, n):
"""Sorpresa por símbolo, -(1/n) log2 p(x), de una secuencia con k unos."""
return -(k / n) * log2(p) - (1 - k / n) * log2(q)
def ventana(n, eps=eps):
"""Valores de k (número de unos) cuyas secuencias son eps-típicas."""
return [k for k in range(n + 1) if abs(coste(k, n) - H) <= eps]
def log2_comb(n, k):
k = np.asarray(k, dtype=float)
return (gammaln(n + 1) - gammaln(k + 1) - gammaln(n - k + 1)) / np.log(2)
print(f"H = {H:.4f} bits; ventana de kappa para n grande: {p - eps / log2(q / p):.4f} a {p + eps / log2(q / p):.4f}")
print(f"{'n':>5} {'P(A)':>7} {'log2|A|/n':>10} {'n·H':>7} {'log2|A|':>9}")
for n in (10, 30, 100, 300, 1000, 2000):
ks = np.array(ventana(n))
lw = log2_comb(n, ks) + ks * log2(p) + (n - ks) * log2(q) # log2 de la masa de cada clase
lA = logsumexp(log2_comb(n, ks) * np.log(2)) / np.log(2) # log2 del número de secuencias típicas
print(f"{n:>5} {np.exp2(lw).sum():7.4f} {lA / n:10.4f} {n * H:7.1f} {lA:9.1f}")
# simulación: la sorpresa por símbolo de 10^5 secuencias de n = 100
rng = np.random.default_rng(0)
n, N = 100, 100_000
K = (rng.random((N, n)) < p).sum(axis=1)
Z = coste(K, n)
V = p * q * log2(q / p) ** 2
print(f"\nn = {n}: media de Z_n = {Z.mean():.4f} (H = {H:.4f}), desviación = {Z.std():.4f} (raíz de V/n = {np.sqrt(V / n):.4f})")
print(f"fracción típica en la simulación: {np.mean(np.abs(Z - H) <= eps):.4f}; secuencias de 100 ceros: {np.sum(K == 0)} de {N}")The typical-set probability grows toward 1 (not monotonically for small : note ) and rises toward , as in the table. In the simulation, surprise per symbol has mean and standard deviation close to , and only 4 of the hundred thousand sequences are all zeros ( are expected): the most probable sequence is hardly ever seen. Now a real encoder. The typical set is numbered class by class, and within each class using the combinatorial number system (the positions of ones in slots give a number between and ), so encoding and decoding require no stored table, using Python arbitrary-precision integers. Index 0 is reserved for “failure”.
import numpy as np
from math import comb, log2
from scipy.stats import binom
p, eps = 0.1, 0.1
q = 1 - p
H = -(p * log2(p) + q * log2(q))
def ventana(n):
return [k for k in range(n + 1) if abs(-(k / n) * log2(p) - (1 - k / n) * log2(q) - H) <= eps]
class CodigoTipico:
"""Indexa las secuencias típicas, clase a clase, con el índice 0 para 'fallo'."""
def __init__(self, n):
self.n, self.ks = n, ventana(n)
self.base, total = {}, 1
for k in self.ks:
self.base[k] = total
total += comb(n, k)
self.bits = (total - 1).bit_length() # ceil(log2(|A| + 1)) bits por bloque
def codificar(self, x):
pos = np.flatnonzero(x) # posiciones de los unos, crecientes
k = len(pos)
if k not in self.base:
return 0 # atípica: el codificador se rinde
return self.base[k] + sum(comb(int(c), i + 1) for i, c in enumerate(pos))
def decodificar(self, idx):
if idx == 0:
return None
k = max(k for k in self.ks if self.base[k] <= idx)
r = idx - self.base[k]
x = np.zeros(self.n, dtype=np.uint8)
c = self.n - 1
for i in range(k, 0, -1): # deshace la suma de binomiales
while comb(c, i) > r:
c -= 1
r -= comb(c, i)
x[c] = 1
c -= 1
return x
rng = np.random.default_rng(0)
print(f"H = {H:.3f} bits. Tasa de cada código = bits por bloque / n")
print(f"{'n':>5} {'bits':>5} {'R':>7} {'fallos medidos':>15} {'P(fallo) exacta':>16} {'ida y vuelta':>13}")
for n in (50, 100, 200, 500):
cod = CodigoTipico(n)
X = rng.random((4000, n)) < p
medido = np.mean([k not in cod.base for k in X.sum(axis=1)])
exacta = 1 - binom.pmf(np.array(cod.ks), n, p).sum()
ok = all(np.array_equal(cod.decodificar(cod.codificar(x)), x) for x in X[:40] if cod.codificar(x))
print(f"{n:>5} {cod.bits:>5} {cod.bits / n:7.3f} {medido:15.4f} {exacta:16.4f} {str(ok):>13}")The pattern matters. With fixed , failure probability (falling outside the typical set) drops as grows, from with to with , and matches the exact binomial value. Rate rises from to and tends to (the limit of explained after the table), always above and, as property 2 guarantees, never above except for rounding to a whole number of bits per block. The round trip is exact for sequences accepted by the encoder. Lowering brings the rate closer to , but a larger is needed to keep failure decreasing.
Estimating the entropy rate of text
Second implementation: estimate for in a corpus. To have an answer for comparison, the corpus is synthetic: sentences with a minimal grammar (determiner, noun, verb, determiner, noun, adverb), with uniform independent choices. Each sentence has exactly bits of entropy and averages characters, so the true rate is bits per character. For real text this figure is unknown: here it is the test bed. The model is an -gram counter with additive smoothing , trained on 70% and evaluated on the remaining 30% (and, for contrast, on the training data themselves).
import numpy as np
from collections import Counter, defaultdict
DET = ["el", "un"]
SUS = ["perro", "gato", "lobo", "tren", "rio", "viento", "motor", "barco"]
VER = ["mira", "sigue", "busca", "cruza", "deja", "evita", "rodea", "teme"]
ADV = ["despacio", "de noche", "otra vez", "sin ruido"]
def frase(r):
f = lambda L: L[r.integers(len(L))]
return f"{f(DET)} {f(SUS)} {f(VER)} {f(DET)} {f(SUS)} {f(ADV)}. "
rng = np.random.default_rng(7)
texto = "".join(frase(rng) for _ in range(300))
bits_frase = np.log2(len(DET) * len(SUS) * len(VER) * len(DET) * len(SUS) * len(ADV))
Lmed = np.mean([len(f"{d} {s} {v} {d2} {s2} {a}. ") for d in DET for s in SUS for v in VER for d2 in DET for s2 in SUS for a in ADV])
print(f"corpus: {len(texto)} caracteres, {len(set(texto))} símbolos distintos")
print(f"tasa verdadera = {bits_frase:.0f} bits / {Lmed:.2f} caracteres = {bits_frase / Lmed:.3f} bits por carácter")
corte = int(0.7 * len(texto))
entrenamiento, prueba = texto[:corte], texto[corte:]
V = len(set(texto))
def entrenar(txt, k):
cuentas = defaultdict(Counter)
for i in range(k, len(txt)):
cuentas[txt[i - k:i]][txt[i]] += 1
return cuentas
def perdida(cuentas, txt, k, alpha):
"""Pérdida media por carácter, en bits, con suavizado aditivo alpha."""
total = 0.0
for i in range(k, len(txt)):
c = cuentas.get(txt[i - k:i], Counter())
total += -np.log2((c[txt[i]] + alpha) / (sum(c.values()) + alpha * V))
return total / (len(txt) - k)
alpha = 0.01
print(f"\n{'k':>2} {'entrenamiento':>14} {'no visto':>9}")
for k in range(9):
m = entrenar(entrenamiento, k)
print(f"{k:>2} {perdida(m, entrenamiento, k, alpha):14.3f} {perdida(m, prueba, k, alpha):9.3f}")Three observations. Loss on unseen text falls with context (from bits with to with ) and always exceeds the true rate : it is the upper bound from the previous section. Training loss misleads: it stays at and does not rise, while unseen loss degrades from onward because long contexts are nearly unique. This is overfitting: the long-context model no longer estimates the rate but memorizes the corpus. The best (here 4) is chosen with data the model has not seen. Finally, contrast with the most-probable-sequence section: the frequency-based model (without smoothing) generates a sample and greedy output, and each one’s mean surprise per character is measured according to the model itself.
import numpy as np
from collections import Counter, defaultdict
DET = ["el", "un"]
SUS = ["perro", "gato", "lobo", "tren", "rio", "viento", "motor", "barco"]
VER = ["mira", "sigue", "busca", "cruza", "deja", "evita", "rodea", "teme"]
ADV = ["despacio", "de noche", "otra vez", "sin ruido"]
def frase(r):
f = lambda L: L[r.integers(len(L))]
return f"{f(DET)} {f(SUS)} {f(VER)} {f(DET)} {f(SUS)} {f(ADV)}. "
rng = np.random.default_rng(7)
texto = "".join(frase(rng) for _ in range(300))
k = 4
cuentas = defaultdict(Counter)
for i in range(k, len(texto)):
cuentas[texto[i - k:i]][texto[i]] += 1
def generar(modo, n, semilla):
"""Devuelve el texto generado y su sorpresa media por carácter bajo el propio modelo."""
r = np.random.default_rng(semilla)
s, bits = texto[:k], 0.0
for _ in range(n):
c = cuentas[s[-k:]]
simbolos = sorted(c)
w = np.array([c[x] for x in simbolos], dtype=float)
p = w / w.sum()
j = int(np.argmax(w)) if modo == "voraz" else int(r.choice(len(simbolos), p=p))
bits += -np.log2(p[j])
s += simbolos[j]
return s[k:], bits / n
muestras = [generar("muestreo", 1000, sd)[1] for sd in range(30)]
txt_m, _ = generar("muestreo", 1000, 0)
txt_v, bits_v = generar("voraz", 1000, 0)
print(f"muestreo: sorpresa media por carácter = {np.mean(muestras):.3f} ± {np.std(muestras):.3f} (30 muestras de 1000 caracteres)")
print(f"voraz: sorpresa media por carácter = {bits_v:.3f}")
print(f"el voraz queda a {(np.mean(muestras) - bits_v) / np.std(muestras):.1f} desviaciones por debajo de lo típico")
print("\nmuestra :", repr(txt_m[:110]))
print("voraz :", repr(txt_v[:110]))Sampling yields surprise per character with mean and small standard deviation, a narrow band: this is the model’s AEP. Greedy output has clearly lower surprise (, more than five standard deviations below) and endlessly repeats “un rio despacio.”, which is not even a grammatical sentence (the verb and complement are missing): each step chooses the most frequent continuation, and with a context of 4 characters the model does not remember its position in the sentence, so locally optimal choices lead to a loop. The most probable sequence according to the model is not what the model would say. The cause is what you saw in the typical set, now with a real model.
The library version
With SciPy, typical-set mass is a sum of the binomial probability mass function: binom.pmf over the window of . For a Markov chain’s rate, the stationary distribution is the left eigenvector with eigenvalue 1 (scipy.linalg.eig on ). As a practical counterpoint, a general compressor (zlib, bz2, lzma) on a chain simulated with shows how much of the limit is reached without knowing the model: none reaches rate , and shuffling the same sequence (same marginal entropy, no memory) makes it compress poorly.
import zlib, bz2, lzma
import numpy as np
from scipy.linalg import eig
def tasa_entropia(P):
P = np.asarray(P, dtype=float)
w, v = eig(P.T)
mu = np.real(v[:, np.argmin(np.abs(w - 1))])
mu = mu / mu.sum() # distribución estacionaria
t = np.where(P > 0, P * np.log2(np.where(P > 0, P, 1.0)), 0.0)
return -float(mu @ t.sum(axis=1)), mu
P = [[0.95, 0.05], [0.05, 0.95]]
tasa, mu = tasa_entropia(P)
print(f"estacionaria = {np.round(mu, 3)}; entropía marginal = 1.000 bit; tasa = {tasa:.4f} bits")
print("caso 0.1 / 0.3:", np.round(tasa_entropia([[0.9, 0.1], [0.3, 0.7]])[0], 4))
rng = np.random.default_rng(1)
n = 200_000
cambios = rng.random(n) < 0.05
x = (np.cumsum(cambios) + rng.integers(2)) % 2 # cadena simétrica con cambio de estado 0.05
def bits_por_simbolo(s, comprime):
return 8 * len(comprime((s.astype(np.uint8) + 48).tobytes())) / n
print(f"\n{'':>10} {'zlib':>7} {'bz2':>7} {'lzma':>7} (bits por símbolo)")
for nombre, s in (("cadena", x), ("barajada", rng.permutation(x))):
print(f"{nombre:>10} {bits_por_simbolo(s, lambda d: zlib.compress(d, 9)):7.3f} {bits_por_simbolo(s, lambda d: bz2.compress(d, 9)):7.3f} {bits_por_simbolo(s, lzma.compress):7.3f}")General compressors do not see the model and pay to bits per symbol (against the bound and the marginal’s bit). The shuffled version, with the same proportion of 0 and 1, exceeds 1 bit: without memory there is nothing to exploit. Entropy rate distinguishes the two sequences; marginal entropy does not. This is why, in lesson 7, a universal compressor must learn the model.
Common mistakes
Exercises
Step 1 of 3. What inequality relates the size of to total mass?
Step 1 of 3. What lower bound do you have for the mass of ?
entropy_rate(P): the entropy rate in bits per symbol of the stationary Markov chain with transition matrix P (rows sum to 1). Compute the stationary distribution as the solution of , (prefer least squares using np.linalg.lstsq to inverting a matrix) and return with the convention . Tests include periodic and nearly deterministic chains: no nan should appear.import numpy as np
def entropy_rate(P):
"""Tasa de entropía en bits por símbolo de la cadena con matriz de transición P."""
P = np.asarray(P, dtype=float)
# tu código: distribución estacionaria mu y luego -sum_i mu_i sum_j P_ij log2 P_ij
return 0.0Summary
- Counting versus weighing. and each sequence with ones weighs , with a straight line. Class mass is (up to a polynomial factor): it concentrates where the line is tangent, at .
- AEP. For iid, in probability, by the weak law; with Chebyshev, , with the varentropy.
- Typical set. , (for every ) and for large . It is an exponentially small fraction of if is not uniform.
- Source coding. With block codes have error (index ); with every code has error (strong converse). The transition has width .
- The most probable is not typical. The maximum-probability sequence has surprise per symbol and does not appear. Searching for the mode (greedy, beam) generates atypical, repetitive sequences; sampling generates typical sequences.
- Entropy rate. for stationary processes, and both sequences decrease toward it. For a Markov chain, . Ignoring memory overestimates cost: a chain with uniform marginal and rate compresses to 29%.
- Shannon–McMillan–Breiman. For stationary ergodic processes, almost surely (for Markov chains, this is the ergodic theorem). Without ergodicity (mixtures) there is no single limit.
- Modern reading. : a model’s loss on unseen text upper-bounds the rate. Estimating it with long contexts on training data is misleading.