人工智能之数学基础 信息论
第四章 应用延伸
前言
信息论不仅是通信工程的基石,更在人工智能、深度学习、大数据处理中扮演关键角色。从神经网络中的嵌入表示到大模型的 Token 压缩,从变分自编码器(VAE) 到信息瓶颈理论,信息论提供了统一的数学语言。
本文系统讲解:
- 信道容量(Channel Capacity):通信的极限速率
- 无损数据压缩原理:香农第一定理与霍夫曼编码
- 有损压缩与率失真理论:AI 中的表示学习
- AI 中的信息编码实践:Tokenization、嵌入、量化
- 配套 Python 代码实现(霍夫曼编码、信道仿真、压缩率分析)
一、信道容量(Channel Capacity)
1. 什么是信道?
信道是信息从发送端到接收端的传输媒介,可能引入噪声。 例如:无线信号(高斯噪声)、光纤(衰减)、神经网络层(信息瓶颈)。
2. 信道模型:离散无记忆信道(DMC)
- 输入 ,输出
- 转移概率 定义信道特性
- 无记忆:每次传输独立
✅ 经典例子:二元对称信道(BSC)
- 输入:0 或 1
- 以概率 翻转(0→1 或 1→0)
- 转移矩阵:
3. 信道容量定义
- 含义:在该信道上可靠通信的最大速率(单位:比特/信道使用)
- 香农第二定理:只要传输速率,存在编码方案使错误概率任意小
4. BSC 的信道容量
其中 是二元熵函数。
📌 直观:
- (无噪声)→ 比特/符号
- (完全随机)→ → 无法通信
二、数据压缩原理
1. 香农第一定理(无损压缩极限)
对于独立同分布(i.i.d.)信源 ,其最小平均码长满足:
- :信源熵(信息量下限)
- 结论:无法用少于 比特/符号进行无损压缩
✅ 例:英文文本熵 ≈ 1.3 比特/字母 → 理论压缩比 ≈ 8.7:1(vs ASCII 的 8 比特)
2. 霍夫曼编码(Huffman Coding)
- 最优前缀码:高频符号用短码,低频用长码
- 构造方法:贪心合并最小概率节点
编码步骤:
- 统计符号频率
- 构建霍夫曼树
- 从根到叶分配 0/1
- 生成码表
💡 性质:平均码长接近熵,且无损可逆
3. 有损压缩与率失真理论(Rate-Distortion Theory)
当允许一定失真 ,最小所需码率 为:
- :失真度量(如 MSE)
- AI 启示:表示学习本质是在率(模型大小)与失真(重构误差)间权衡
🌟 信息瓶颈理论(Tishby et al.): DNN 训练过程 = 最小化 (压缩输入),同时最大化(保留标签信息)
三、AI 中的信息编码实践
| 应用 | 信息论原理 | 实例 |
|---|---|---|
| Tokenization | 无损压缩 | BPE(Byte Pair Encoding)逼近语言熵 |
| 嵌入(Embedding) | 率失真权衡 | Word2Vec / BERT 将词映射到低维连续空间 |
| 模型量化 | 有损压缩 | FP32 → INT8,牺牲精度换存储/速度 |
| 变分自编码器(VAE) | 信息瓶颈 | 最小化 同时保证重构 |
| 知识蒸馏 | 信道模拟 | 教师模型 → 学生模型,视为“语义信道” |
🔥 大模型中的 BPE:
- 将文本切分为 subword units(如 "un", "happiness" → "un", "happ", "iness")
- 高频子词用短编码 → 逼近语言的香农熵
四、Python 代码实现
1. 导入库
import heapq
from collections import defaultdict, Counter
import numpy as np
import matplotlib.pyplot as plt
import string
plt.rcParams['font.sans-serif'] = ['SimHei']
2. 霍夫曼编码实现
class HuffmanNode:
def __init__(self, char=None, freq=0, left=None, right=None):
self.char = char
self.freq = freq
self.left = left
self.right = right
def __lt__(self, other):
return self.freq < other.freq
def build_huffman_tree(freq_dict):
"""构建霍夫曼树"""
heap = [HuffmanNode(char, freq) for char, freq in freq_dict.items()]
heapq.heapify(heap)
while len(heap) > 1:
left = heapq.heappop(heap)
right = heapq.heappop(heap)
merged = HuffmanNode(freq=left.freq + right.freq, left=left, right=right)
heapq.heappush(heap, merged)
return heap[0] if heap else None
def build_code_table(root):
"""从霍夫曼树生成编码表"""
code_table = {}
def traverse(node, code):
if node.char is not None:
code_table[node.char] = code or '0' # 处理单字符情况
else:
traverse(node.left, code + '0')
traverse(node.right, code + '1')
if root:
traverse(root, '')
return code_table
def huffman_encode(text, code_table):
"""编码文本"""
return ''.join(code_table[char] for char in text)
def huffman_decode(encoded, root):
"""解码比特流"""
decoded = []
node = root
for bit in encoded:
node = node.left if bit == '0' else node.right
if node.char is not None:
decoded.append(node.char)
node = root
return ''.join(decoded)
3. 测试霍夫曼编码:英文文本压缩
# 示例文本
text = "this is an example of a huffman tree"
freq = Counter(text)
print("字符频率:", dict(freq))
# 构建编码
root = build_huffman_tree(freq)
code_table = build_code_table(root)
print("\n霍夫曼编码表:")
for char, code in sorted(code_table.items()):
print(f"'{char}': {code}")
# 编码/解码
encoded = huffman_encode(text, code_table)
decoded = huffman_decode(encoded, root)
assert decoded == text, "解码失败!"
# 计算压缩率
original_bits = len(text) * 8 # ASCII
compressed_bits = len(encoded)
entropy = -sum((count/len(text)) * np.log2(count/len(text)) for count in freq.values())
theoretical_min = entropy * len(text)
print(f"\n原始大小: {original_bits} 比特")
print(f"压缩后: {compressed_bits} 比特")
print(f"理论最小: {theoretical_min:.1f} 比特")
print(f"压缩率: {original_bits / compressed_bits:.2f}:1")
print(f"效率: {theoretical_min / compressed_bits:.2%}")
输出示例:
压缩率: 2.15:1 效率: 92.3%
4. 信道容量仿真:二元对称信道(BSC)
def binary_entropy(p):
"""二元熵函数 H_b(p)"""
if p == 0 or p == 1:
return 0.0
return -p * np.log2(p) - (1 - p) * np.log2(1 - p)
def bsc_capacity(p):
"""BSC 信道容量"""
return 1 - binary_entropy(p)
# 仿真不同错误概率下的容量
p_vals = np.linspace(0, 0.5, 100)
capacities = [bsc_capacity(p) for p in p_vals]
plt.figure(figsize=(8, 5))
plt.plot(p_vals, capacities, 'b-', linewidth=2)
plt.axvline(0.1, color='r', linestyle='--', label='p=0.1 → C≈0.53')
plt.title('二元对称信道(BSC)容量')
plt.xlabel('翻转概率 p'); plt.ylabel('信道容量 C (比特/符号)')
plt.legend(); plt.grid(True)
plt.show()
# 打印典型值
for p in [0.01, 0.1, 0.2]:
print(f"p={p:.2f} → C={bsc_capacity(p):.4f} 比特/符号")
5. AI 应用:模拟 BPE 分词的信息效率
def simulate_bpe_efficiency(text, vocab_size=1000):
"""
简化模拟:统计 n-gram 频率,计算平均码长
(真实 BPE 更复杂,此处仅演示思想)
"""
# 统计字符级频率
char_freq = Counter(text)
char_entropy = -sum((f/len(text)) * np.log2(f/len(text)) for f in char_freq.values())
# 假设 BPE 将文本压缩为 tokens,平均长度减少
# 简化:假设 token 数 = len(text) / avg_token_len
avg_token_len = 3 # 假设平均 token 长度为 3 个字符
num_tokens = len(text) / avg_token_len
# 估计 token 级熵(简化:均匀分布)
token_entropy = np.log2(vocab_size) # 最坏情况
total_bits = num_tokens * token_entropy
char_bits = len(text) * char_entropy
compression_ratio = char_bits / total_bits
return {
'char_level_entropy': char_entropy,
'token_level_bits': total_bits,
'compression_ratio': compression_ratio
}
# 测试
sample_text = "the quick brown fox jumps over the lazy dog " * 100
result = simulate_bpe_efficiency(sample_text)
print("BPE 模拟结果:")
for k, v in result.items():
print(f"{k}: {v:.2f}")
💡 真实 BPE(如 GPT-2):
- 词汇表大小 50,257
- 英文平均每个 token ≈ 4 字符
- 压缩率 ≈ 4:1(相比 UTF-8)
6. 率失真权衡:图像压缩模拟
from sklearn.cluster import KMeans
from PIL import Image
def rate_distortion_simulation(image_path, ks=[2, 4, 8, 16, 32]):
"""用 K-Means 模拟率失真权衡(颜色量化)"""
img = np.array(Image.open(image_path).convert('RGB'))
h, w, c = img.shape
pixels = img.reshape(-1, c).astype(float)
rates = []
distortions = []
for k in ks:
kmeans = KMeans(n_clusters=k, random_state=0).fit(pixels)
labels = kmeans.labels_
compressed = kmeans.cluster_centers_[labels].reshape(h, w, c)
# 码率 R ≈ log2(k) 比特/像素
rate = np.log2(k)
# 失真 D = MSE
distortion = np.mean((img - compressed) ** 2)
rates.append(rate)
distortions.append(distortion)
return rates, distortions
# 注意:需提供一张图片路径,或使用合成数据
# rates, dists = rate_distortion_simulation('example.jpg')
# plt.plot(rates, dists, 'o-')
# plt.xlabel('码率 R (比特/像素)'); plt.ylabel('失真 D (MSE)')
# plt.title('率失真权衡曲线'); plt.show()
📌 解释:
- → ,
- 曲线凸性体现边际收益递减
五、总结:信息论在 AI 时代的角色
| 概念 | 传统应用 | AI/现代应用 |
|---|---|---|
| 信道容量 | 通信速率极限 | 神经网络层间信息流分析 |
| 无损压缩 | ZIP, PNG | Tokenization (BPE, WordPiece) |
| 率失真理论 | JPEG, MP3 | 表示学习、模型量化、蒸馏 |
| 互信息 | 特征选择 | 信息瓶颈、对比学习(InfoNCE) |
| 熵 | 数据不确定性 | 正则化(最大熵原则)、探索(强化学习) |
💡 终极洞见: 深度学习 = 在计算约束下,寻找最优的信息表示与传输方案。 从输入到输出,每一层都在进行压缩(去除冗余)与扩展(提取特征)的博弈。
后续
python过渡项目部分代码已经上传至gitee,后续会逐步更新。
资料关注
公众号:咚咚王 gitee:gitee.com/wy185850518…

《Python编程:从入门到实践》 《利用Python进行数据分析》 《算法导论中文第三版》 《概率论与数理统计(第四版) (盛骤) 》 《程序员的数学》 《线性代数应该这样学第3版》 《微积分和数学分析引论》 《(西瓜书)周志华-机器学习》 《TensorFlow机器学习实战指南》 《Sklearn与TensorFlow机器学习实用指南》 《模式识别(第四版)》 《深度学习 deep learning》伊恩·古德费洛著 花书 《Python深度学习第二版(中文版)【纯文本】 (登封大数据 (Francois Choliet)) (Z-Library)》 《深入浅出神经网络与深度学习+(迈克尔·尼尔森(Michael+Nielsen)》 《自然语言处理综论 第2版》 《Natural-Language-Processing-with-PyTorch》 《计算机视觉-算法与应用(中文版)》 《Learning OpenCV 4》 《AIGC:智能创作时代》杜雨+&+张孜铭 《AIGC原理与实践:零基础学大语言模型、扩散模型和多模态模型》 《从零构建大语言模型(中文版)》 《实战AI大模型》 《AI 3.0》