在掌握了概率统计模型方法之后,今天我们来聊聊Word2Vec。这是由Google在2013年提出的一种将单词表示为向量的方法,它的核心贡献在于为自然语言处理提供了一种能让计算机更好地理解单词间语义关系的向量化方式。不妨说,它给语言装上了一个可计算的“坐标系统”。
一、Word2Vec 的基本概念
1. 定义
- Word2Vec 是一种将单词映射到高维空间的方法,在语义上相近的单词,它们的向量在空间中也彼此靠近。比如经典的例子:“King - Man + Woman ≈ Queen”。
2. 两种模型
- CBOW(Continuous Bag of Words):根据当前单词的上下文来预测该单词。例如在“The cat sat on the mat”中,用上下文“The cat … on the mat”来预测中间的“sat”。
- Skip-gram:正好反过来,根据当前单词预测它的上下文。还是那句话,用“sat”去预测它周围的“The cat…on the mat”。

二、Word2Vec 模型的实现
1. CBOW 模型
输入是上下文单词,输出是目标单词。优化的目标是最大化目标单词在给定上下文下的条件概率,通常用Softmax来计算概率分布。损失函数如下:
实际应用中,我们可以借助Gensim库轻松实现CBOW模型并训练词向量。下面是一个简单的示例:
from gensim.models import Word2Vec
import re
import string
import jieba
# 示例文本
text = """
一个男人和一个女人在打猎,吃树上的果实
亚当和夏娃在远远看着他们
我在写从零基础到精通大语言模型
"""
# 数据预处理
def preprocess(text):
text = text.lower()
text = re.sub(f"[{string.punctuation}]", "", text)
return list(jieba.cut(text, cut_all=False))
# 预处理数据
sentences = [preprocess(sentence) for sentence in text.split("\n") if sentence]
print(sentences)
# 使用 Gensim 训练 CBOW 模型
model = Word2Vec(sentences, vector_size=100, window=5, min_count=1, sg=0) # sg=0 代表使用 CBOW 模型
# 查看词向量
print(f"Vector for '男人':\n {model.wv['男人']}")
# 寻找相似的单词
similar_words = model.wv.most_similar("男人")
print(f"Words most similar to '男人':\n {similar_words}")
# 计算机输出 [('模型', 0.25292226672172546), ('和', 0.17017711699008942), ('亚当', 0.15016482770442963), ('女人', 0.13886758685112), ('他们', 0.10851667821407318), ('基础', 0.09937489777803421), ('打猎', 0.034764934331178665), ('写', 0.033063217997550964), ('夏娃', 0.01984061673283577), ('看着', 0.0160182137042284)]
CBOW模型的优缺点及改进方法
优点
- 效率高:上下文单词数量有限,训练速度快。
- 鲁棒性:在小数据集上表现更稳定。
缺点
- 忽略顺序:CBOW只考虑上下文单词的集合,不考虑它们的前后顺序。
- 上下文窗口:窗口大小需要手动设定。窗口过小只能捕捉局部信息,窗口过大则可能引入噪音。
改进方向
- Skip-gram 模型:CBOW的逆操作,用目标词预测上下文。下面就会详细说。
- 子词建模:比如FastText,能够捕捉词的子结构信息。
- 上下文相关的词向量:使用BERT、GPT等模型,能根据上下文动态调整词向量。
2. Skip-gram 模型
- 输入是目标单词,输出是上下文单词。
- 优化目标是最大化上下文单词在目标单词下的条件概率。
- 损失函数如下:
模型结构
- 输入层:目标词的单词索引。
- 隐藏层:目标词映射到一个词向量。
- 输出层:输出上下文词的概率分布。
Skip-gram 模型的应用场景
1. 相似性计算与推荐
- 根据用户的历史搜索或兴趣,推荐相关内容或产品。比如在电商中,用户搜索“laptop”,系统就可以推荐“tablet”、“desktop”等。
similar_words = model.wv.most_similar("laptop")
print(f"Words most similar to 'natural':\n {similar_words}")
2. 词类比与推理
- 解决“King - Man + Woman = Queen”这类问题。
result = model.wv.most_similar(positive=["king", "woman"], negative=["man"])
print(f"Words similar to 'King - Man + Woman':\n {result}")
3. 文本分类与聚类
- 利用Word2Vec将文本表示为向量,应用于情感分析、新闻分类(体育、财经、科技)等任务。
from sklearn.svm import SVC
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
import numpy as np
from gensim.models import Word2Vec
import re, string
# 数据预处理
def preprocess(text):
text = text.lower()
text = re.sub(f"[{string.punctuation}]", "", text)
return text.split()
# 示例数据
data = [
("Machine learning is great", "tech"),
("The stock market is booming", "finance"),
("Football is very popular", "sports"),
("Deep learning is a branch of machine learning", "tech"),
("Investing in stocks is risky", "finance"),
("Basketball is fun", "sports"),
]
# 预处理数据
sentences = [preprocess(text) for text, _ in data]
labels = [label for _, label in data]
# 训练 Word2Vec 模型
model = Word2Vec(sentences, vector_size=100, window=5, min_count=1, sg=1)
# 将文本转化为向量
def get_vector_base(sentence):
return np.mean([model.wv[word] for word in preprocess(sentence) if word in model.wv], axis=0)
def get_vector(sentence):
words = preprocess(sentence)
word_vectors = [model.wv[word] for word in words if word in model.wv]
if not word_vectors:
return np.zeros(model.vector_size)
return np.mean(word_vectors, axis=0)
X = np.array([get_vector(text) for text, _ in data])
y = np.array(labels)
# 训练分类模型
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
clf = make_pipeline(StandardScaler(), SVC())
clf.fit(X_train, y_train)
# 评估模型
y_pred = clf.predict(X_test)
print(classification_report(y_test, y_pred))
4. 聚类与可视化
- 使用T-SNE或PCA对词向量降维,然后可视化。
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt
# 获取所有词向量
words = list(model.wv.index_to_key)
word_vectors = model.wv[words]
# PCA 降维
pca = PCA(n_components=2)
word_vectors_pca = pca.fit_transform(word_vectors)
# 可视化
plt.figure(figsize=(10, 8))
plt.scatter(word_vectors_pca[:, 0], word_vectors_pca[:, 1], marker='o')
for i, word in enumerate(words):
plt.text(word_vectors_pca[i, 0], word_vectors_pca[i, 1], word)
plt.show()
三、Word2Vec 模型的改进与替代
- FastText:Word2Vec的改进版,能捕捉词的子结构信息(如字符n-gram)。
- GloVe:基于共现矩阵的全局统计词向量模型。
- 其他预训练词向量:如BERT、BGE等,提供更丰富的语义表征。
优化技巧
- 负采样(Negative Sampling):将多分类问题简化为二分类,每个正样本随机采样几个负样本来加速训练。
- 层次Softmax(Hierarchical Softmax):利用Huffman树实现高效的Softmax计算。
