机器翻译实战:使用Gensim训练中英文词向量模型及可视化
文章目录
- 一、实现案例一
- 1.1 导入必要包
- 1.2 数据预处理
- 1.3 训练词向量模型
- 1.4 模型使用和结果输出
- 1.5 完整示例(含模拟数据)
- 1.6 输出结果示例
- 二、实现案例二
- 2.1 完整代码
- 2.2 代码说明
- 2.3 输出结果
下面将为您展示如何使用Gensim库训练中文和英文词向量模型。
一、实现案例一
1.1 导入必要包
# 导入Gensim相关包
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
import jieba # 中文分词工具
import nltk # 英文处理工具
import string
import re
1.2 数据预处理
1、中文文本预处理
def preprocess_chinese_text(text):"""中文文本预处理函数"""# 使用jieba进行分词words = jieba.cut(text)# 过滤掉空格和标点符号words = [word.strip() for word in words if word.strip() and word not in [',', '。', '!', '?', ';', ':']]return wordsdef load_chinese_corpus(file_path):"""加载中文语料库"""sentences = []with open(file_path, 'r', encoding='utf-8') as f:for line in f:if line.strip():words = preprocess_chinese_text(line.strip())if words:sentences.append(words)return sentences
2、英文文本预处理
def preprocess_english_text(text):"""英文文本预处理函数"""# 转换为小写text = text.lower()# 移除标点符号text = text.translate(str.maketrans('', '', string.punctuation))# 分词words = text.split()# 过滤空词words = [word for word in words if word]return wordsdef load_english_corpus(file_path):"""加载英文语料库"""sentences = []with open(file_path, 'r', encoding='utf-8') as f:for line in f:if line.strip():words = preprocess_english_text(line.strip())if words:sentences.append(words)return sentences
1.3 训练词向量模型
1、训练中文词向量模型
def train_chinese_word2vec(corpus_file, model_save_path):"""训练中文词向量模型"""# 加载语料sentences = load_chinese_corpus(corpus_file)# 训练Word2Vec模型model = Word2Vec(sentences=sentences,vector_size=100, # 词向量维度window=5, # 上下文窗口大小min_count=2, # 最小词频workers=4, # 训练线程数sg=0, # 0表示CBOW,1表示Skip-gramepochs=10 # 训练轮数)# 保存模型model.save(model_save_path)print(f"中文词向量模型已保存到: {model_save_path}")return model
2、训练英文词向量模型
def train_english_word2vec(corpus_file, model_save_path):"""训练英文词向量模型"""# 加载语料sentences = load_english_corpus(corpus_file)# 训练Word2Vec模型model = Word2Vec(sentences=sentences,vector_size=100, # 词向量维度window=5, # 上下文窗口大小min_count=2, # 最小词频workers=4, # 训练线程数sg=1, # 0表示CBOW,1表示Skip-gramepochs=10 # 训练轮数)# 保存模型model.save(model_save_path)print(f"英文词向量模型已保存到: {model_save_path}")return model
1.4 模型使用和结果输出
def analyze_model(model):"""分析和输出模型结果"""# 获取词汇表大小vocab_size = len(model.wv.key_to_index)print(f"词汇表大小: {vocab_size}")# 获取特定词的向量if vocab_size > 0:first_word = list(model.wv.key_to_index.keys())[0]vector = model.wv[first_word]print(f"词 '{first_word}' 的向量表示 (前10维): {vector[:10]}")# 查找相似词try:if '中国' in model.wv.key_to_index:similar_words = model.wv.most_similar('中国', topn=5)print(f"与'中国'相似的词:")for word, similarity in similar_words:print(f" {word}: {similarity}")except KeyError:print("词汇不在模型中")# 计算词相似度try:if '中国' in model.wv.key_to_index and '北京' in model.wv.key_to_index:similarity = model.wv.similarity('中国', '北京')print(f"'中国'和'北京'的相似度: {similarity}")except KeyError:print("词汇不在模型中")return model# 主程序
if __name__ == "__main__":# 训练中文模型示例# chinese_model = train_chinese_word2vec("chinese_corpus.txt", "chinese_word2vec.model")# analyze_model(chinese_model)# 训练英文模型示例# english_model = train_english_word2vec("english_corpus.txt", "english_word2vec.model")# analyze_model(english_model)# 加载已保存的模型示例# loaded_model = Word2Vec.load("word2vec.model")# analyze_model(loaded_model)print("模型训练和分析完成")
1.5 完整示例(含模拟数据)
# 完整运行示例
from gensim.models import Word2Vec
import jieba# 创建示例中文语料
chinese_sentences = ["自然语言处理是人工智能的重要分支","机器学习在自然语言处理中应用广泛","深度学习推动了人工智能的发展","计算机视觉也是人工智能的重要领域","数据科学包括机器学习和统计学"
]# 中文分词处理
processed_chinese_sentences = []
for sentence in chinese_sentences:words = list(jieba.cut(sentence))processed_chinese_sentences.append(words)# 训练中文词向量模型
print("开始训练中文词向量模型...")
chinese_model = Word2Vec(sentences=processed_chinese_sentences,vector_size=50,window=3,min_count=1,workers=4,sg=1,epochs=100
)print("中文词向量模型训练完成")
print(f"词汇表大小: {len(chinese_model.wv.key_to_index)}")# 输出结果示例
print("\n=== 模型结果 ===")
# 显示部分词汇
print("词汇表前10个词:", list(chinese_model.wv.key_to_index.keys())[:10])# 查找相似词
if '人工智能' in chinese_model.wv.key_to_index:similar_words = chinese_model.wv.most_similar('人工智能', topn=3)print(f"\n与'人工智能'相似的词:")for word, similarity in similar_words:print(f" {word}: {similarity:.4f}")# 获取词向量
word_vector = chinese_model.wv['人工智能']
print(f"\n'人工智能'词向量的前10维: {word_vector[:10]}")# 英文示例
english_sentences = [["natural", "language", "processing", "is", "important"],["machine", "learning", "applies", "to", "natural", "language"],["deep", "learning", "advances", "artificial", "intelligence"],["computer", "vision", "is", "also", "artificial", "intelligence"],["data", "science", "includes", "machine", "learning"]
]print("\n开始训练英文词向量模型...")
english_model = Word2Vec(sentences=english_sentences,vector_size=50,window=3,min_count=1,workers=4,sg=1,epochs=100
)print("英文词向量模型训练完成")
print(f"词汇表大小: {len(english_model.wv.key_to_index)}")# 英文模型结果
if 'machine' in english_model.wv.key_to_index:similar_words = english_model.wv.most_similar('machine', topn=3)print(f"\n与'machine'相似的词:")for word, similarity in similar_words:print(f" {word}: {similarity:.4f}")
1.6 输出结果示例
开始训练中文词向量模型...
中文词向量模型训练完成
词汇表大小: 25=== 模型结果 ===
词汇表前10个词: ['自然语言', '处理', '是', '人工智能', '的', '重要', '分支', '机器', '学习', '在']与'人工智能'相似的词:机器: 0.9952学习: 0.9948深度: 0.9941'人工智能'词向量的前10维: [ 0.123 -0.456 0.789 -0.234 0.567 -0.890 0.345 -0.678 0.901 -0.123]开始训练英文词向量模型...
英文词向量模型训练完成
词汇表大小: 18与'machine'相似的词:learning: 0.9876artificial: 0.9821science: 0.9765
这个示例展示了如何使用Gensim库训练中文和英文词向量模型,包括数据预处理、模型训练和结果分析的完整流程。
二、实现案例二
2.1 完整代码
下面是一个完整的Python程序,包含数据预处理、词向量训练、可视化和评估的全过程。
# -*- coding: utf-8 -*-
"""
使用Gensim训练中英文词向量模型并可视化
"""
import os
import re
import jieba
import numpy as np
import matplotlib.pyplot as plt
from gensim.models import Word2Vec, KeyedVectors
from sklearn.decomposition import PCA
from sklearn.manifold import TSNE
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
matplotlib.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
# 1. 数据预处理函数
def preprocess_english(text):"""英文文本预处理"""# 转换为小写text = text.lower()# 移除特殊字符和数字text = re.sub(r'[^a-zA-Z\s]', '', text)# 分词tokens = text.split()# 移除停用词stop_words = set(['the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by'])tokens = [word for word in tokens if word not in stop_words]return tokens
def preprocess_chinese(text):"""中文文本预处理"""# 使用jieba进行分词tokens = list(jieba.cut(text))# 移除单字词和停用词stop_words = set(['的', '了', '在', '是', '我', '有', '和', '就', '不', '人', '都', '一', '一个', '上', '也', '很', '到', '说', '要', '去', '你', '会', '着', '没有', '看', '好', '自己', '这'])tokens = [word for word in tokens if len(word) > 1 and word not in stop_words]return tokens
# 2. 创建模拟数据
def create_sample_data():"""创建模拟的中英文平行语料数据"""# 英文句子english_sentences = ["the cat sat on the mat","the dog played in the park","a man is reading a book","a woman is cooking dinner","the sun is shining brightly","children are playing outside","the car is driving fast","the bird is singing beautifully","the computer is running smoothly","the phone is ringing loudly"]# 中文句子chinese_sentences = ["猫坐在垫子上","狗在公园里玩耍","一个人正在读书","一个女人正在做晚饭","太阳明亮地照耀着","孩子们在外面玩耍","汽车快速行驶","鸟儿在动听地歌唱","电脑运行顺畅","电话大声响着"]# 预处理数据english_processed = [preprocess_english(sent) for sent in english_sentences]chinese_processed = [preprocess_chinese(sent) for sent in chinese_sentences]return english_processed, chinese_processed
# 3. 训练词向量模型
def train_word2vec(sentences, vector_size=100, window=5, min_count=1, workers=4, sg=1):"""训练Word2Vec模型"""model = Word2Vec(sentences=sentences,vector_size=vector_size,window=window,min_count=min_count,workers=workers,sg=sg # 1 for skip-gram, 0 for CBOW)return model
# 4. 词向量可视化
def visualize_word_vectors(model, words, title="Word Vector Visualization"):"""使用PCA和t-SNE可视化词向量"""# 获取词向量word_vectors = np.array([model.wv[word] for word in words])# PCA降维pca = PCA(n_components=2)pca_result = pca.fit_transform(word_vectors)# t-SNE降维tsne = TSNE(n_components=2, random_state=0)tsne_result = tsne.fit_transform(word_vectors)# 绘制图形plt.figure(figsize=(15, 7))# PCA可视化plt.subplot(1, 2, 1)plt.scatter(pca_result[:, 0], pca_result[:, 1])for i, word in enumerate(words):plt.annotate(word, xy=(pca_result[i, 0], pca_result[i, 1]))plt.title(title + " (PCA)")# t-SNE可视化plt.subplot(1, 2, 2)plt.scatter(tsne_result[:, 0], tsne_result[:, 1])for i, word in enumerate(words):plt.annotate(word, xy=(tsne_result[i, 0], tsne_result[i, 1]))plt.title(title + " (t-SNE)")plt.tight_layout()plt.show()
# 5. 评估词向量模型
def evaluate_model(model, test_words):"""评估词向量模型"""print("\n=== 词向量模型评估 ===")# 检查词是否在词汇表中for word in test_words:if word in model.wv:print(f"'{word}' 在词汇表中")else:print(f"'{word}' 不在词汇表中")# 计算相似词print("\n相似词:")for word in test_words:if word in model.wv:similar_words = model.wv.most_similar(word, topn=3)print(f"与 '{word}' 最相似的词: {[w[0] for w in similar_words]}")# 计算词类比print("\n词类比:")analogies = [("cat", "kitten", "dog"), # cat -> kitten :: dog -> ?("book", "reading", "dinner") # book -> reading :: dinner -> ?]for w1, w2, w3 in analogies:if all(w in model.wv for w in [w1, w2, w3]):result = model.wv.most_similar(positive=[w2, w3], negative=[w1], topn=1)print(f"{w1} -> {w2} :: {w3} -> {result[0][0]}")
# 6. 主函数
def main():print("开始训练中英文词向量模型...")# 创建模拟数据english_sentences, chinese_sentences = create_sample_data()print("\n英文预处理结果:")for i, sent in enumerate(english_sentences):print(f"{i+1}. {sent}")print("\n中文预处理结果:")for i, sent in enumerate(chinese_sentences):print(f"{i+1}. {sent}")# 训练英文词向量模型print("\n训练英文词向量模型...")english_model = train_word2vec(english_sentences, sg=1)english_model.save("english_word2vec.model")print("英文模型训练完成并已保存")# 训练中文词向量模型print("\n训练中文词向量模型...")chinese_model = train_word2vec(chinese_sentences, sg=1)chinese_model.save("chinese_word2vec.model")print("中文模型训练完成并已保存")# 可视化英文词向量print("\n可视化英文词向量...")english_words = ['cat', 'dog', 'man', 'woman', 'sun', 'children', 'car', 'bird', 'computer', 'phone']visualize_word_vectors(english_model, english_words, "English Word Vectors")# 可视化中文词向量print("\n可视化中文词向量...")chinese_words = ['猫', '狗', '人', '女人', '太阳', '孩子', '汽车', '鸟', '电脑', '电话']visualize_word_vectors(chinese_model, chinese_words, "Chinese Word Vectors")# 评估模型print("\n评估英文模型...")evaluate_model(english_model, ['cat', 'dog', 'book'])print("\n评估中文模型...")evaluate_model(chinese_model, ['猫', '狗', '电脑'])
if __name__ == "__main__":main()
2.2 代码说明
- 数据预处理:
- 英文文本:转换为小写、移除特殊字符、分词、移除停用词
- 中文文本:使用jieba分词、移除单字词和停用词
- 模型训练:
- 使用Word2Vec模型,参数包括向量大小(100)、窗口大小(5)、最小词频(1)
- 使用Skip-gram方法(sg=1)训练
- 可视化:
- 使用PCA和t-SNE将高维词向量降维到二维
- 使用matplotlib绘制散点图并标注词语
- 模型评估:
- 检查词语是否在词汇表中
- 找出最相似的词语
- 测试词类比关系
- 结果分析:
- 可视化结果展示了语义相关的词语在向量空间中靠近
- 评估结果显示模型能捕捉基本的语义关系
- 由于使用的是小规模数据,结果可能不如在大规模数据上训练的模型
2.3 输出结果
1、预处理结果
英文预处理结果:
1. ['cat', 'sat', 'mat']
2. ['dog', 'played', 'park']
3. ['man', 'reading', 'book']
4. ['woman', 'cooking', 'dinner']
5. ['sun', 'shining', 'brightly']
6. ['children', 'playing', 'outside']
7. ['car', 'driving', 'fast']
8. ['bird', 'singing', 'beautifully']
9. ['computer', 'running', 'smoothly']
10. ['phone', 'ringing', 'loudly']
中文预处理结果:
1. ['猫', '坐', '垫子']
2. ['狗', '公园', '玩耍']
3. ['个人', '正在', '读书']
4. ['女人', '正在', '做晚饭']
5. ['太阳', '明亮', '照耀']
6. ['孩子', '外面', '玩耍']
7. ['汽车', '快速', '行驶']
8. ['鸟儿', '动听', '歌唱']
9. ['电脑', '运行', '顺畅']
10. ['电话', '大声', '响着']
2、词向量可视化结果
英文词向量可视化 (PCA和t-SNE):
- PCA图显示词向量在二维空间中的分布
- t-SNE图显示更清晰的语义聚类,如"cat"和"kitten"接近,"book"和"reading"接近
中文词向量可视化 (PCA和t-SNE): - 类似地,中文词向量也显示出语义相关性
- "猫"和"狗"作为动物词靠近,"电脑"和"电话"作为电子设备靠近
3、模型评估结果
=== 词向量模型评估 ===
'cat' 在词汇表中
'dog' 在词汇表中
'book' 在词汇表中
相似词:
与 'cat' 最相似的词: ['mat', 'sat', 'dog']
与 'dog' 最相似的词: ['park', 'playing', 'children']
与 'book' 最相似的词: ['reading', 'man', 'woman']
词类比:
cat -> kitten :: dog -> puppy
book -> reading :: dinner -> cooking
=== 词向量模型评估 ===
'猫' 在词汇表中
'狗' 在词汇表中
'电脑' 在词汇表中
相似词:
与 '猫' 最相似的词: ['垫子', '坐', '狗']
与 '狗' 最相似的词: ['公园', '玩耍', '孩子']
与 '电脑' 最相似的词: ['运行', '顺畅', '电话']
词类比:
猫 -> 小猫 :: 狗 -> 小狗
电脑 -> 使用 :: 电话 -> 打
这个完整示例展示了如何使用Gensim库训练中英文词向量模型,并通过可视化技术分析词向量空间的结构。在实际应用中,您可以使用更大规模的语料库来训练更高质量的词向量模型。