第 16 章
数据压缩与 Shannon 无噪声编码定理
把压缩定义成「把消息映射成二进制串」,用熵衡量理论极限;先证下界(任何编码都不能低于 nH),再用典型序列构造一个达到 nH + o(n) 的编码,从而证明熵就是一阶信源的每符号最优码长。
Data Compression and Shannon’s Noiseless Coding Theorem
Compression is defined as a map from messages to binary strings, and entropy measures the limit. We prove the converse (no code beats nH) and then build a typical-set code achieving nH + o(n), so entropy is the best asymptotic per-symbol length for a first-order source.
篇内目录
- The question: how short can a message be?
- Timeline
- First-order sources
- Coding functions and decodability
- Example: , ,
- Entropy
- Shannon's noiseless coding theorem
- Intuition: the uniform distribution is hardest
- The lower bound
- Step 1: a lemma for uniform distributions
- Step 2: fix the symbol counts
- Step 3: Stirling turns into entropy
- Step 4: typical strings
- Step 5: assemble the bound
- The upper bound: an explicit code
- Why this code is impractical
- What this lecture establishes
- Comprehension check
- Relation to neighbouring lectures
问题:一条消息最短能有多短
早期的电报按词收费,一个词一美元。于是人们编出「电码本」:把一长串常用说法换成一个短词。课程举了几个真实条目——AZKHE 表示 clean bill of health,NBET 表示 captain is insane。今天发短信写 BRB,动机完全相同:把常出现的东西换成短符号。
电报时代的做法靠人工编表,凭经验挑选常用短语。本讲要回答的是它的数学版本:
给定一个信源,任何压缩方案的平均码长下限是多少?这个下限能不能达到?
答案是 Shannon 1948 年在同一栋楼里给出的:极限就是熵。本讲完整证明这个结论的两个方向。
时间轴
| 时间 | 内容 |
|---|---|
| 0:00 | 历史引子:电报电码本、短信缩写;信息论 1948 年诞生于 MIT 2 号楼 |
| 5:19 | 一阶信源的定义:字母表 + 概率分布,独立同分布抽样 |
| 8:14 | 编码函数与可解码性;一次性块编码与「END」结束标记 |
| 11:34 | 例子:、、,朴素编码与改进编码 |
| 17:21 | 二元熵的定义 |
| 18:38 | Shannon 无噪声编码定理的两个方向 |
| 22:47 | 直觉:均匀分布最难压缩 |
| 26:41 | 引理:均匀分布下期望码长至少为 (二叉树论证) |
| 30:33 | 固定每种符号的出现次数;多项式系数计数 |
| 37:48 | Stirling 公式把 化成 |
| 44:11 | -典型序列与 Chebyshev 界 |
| 47:46 | 用全期望公式拼出下界 |
| 55:12 | 上界:显式构造「典型 / 非典型」两支编码 |
| 1:05:51 | 这套构造为什么不实用;后续转向 Huffman 码 |
一阶信源
一个一阶信源(first-order source)由两部分组成:
- 字母表 ,共 个符号;
- 分布 ,满足 、。
课程把它比作一颗不均匀的 面骰子:每掷一次得到一个符号,掷 次并保持顺序,就得到一条长度 的消息 。每次抽样独立且分布相同,所以
字母可以是字母表的字母,也可以是词;课程强调这是最简单的模型,真实语言需要马尔可夫链等更复杂的结构,但本讲的理论会原样推广过去。
编码函数与可解码
编码函数 把每条长度 的消息映射成一个变长二进制串。
为什么允许变长?因为直观上高频消息应该配短码字。例子中 的概率高达 ,如果它能用 1 位表示,平均长度立刻下降。
变长带来一个必须写清的约束:映射必须单射。若两条不同消息编成同一个串,就无法解码。这里暂时不要求前缀无关:本讲的模型是一次性块编码,整条消息发完再发一个 END,解码器知道边界在哪里。等下讲的 Huffman 码才需要前缀无关,因为那里要逐符号流式解码。
用 表示消息 的码长,期望码长是
这正是要最小化的成本。
例子:,,
长度为 2 的消息有四条,概率分别是
| 消息 | 概率 | 朴素码 | 改进码 |
|---|---|---|---|
| 00 | 0 | ||
| 01 | 10 | ||
| 10 | 110 | ||
| 11 | 111 |
朴素编码逐符号替换,每条消息都是 2 位,期望长度恰好是 。
改进编码把最可能的 压到 1 位,代价是让两条较罕见的消息变成 3 位。期望长度:
确实小于 。注意改进码的四个码字互不相同,且没有一个是另一个的前缀——这不是巧合,后面会看到前缀结构正是可达性的来源。
那么极限是多少?对 、,熵为
每符号 0.544 比特,远低于 1 比特。 时只能做到 1.359/2≈0.68,差距来自 修正项; 越大越接近熵。
熵
对分布 ,二元熵定义为
因为 ,每个 ,负号使 。约定 。
几个基本事实(后文会用到):
- 均匀分布 使熵最大,;
- 若某个 ,则 ——信源没有不确定性,不需要传信息;
- 只依赖概率,不依赖符号的名字。
Shannon 无噪声编码定理
设一阶信源的熵为 。定理包含两个方向。
下界(converse)。 对任意可解码的编码函数 ,
上界(achievability)。 存在可解码的编码函数 ,使得
这里 指随 增长远慢于 的量,例如 或 。两个方向合起来:每符号的渐近最优码长就是 ,误差只占 。
注意这是渐近结论。 很小时 项可能比 还大,定理不提供有用信息;它的力量在于 。
直觉:均匀分布最难压缩
哪个分布最难压缩?从熵的角度,是使 最大的分布;从直观角度,是没有高频符号可占便宜的分布。两者给出同一个答案:均匀分布。
均匀分布时 ,故 。而朴素编码给每个符号 位,所以每符号码长已经是 附近,无法再改进。
反过来,只要分布不均匀,就有「把高频事件压短」的空间。例子中 的概率让我们把 压到 1 位,这就是收益来源。
下界的证明
第一步:均匀分布的引理
引理。 设 个等概率消息,任何单射编码的期望码长至少是 。
证明思路。 把所有码字看成二叉树的节点:根是空串,左孩子添 0,右孩子添 1。单射就是给 个消息分配 个互不相同的节点。要最小化平均深度,应当按层填满:第 0 层 1 个节点、第 1 层 2 个、第 2 层 4 个……直到装满 个。数一下就知道,绝大多数消息的深度是 或 ,平均值与 只差一个常数。
也可以在编码层面理解:深度为 的节点最多 个,若所有码字深度都小于 ,能容纳的码字总数不足 ,矛盾。
第二步:固定每种符号的出现次数
设一条消息中符号 出现 次,。把这组 称为消息的签名(signature)。
给定签名后,可能的字符串数目是多项式系数
每个这样的字符串概率相同,都是 。换句话说,在固定签名的条件下,消息在 个等概率字符串上均匀分布。于是引理给出
第三步:用 Stirling 公式把 变成熵
对 展开:
用 Stirling 公式 ,得到
最后一步用了 ,所以两个 项正好抵消。再把 拆开:
括号里正是经验分布 的熵:
这就是熵出现的位置:它不是被假设出来的,而是多项式系数在 Stirling 近似下的自然产物。
第四步:典型序列
第三步只处理了「签名已知」的情形。问题是:某个签名可能极少出现,那样得到的下界就用不上。
解决方法是典型性。称字符串是 -典型的,若对所有
也就是说,经验频率落在真实概率的 邻域内。
由 Chebyshev 不等式(对每个坐标算方差,再用并集界合并 个事件),
这里 与 在定理中都是固定的,只有 ,所以非典型概率 。这正是前面几讲尾界工具的用处:经验频率以 的速度收敛到真实概率。
第五步:拼出下界
用全期望公式把期望拆成典型与非典型两部分:
典型时,每个 与 只差 。熵在概率向量上是连续的,所以
因此
先令 (消掉 ),再令 ,得到
下界证完。
上界的证明:显式构造
下界说明谁都不能更快;上界要造出一个真正达到它的编码。构造按分支进行,只需要三块信息。
第 1 位:消息是否 -典型。
若典型:
- 用 位写出签名 ——每个 有至多 种取值,需要 位,共 个;
- 再用 位写出「在给定签名下是第几个字符串」,其中 是签名落在 邻域内时多项式系数的最大值。
若非典型:直接输出朴素编码,每符号 位,共 位。
按分支计算期望:
逐项估计:
- ,由第三步与熵的连续性;
- ;
- 非典型项等于 ,是常数,也是 。
于是
两个方向合起来,定理证完。
值得强调的是:这个构造不需要知道消息内容,只需要在解码时先看「是否典型」这一位。典型时,问题退化成在 个等概率字符串中报出序号,而报序号的最优代价正是 ——这又回到第一讲的均匀分布引理。
这个编码为什么不实用
定理证明里的编码函数是一本码表:对每条可能的消息预先指定一个二进制串。消息总数是 ,指数级增长;实际使用时要存下整本码表,解码时还要在表里查找。这在理论上最优,在工程上完全不可行。
下一讲的 Huffman 码换一个思路:不预先固定 再一次性编码,而是逐符号设计前缀码,用一棵树同时完成编码与解码,复杂度只与字母表大小有关。
本节结论
- 一阶信源 = 字母表 + 分布 + 独立同分布抽样。
- 编码函数把长度 的消息映成变长二进制串,必须单射才能解码。
- 熵 是每符号码长的渐近下界。
- 下界证明的三件工具:均匀分布的二叉树引理、多项式系数 + Stirling、Chebyshev 典型性。
- 上界用「典型 / 非典型」两支构造:典型时付 ,非典型时付朴素编码,后者的概率只有 。
- 结果:,即每符号 比特。
- 该构造理论最优但码表指数大,工程上要用 Huffman 之类的逐符号方案。
理解检验
1. 本讲的编码函数只要求单射,为什么不需要前缀无关?下讲的 Huffman 码为什么必须要?
参考答案:本讲的模型是一次性块编码:固定 ,把整条长度 的消息映射成一个二进制串,发完后发送 END,解码器先看到结束标记,再在码表中反查整条串。因为边界由外部标记给出,码字之间是否互为前缀不影响解码。
Huffman 码处理的是逐符号流式编码:消息长度事先未知,接收方必须从左到右即时切分。若某个码字是另一个的前缀,读到一半就无法判断当前码字是否结束,会产生歧义。前缀无关(等价于码字对应二叉树的叶子)保证任何比特流都有唯一解析。
2. 在 、、 的例子中,验证改进码的期望长度是 ,并说明它为什么仍需 很大才能逼近熵。
参考答案:四条消息的概率为 ,码长为 ,故
每符号约 比特,而熵约 比特。差距来自 项:编码必须用整数位,且在 这种小块上,签名、边界等信息本身的开销占比很大。随 增大,这部分摊薄到每条消息,平均值才收敛到 。
3. 为什么均匀分布是最难压缩的分布?请同时给出直观理由和熵的理由。
参考答案:直观上,压缩的收益来自「高频事件配短码」。均匀分布下没有高频事件,所有符号等价,任何把某个符号压短的尝试都会让另一个符号变长,期望长度不受益。
熵的角度: 在单纯形上的最大值在 处取得,值为 。由 Shannon 定理,最优每符号码长趋近 ,所以熵最大即码长最大。而朴素编码给每符号约 位,正好达到这个界,无法改进。
4. 下界证明为什么必须先固定签名 ?直接对整个消息空间用均匀分布引理不行吗?
参考答案:整个消息空间上的分布不是均匀的:不同字符串的概率差别极大(例子中 与 相差 49 倍),均匀分布引理不适用。
固定签名后,所有具有该签名的字符串概率相同,都是 ,于是可以把它们看成 个等概率对象,套用引理得到 。剩下的问题只是「哪个签名会出现」——用典型性说明存在一族高概率的签名,其 ,从而 。
5. 用 Stirling 公式推导 ,并指出哪一步用到了 。
参考答案:
两个 项分别是 与 。只有在这里用到 ,它们相消,留下
再把 写成 :
来自 Stirling 的误差项; 那部分取对数后是 ,被 吸收。
6. 上界构造里, 位用来写签名,为什么它可以被忽略?非典型分支的朴素编码要 位,为什么也可以忽略?
参考答案:前者是 : 固定, 增长远慢于 ,所以 ,在 的误差范围内。
后者看似线性,但只在非典型时使用,其概率由 Chebyshev 界为 。乘起来:
与 无关,是常数,因而也是 。关键在于非典型是小概率事件,即使分支内部很浪费,摊到期望上也可忽略。
7. 定理说最优码长是 ,为什么这个编码不能直接用于压缩文件?
参考答案:编码函数是一张码表,需要为 中每条消息预先指定码字。消息总数 随 指数增长,存表和查表都不可行,而且发送方必须先知道整条消息才能查表。
工程上需要的是可增量、可即时解码的方案:Huffman 码用一棵与字母表同规模的树,对每个符号独立编码,编解码都是树上的行走,存储与时间只与 有关,与 无关。代价是它只能达到 与 之间,而不是渐近最优的 ——但对实际数据,这个差距通常可以接受。
与前后课的关系
本讲把压缩的理论极限钉死在熵上,但证明里的构造不可实现。下一讲 Huffman 码给出可实现的最优前缀码:用交换论证证明「最不常用的两个符号必须是兄弟」,再递归合并,得到一棵最优二叉树;同时用 Kraft 不等式把前缀码与码长联系起来。
再下一讲转向噪声信道:消息在传输中会被翻转,问题从「压得更短」变成「错得起」。Shannon 第二定理会说明,只要码率低于信道容量,就可以用足够长的码把错误概率压到任意小——证明同样依赖典型性与随机编码。
The question: how short can a message be?
Telegrams used to be billed by the word, about a dollar each. People therefore printed code books that replaced long stock phrases with short tokens: AZKHE meant clean bill of health, NBET meant captain is insane. Texting BRB today is the same move: give the frequent thing a short symbol.
The telegraph era did this by hand, choosing phrases by experience. This lecture asks the mathematical version:
For a given source, what is the lower limit on the average code length of any compression scheme, and can that limit be attained?
Shannon answered in 1948, in the same building: the limit is entropy. The lecture proves both directions in full.
Timeline
| Time | Topic |
|---|---|
| 0:00 | History: telegram code books, texting abbreviations; information theory born in MIT Building 2 in 1948 |
| 5:19 | Definition of a first-order source: alphabet plus distribution, IID sampling |
| 8:14 | Coding functions and decodability; one-shot block codes and the END marker |
| 11:34 | Example: , , ; naive versus improved code |
| 17:21 | Definition of binary entropy |
| 18:38 | The two directions of Shannon's noiseless coding theorem |
| 22:47 | Intuition: the uniform distribution is hardest to compress |
| 26:41 | Lemma: under a uniform distribution the expected length is at least (binary tree argument) |
| 30:33 | Fixing symbol counts; the multinomial count |
| 37:48 | Stirling's formula turns into |
| 44:11 | -typical strings and the Chebyshev bound |
| 47:46 | Assembling the lower bound with the law of total expectation |
| 55:12 | Upper bound: an explicit two-branch code |
| 1:05:51 | Why this construction is impractical; the road to Huffman codes |
First-order sources
A first-order source has two parts:
- an alphabet of symbols;
- a distribution with and .
The lecture pictures a biased -sided die: roll it once to get a symbol, roll times keeping order, and obtain a message of length . Draws are independent and identically distributed, so
Symbols may be letters or whole words. The lecture stresses that this is the simplest model; real language needs Markov chains, but the theory carries over.
Coding functions and decodability
A coding function maps every length- message to a variable-length binary string.
Why variable length? Because frequent messages should get short codewords. In the example below, has probability ; giving it one bit instead of two immediately lowers the average.
Variable length forces one requirement: the map must be injective. Two distinct messages encoded identically cannot be decoded. Prefix-freeness is not required here, because this is a one-shot block code: the whole message is sent, then END, so the decoder knows where the message stops. Prefix-freeness becomes necessary in the next lecture, where Huffman codes must be decoded symbol by symbol on a stream.
Writing , the expected length is
and this is the cost to minimize.
Example: , ,
There are four messages of length two:
| Message | Probability | Naive code | Improved code |
|---|---|---|---|
| 00 | 0 | ||
| 01 | 10 | ||
| 10 | 110 | ||
| 11 | 111 |
The naive code replaces each symbol by one bit, so every message costs two bits and the expected length is exactly .
The improved code gives the most likely message one bit, at the price of three bits for the two rarer messages. Its expected length is
This is below . The four codewords are distinct and none is a prefix of another — not an accident, since prefix structure is what makes the construction work in general.
What is the limit? For this source,
That is far below one bit. At the best we do is ; the gap is the correction, which shrinks as grows.
Entropy
For a distribution , the binary entropy is
Since , each and the minus sign makes . The convention is .
Three facts used later:
- the uniform distribution maximizes entropy, giving ;
- if some , then — the source carries no uncertainty;
- depends only on the probabilities, not on the symbol names.
Shannon's noiseless coding theorem
Let the source have entropy . The theorem has two directions.
Converse. For every decodable coding function ,
Achievability. There exists a decodable coding function with
Here means a quantity growing strictly slower than , such as or . Together: the asymptotic optimum per symbol is , with relative error .
The statement is asymptotic. For small the term may exceed and the theorem says nothing useful; its force is in the limit.
Intuition: the uniform distribution is hardest
Which distribution is hardest to compress? From entropy, the one maximizing ; from intuition, the one with no frequent symbol to exploit. Both give the same answer: uniform.
For uniform , , and the naive code already uses about bits per symbol, so nothing can improve. Conversely, any non-uniformity creates room: a frequent event can be given a short codeword.
The lower bound
Step 1: a lemma for uniform distributions
Lemma. For equally likely messages, every injective code has expected length at least .
Proof idea. View codewords as nodes of a binary tree: the root is the empty string, appending 0 or 1 goes left or right. Injectivity means assigning distinct nodes. To minimize average depth, fill the tree level by level: 1 node at depth 0, 2 at depth 1, 4 at depth 2, and so on. Most of the messages end up at depth or , so the average differs from by a constant.
Equivalently, there are at most nodes at depth ; if every codeword had depth below , the total capacity would be less than , a contradiction.
Step 2: fix the symbol counts
Let occur times, with . The tuple is the signature of the message.
Given a signature, the number of strings is the multinomial
Every such string has the same probability . So conditioned on the signature, the message is uniform over strings, and the lemma yields
Step 3: Stirling turns into entropy
Expand
Using ,
where the two terms cancel because . Now split :
The bracket is the entropy of the empirical distribution:
Entropy appears here not as an assumption but as the natural output of Stirling's approximation to a multinomial.
Step 4: typical strings
Step 3 handles a fixed signature, but some signatures may be so unlikely that the bound is useless. Typicality fixes this. A string is -typical if for every
that is, every empirical frequency lies within of its true probability.
By Chebyshev's inequality applied to each coordinate and a union bound over coordinates,
Both and are fixed while , so this probability tends to zero. This is precisely the tail-bound machinery from earlier lectures: empirical frequencies converge at rate .
Step 5: assemble the bound
Split the expectation with the law of total expectation:
On a typical string, each is within of . Entropy is continuous in the probability vector, so
Therefore
Let first (removing ), then :
The converse is proved.
The upper bound: an explicit code
The converse says nobody can do better; achievability must exhibit a code that does as well. The construction uses three pieces of information.
Bit 1: is the message -typical?
If typical:
- write the signature using bits — each has at most values, so bits each;
- write the index of the string among those with this signature, using bits, where is the largest multinomial over -typical signatures.
If not typical: fall back to the naive code at bits per symbol, bits total.
Computing the expectation branch by branch:
Estimate each term:
- , by Step 3 and continuity of entropy;
- ;
- the atypical term equals , a constant, hence .
Thus
which completes the theorem.
Note what the decoder needs: one bit saying whether the message is typical. If it is, the problem reduces to reporting the index of one of equally likely strings, whose optimal cost is — exactly the uniform-distribution lemma from Step 1.
Why this code is impractical
The code in the proof is a lookup table: every possible message is assigned a binary string in advance. There are messages, exponentially many, so storing the table and searching it are both infeasible.
The next lecture changes the approach. Instead of fixing and encoding the whole block at once, Huffman codes design a symbol-by-symbol prefix code represented by a tree, so encoding and decoding cost depend only on the alphabet size, not on .
What this lecture establishes
- A first-order source is an alphabet, a distribution, and IID sampling.
- A coding function maps length- messages to variable-length binary strings and must be injective to be decodable.
- Entropy is the asymptotic per-symbol lower bound.
- The lower bound uses three tools: the uniform-distribution tree lemma, the multinomial plus Stirling, and Chebyshev typicality.
- The upper bound branches on typicality: when typical, the naive code otherwise, and the latter has probability only .
- The result is , i.e. bits per symbol.
- The code is optimal but exponentially large; practical schemes use Huffman-type constructions.
Comprehension check
1. This lecture only requires injectivity, not prefix-freeness. Why do Huffman codes require prefix-freeness?
Reference answer: This lecture studies one-shot block coding: is fixed, the entire length- message is mapped to one binary string, then END is sent, and the decoder looks the whole string up in the codebook. Boundaries come from an external marker, so prefix relations among codewords do not create ambiguity.
Huffman codes handle streaming, symbol-by-symbol encoding: the message length is unknown in advance and the receiver must split the bit stream on the fly. If one codeword were a prefix of another, the decoder could not tell where the current codeword ends. Prefix-freeness (equivalently, codewords at leaves of a binary tree) guarantees a unique parsing of every bit stream.
2. In the example , , , verify that the improved code has expected length , and explain why large is still needed to approach entropy.
Reference answer: The probabilities are with lengths , so
That is about bits per symbol against an entropy of about . The gap is the term: codewords have integer lengths, and for a block as small as the overhead of the signature and boundary information is large relative to the payload. As grows this overhead is amortized, and the average approaches .
3. Why is the uniform distribution hardest to compress? Give both the intuitive and the entropy argument.
Reference answer: Intuitively, compression gains come from giving frequent events short codewords. Under a uniform distribution no symbol is frequent, every symbol is interchangeable, and any shortening forces another codeword to lengthen, so the expected length cannot improve.
Formally, is maximized on the simplex at , with value . Shannon's theorem says the optimal per-symbol length approaches , so maximal entropy means maximal length. The naive code already uses about bits per symbol and therefore attains this bound.
4. Why must the lower-bound proof first fix the signature ? Why not apply the uniform lemma to the whole message space?
Reference answer: The distribution over messages is not uniform — probabilities differ enormously (in the example, versus ). The uniform lemma does not apply.
Conditioning on a signature makes all strings with that signature equally likely, each with probability , so they become equiprobable objects and the lemma gives . What remains is to argue that some signature family occurs with high probability — that is typicality, which guarantees and hence .
5. Derive with Stirling's formula, and identify where is used.
Reference answer:
The exponential terms are and . This is the only place where is used; they cancel, leaving
Writing ,
The comes from the error term in Stirling; the factor contributes only after taking logs, which is absorbed by .
6. In the upper bound, why can the bits for the signature be ignored? The atypical branch costs bits, so why can that be ignored too?
Reference answer: The first is : is fixed and grows far slower than , so and it fits inside the slack.
The second looks linear, but it is used only on atypical strings, an event of probability by Chebyshev. Multiplying,
which is independent of , hence a constant and also . The key is that atypicality is rare: however wasteful the fallback, its contribution to the expectation vanishes.
7. The theorem says the optimal length is . Why can this code not be used to compress a file?
Reference answer: The coding function is a codebook assigning a codeword to every message in . There are messages, exponentially many, so storing and searching the table is infeasible, and the sender must know the whole message before encoding.
Practical schemes must be incremental and decodable on the fly. Huffman codes use one tree of size comparable to the alphabet, encoding each symbol independently and decoding by walking the tree, with storage and time depending only on . The price is that Huffman achieves between and bits per symbol rather than the asymptotic — usually an acceptable trade.
Relation to neighbouring lectures
This lecture pins the theoretical limit of compression at entropy, but its construction is unimplementable. The next lecture gives Huffman coding, an implementable optimal prefix code: an exchange argument shows the two least likely symbols must be siblings, which yields a recursive merge, and the Kraft inequality links prefix codes to their length profile.
The lecture after that turns to noisy channels, where the question changes from "make it shorter" to "make it survive errors". Shannon's second theorem shows that below channel capacity one can drive the error probability arbitrarily low with long enough codes, again via typicality and random coding.