什么是词向量
词向量(Word Embeddings)是一种将词语表示为实数向量的技术。这种表示方式将文本数据转换为可以输入到机器学习模型中的数值形式。词向量通过捕捉词语之间的语义关系,使得相似词语在向量空间中距离更近。
词向量的生成
词向量是通过在大量文本上训练模型得到的。常见的词向量生成方法包括:
- Word2Vec:通过Skip-gram或CBOW(Continuous Bag of Words)模型训练得到词向量。
- GloVe(Global Vectors for Word Representation):利用词在整个语料库中的共现矩阵来训练词向量。
- FastText:Facebook开发的词向量模型,能够处理未登录词(out-of-vocabulary words),适用于多语言环境。
词向量的表示
词向量将每个词表示为一个高维实数向量。例如,在一个300维的词向量空间中,“king”可能被表示为一个300维的向量:
[ \text{king} = [0.25, -0.12, 0.54, \ldots, 0.03] ]
词向量的用途
词向量在自然语言处理(NLP)任务中有广泛的应用,主要用途包括:
- 文本分类:将文本表示为词向量,然后用这些向量作为特征进行分类。
- 词语相似度计算:通过计算词向量之间的余弦相似度来判断词语的相似度。
- 文本聚类:利用词向量将文本数据聚类成不同的组。
- 命名实体识别(NER):通过词向量捕捉词语的语义信息,提高识别准确性。
- 机器翻译:将源语言和目标语言的词表示为向量,实现更加准确的翻译。
- 问答系统:将问题和答案表示为向量,通过向量匹配找到最相关的答案。
词向量的使用示例
以下是使用Word2Vec生成和使用词向量的示例代码:
1. 训练Word2Vec模型
from gensim.models import Word2Vec
from gensim.test.utils import common_texts
# 训练Word2Vec模型
model = Word2Vec(sentences=common_texts, vector_size=100, window=5, min_count=1, workers=4)
# 保存模型
model.save("word2vec.model")
2. 加载并使用Word2Vec模型
# 加载模型
model = Word2Vec.load("word2vec.model")
# 获取词向量
vector = model.wv['computer']
# 计算两个词的相似度
similarity = model.wv.similarity('computer', 'laptop')
print("Similarity between 'computer' and 'laptop':", similarity)
# 找出与某个词最相似的词
similar_words = model.wv.most_similar('computer', topn=5)
print("Words most similar to 'computer':", similar_words)
3. 文本分类示例
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
import numpy as np
# 准备训练数据
X = []
y = []
sentences = ["I love machine learning", "Deep learning is fascinating", "Natural language processing is amazing"]
labels = [1, 1, 0] # 1: positive, 0: negative
for sentence in sentences:
words = sentence.split()
vector = np.mean([model.wv[word] for word in words if word in model.wv], axis=0)
X.append(vector)
y.append(labels[sentences.index(sentence)])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 训练分类模型
clf = LogisticRegression()
clf.fit(X_train, y_train)
# 预测并计算准确率
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)