”工欲善其事,必先利其器。“—孔子《论语.录灵公》
首页 > 编程 > 使用 Python 进行词嵌入:Wordc

使用 Python 进行词嵌入:Wordc

发布于2024-11-08
浏览:464

Word-embedding-with-Python: Wordc

使用 Python(和 Gensim)实现 word2vec

  • 注意:此代码是用Python 3.6.1(Gensim 2.3.0)编写的

  • word2vec与Gensim的Python实现及应用

  • 原始论文:Mikolov, T.、Chen, K.、Corrado, G. 和 Dean, J. (2013)。向量空间中单词表示的有效估计。 arXiv 预印本 arXiv:1301.3781.

import re
import numpy as np

from gensim.models import Word2Vec
from nltk.corpus import gutenberg
from multiprocessing import Pool
from scipy import spatial
  • 导入训练数据集
  • 从nltk库导入莎士比亚的哈姆雷特语料库
sentences = list(gutenberg.sents('shakespeare-hamlet.txt'))   # import the corpus and convert into a list

print('Type of corpus: ', type(sentences))
print('Length of corpus: ', len(sentences))

语料库类型:class 'list'
语料长度:3106

print(sentences[0])    # title, author, and year
print(sentences[1])
print(sentences[10])

['[', 'The', '悲剧', 'of', '哈姆雷特', 'by', '威廉', '莎士比亚', '1599', ']']
['Actus', 'Primus', '.']
['弗兰', '.']

预处理数据

  • 使用re模块预处理数据
  • 将所有字母转换为小写
  • 删除标点符号、数字等。
for i in range(len(sentences)):
    sentences[i] = [word.lower() for word in sentences[i] if re.match('^[a-zA-Z] ', word)]  
print(sentences[0])    # title, author, and year
print(sentences[1])
print(sentences[10])

['the'、'悲剧'、'of'、'哈姆雷特'、'by'、'威廉'、'莎士比亚']
['actus', 'primus']
['弗兰']

创建和训练模型

  • 创建 word2vec 模型并使用 Hamlet 语料库对其进行训练
  • 关键参数说明(https://radimrehurek.com/gensim/models/word2vec.html)
    • 句子:训练数据(必须是带有标记化句子的列表)
    • size:嵌入空间的尺寸
    • sg: CBOW 如果为 0,skip-gram 如果为 1
    • 窗口:每个上下文中的单词数(如果窗口
    • 大小为3,考虑左邻域中的3个单词和右邻域中的3个单词)
    • min_count:词汇表中包含的最小单词数
    • iter:训练迭代次数
    • workers:要训练的工作线程数量
model = Word2Vec(sentences = sentences, size = 100, sg = 1, window = 3, min_count = 1, iter = 10, workers = Pool()._processes)

model.init_sims(replace = True)

保存和加载模型

  • word2vec模型可以本地保存和加载
  • 这样做可以减少再次训练模型的时间
model.save('word2vec_model')
model = Word2Vec.load('word2vec_model')

相似度计算

  • 嵌入单词(即向量)之间的相似度可以使用余弦相似度等指标来计算
model.most_similar('hamlet')

[('horatio', 0.9978846311569214),
('女王', 0.9971947073936462),
('莱尔特斯', 0.9971820116043091),
('国王', 0.9968599081039429),
('妈妈', 0.9966716170310974),
('哪里', 0.9966292381286621),
('迪尔', 0.9965540170669556),
('奥菲莉亚', 0.9964221715927124),
('非常', 0.9963752627372742),
('哦', 0.9963476657867432)]

v1 = model['king']
v2 = model['queen']

# define a function that computes cosine similarity between two words
def cosine_similarity(v1, v2):
    return 1 - spatial.distance.cosine(v1, v2)

cosine_similarity(v1, v2)

0.99437165260314941

版本声明 本文转载于:https://dev.to/ragoli86/word-embedding-with-python-word2vec-540c?1如有侵犯,请联系[email protected]删除
最新教程 更多>

免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。

Copyright© 2022 湘ICP备2022001581号-3