别再死记硬背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_count1): 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_size2): 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, xticklabelsvocab.keys(), yticklabelsvocab.keys(), cmapBlues) 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_size2): 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, dim50): svd TruncatedSVD(n_componentsdim) 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_size3) # 找出强关联词对 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_size2, min_count1): 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, xticklabelsself.vocab.keys(), yticklabelsself.vocab.keys(), cmapBlues) plt.title(Co-Occurrence Matrix) plt.show() # 使用示例 text Your input text here... cooc CooccurrenceMatrix(window_size2) cooc.fit(text) cooc.visualize()在实际项目中共现矩阵往往只是NLP流水线的第一步。我发现将窗口大小设置为3-5配合适当的最小词频过滤如min_count3能在语义捕捉和计算效率间取得较好平衡。对于特别长的文档分段落处理后再合并矩阵结果通常效果更好。