别再死记硬背SVD了!用Python从零手搓一个共现矩阵(附完整代码与可视化)
从零构建共现矩阵:Python实战与可视化解析
在自然语言处理领域,词向量表示一直是核心课题。传统方法如TF-IDF虽然简单有效,但无法捕捉词语间的语义关系。共现矩阵(Co-Occurrence Matrix)通过统计词语在上下文窗口中的共现频率,为词嵌入提供了更丰富的语义信息。本文将带你用Python从零实现一个完整的共现矩阵构建流程,包括文本预处理、字典生成、滑动窗口计数和热力图可视化。
1. 理解共现矩阵的核心概念
共现矩阵本质上是一个对称矩阵,记录语料库中每对词语在一定窗口大小内共同出现的次数。它的核心假设是:语义相近的词语往往出现在相似的上下文中。例如,"咖啡"和"茶"可能经常与"喝"、"杯子"等词共同出现。
关键参数解析:
| 参数 | 说明 | 典型值 |
|---|---|---|
| 窗口大小 | 定义上下文范围 | 2-10 |
| 权重衰减 | 距离中心词越远权重越低 | 线性/指数衰减 |
| 最小词频 | 过滤低频词 | 3-5 |
提示:窗口大小选择需要平衡局部语法(小窗口)和全局语义(大窗口)的关系
共现矩阵的数学表示为:
import numpy as np # 假设词汇表大小为V cooc_matrix = np.zeros((V, V)) # 初始化V×V的零矩阵2. 数据预处理与词典构建
我们从简单的文本开始,构建一个完整的处理流程。以下示例使用《傲慢与偏见》的开篇段落:
text = """ It is a truth universally acknowledged, that a single man in possession of a good fortune, must be in want of a wife. """ # 预处理函数 def preprocess(text): # 转换为小写并移除非字母字符 text = text.lower() words = re.findall(r'\w+', text) return words words = preprocess(text) print(f"处理后词汇: {words}")构建词汇表的完整流程:
- 统计词频
- 过滤低频词
- 建立词到索引的映射
from collections import Counter def build_vocab(words, min_count=1): counter = Counter(words) vocab = {w:i for i,(w,c) in enumerate(counter.items()) if c >= min_count} return vocab vocab = build_vocab(words) print(f"词汇表: {vocab}")3. 滑动窗口计数实现
窗口大小为2的共现计数算法:
def build_cooccurrence_matrix(words, vocab, window_size=2): V = len(vocab) matrix = np.zeros((V, V)) for i, center_word in enumerate(words): if center_word not in vocab: continue # 确定窗口边界 start = max(0, i - window_size) end = min(len(words), i + window_size + 1) for j in range(start, end): if j == i: # 跳过中心词本身 continue context_word = words[j] if context_word in vocab: matrix[vocab[center_word]][vocab[context_word]] += 1 return matrix cooc_matrix = build_cooccurrence_matrix(words, vocab)性能优化技巧:
- 使用稀疏矩阵存储(如scipy.sparse)
- 多进程处理大型语料
- 增量式更新矩阵
4. 矩阵可视化与分析
使用matplotlib和seaborn进行热力图可视化:
import seaborn as sns import matplotlib.pyplot as plt def visualize_matrix(matrix, vocab): plt.figure(figsize=(10,8)) sns.heatmap(matrix, xticklabels=vocab.keys(), yticklabels=vocab.keys(), cmap='Blues') plt.title("Co-Occurrence Matrix Heatmap") plt.show() visualize_matrix(cooc_matrix, vocab)解读热力图:
- 对角线表示词语自共现(通常为0)
- 颜色深浅反映共现强度
- 对称性验证矩阵的正确性
5. 进阶应用与优化
5.1 加权窗口计数
距离中心词越远的上下文词贡献越小:
def weighted_count(matrix, center_idx, context_idx, distance): weight = 1.0 / distance # 线性衰减 matrix[center_idx][context_idx] += weight5.2 处理大规模语料
使用生成器逐行处理大文件:
def process_large_corpus(file_path, window_size=2): cooc_matrix = np.zeros((V, V)) with open(file_path) as f: for line in f: words = preprocess(line) update_matrix(cooc_matrix, words, window_size) return cooc_matrix5.3 降维与词向量生成
虽然SVD是传统方法,但我们可以尝试更现代的降维技术:
from sklearn.decomposition import TruncatedSVD def generate_word_vectors(matrix, dim=50): svd = TruncatedSVD(n_components=dim) word_vectors = svd.fit_transform(matrix) return word_vectors6. 实际应用案例
分析科技新闻中的技术术语关联:
tech_news = """ Artificial intelligence is transforming healthcare with deep learning. Blockchain and cryptocurrency are revolutionizing finance. Quantum computing promises breakthroughs in materials science. """ # 构建技术领域共现矩阵 tech_words = preprocess(tech_news) tech_vocab = build_vocab(tech_words) tech_matrix = build_cooccurrence_matrix(tech_words, tech_vocab, window_size=3) # 找出强关联词对 strong_pairs = np.where(tech_matrix > 1) for i,j in zip(*strong_pairs): print(f"{list(tech_vocab.keys())[i]} - {list(tech_vocab.keys())[j]}")7. 常见问题与调试技巧
问题1:矩阵过于稀疏
- 增大窗口尺寸
- 降低最小词频阈值
- 使用更丰富的语料
问题2:内存不足
- 使用稀疏矩阵格式
- 分批处理数据
- 降低词汇表规模
问题3:无意义的强关联
- 去除停用词
- 添加词性过滤
- 使用短语检测
# 调试示例:检查特定词对的共现 word1 = "deep" word2 = "learning" print(f"共现次数: {cooc_matrix[vocab[word1]][vocab[word2]]}")8. 完整代码实现
以下是整合所有功能的完整实现:
import numpy as np import re from collections import Counter import seaborn as sns import matplotlib.pyplot as plt class CooccurrenceMatrix: def __init__(self, window_size=2, min_count=1): self.window_size = window_size self.min_count = min_count self.vocab = {} self.matrix = None def preprocess(self, text): text = text.lower() return re.findall(r'\w+', text) def build_vocab(self, words): counter = Counter(words) self.vocab = {w:i for i,(w,c) in enumerate(counter.items()) if c >= self.min_count} self.matrix = np.zeros((len(self.vocab), len(self.vocab))) def fit(self, text): words = self.preprocess(text) self.build_vocab(words) for i, center_word in enumerate(words): if center_word not in self.vocab: continue start = max(0, i - self.window_size) end = min(len(words), i + self.window_size + 1) for j in range(start, end): if j == i: continue context_word = words[j] if context_word in self.vocab: center_idx = self.vocab[center_word] context_idx = self.vocab[context_word] self.matrix[center_idx][context_idx] += 1 def visualize(self): plt.figure(figsize=(10,8)) sns.heatmap(self.matrix, xticklabels=self.vocab.keys(), yticklabels=self.vocab.keys(), cmap='Blues') plt.title("Co-Occurrence Matrix") plt.show() # 使用示例 text = """Your input text here...""" cooc = CooccurrenceMatrix(window_size=2) cooc.fit(text) cooc.visualize()在实际项目中,共现矩阵往往只是NLP流水线的第一步。我发现将窗口大小设置为3-5,配合适当的最小词频过滤(如min_count=3),能在语义捕捉和计算效率间取得较好平衡。对于特别长的文档,分段落处理后再合并矩阵结果通常效果更好。
