词汇熵(Vocabulary Entropy)是信息论中的一个概念,用于衡量一个词汇分布的“不确定性”或“多样性”。它可以帮助我们了解词汇在某个语料库中的分布是否均匀。如果词汇分布非常均匀,熵值会较高;如果某些词汇出现得非常频繁,而其他词汇很少出现,熵值会较低。
数学表示
词汇熵的计算基于信息熵公式:
\[H = - \sum^N_{i=1} p_i \cdot log_2{p_i}\]其中, $N$ 是词汇量, $p_i$ 是词汇 $i$ 的概率(文中出现该词的频率)
计算过程
分词 -> 构造词典 -> 构建词袋模型 -> 计算词汇频率 -> 计算信息熵
示例
假设语料库如下:
cat, sat, on, the, mat
dog, ate, my, homework
cat, ate, my, homework
dog, sat, on, my, mat
构建词袋模型
cat: 2
sat: 2
on: 2
the: 1
mat: 2
dog: 2
ate: 2
my: 2
计算词汇频率
\[p_{cat}=2/15\\ p_{sat}=2/15\\ p_{on}=2/15\\ p_{the}=1/15\\ p_{mat}=2/15\\ p_{dog}=2/15\\ p_{ate}=2/15\\ p_{my}=2/15\\ p_{homework}=2/15\\\]计算信息熵
\[H = - \left(\frac {2}{15} log_2\frac {2}{15} \times 8 + \frac {1}{15} log_2\frac {1}{15}\right) = 3.1279868068776753\]Python 实现
import math
from collections import Counter
# 示例文本数据
texts = [
['cat', 'sat', 'on', 'the', 'mat'],
['dog', 'ate', 'my', 'homework'],
['cat', 'ate', 'my', 'homework'],
['dog', 'sat', 'on', 'my', 'mat']
]
# 合并所有文本
all_words = [word for doc in texts for word in doc]
# 统计词频
word_freq = Counter(all_words)
# 总词数
total_words = len(all_words)
# 计算词汇熵
entropy = 0.0
for freq in word_freq.values():
probability = freq / total_words
entropy -= probability * math.log2(probability)
print(f"词汇熵: {entropy}")