NLP工具——Gensim的model.keyedvectors模块

1、简介

models.keyedVectors模块实现了词向量及其相似性查找。训练好的此线路与训练方式无关,因此他们可以由独立结构表示。

该结构称为KeyedVectors,实质上是实体和向量之间的映射。每个实体由其字符串id标识,因此是字符串和1维数组之间的映射关系。
实体通常对应一个单词,因此是将单词映射到一维向量,对于某些某些,值也可以对应一篇文档,一个图像或其他。

KeyedVectors和完整模型的区别在于无法进一步的训练,及更小的RAM占用,更简单的接口。

2、如何获取词向量

训练一个完整的模型,然后获取它的model.wv属性,该属性包含独立的keyed vectors。如,使用word2vec训练向量。

from gensim.test.utils import common_texts
from gensim.models import Word2Vec

model = Word2Vec(common_texts, size=100, window=5, min_count=1, workers=4)
word_vectors = model.wv

从磁盘加载词向量文件

from gensim.models import KeyedVectors

word_vectors.save("vectors_wv")
word_vectors = KeyedVectors.load("vectors_wv", mmap='r')

从磁盘加载原始Google’s word2vec C格式的词向量文件作为KeyedVectors实例

wv_from_text = KeyedVectors.load_word2vec_format(datapath('word2vec_pre_kv_c'), binary=False)  # C text format
wv_from_bin = KeyedVectors.load_word2vec_format(datapath('word2vec_vector.bin'), binary=True)  # C text format

3、使用这些词向量可以做什么?

可以执行各种NLP语法/语义的单词任务。

>>> import gensim.downloader as api
>>>
>>> word_vectors = api.load("glove-wiki-gigaword-100")  # load pre-trained word-vectors from gensim-data
>>>
>>> result = word_vectors.most_similar(positive=['woman', 'king'], negative=['man'])
>>> print("{}: {:.4f}".format(*result[0]))
queen: 0.7699

>>> result = word_vectors.most_similar_cosmul(positive=['woman', 'king'], negative=['man'])
>>> print("{}: {:.4f}".format(*result[0]))
queen: 0.8965
>>>
>>> print(word_vectors.doesnt_match("breakfast cereal dinner lunch".split()))
cereal
# 两个单词的相似度
>>> similarity = word_vectors.similarity('woman', 'man')
>>> similarity > 0.8
True
# 与指定单词最相近的词列表
>>> result = word_vectors.similar_by_word("cat")
>>> print("{}: {:.4f}".format(*result[0]))
dog: 0.8798
>>>
>>> sentence_obama = 'Obama speaks to the media in Illinois'.lower().split()
>>> sentence_president = 'The president greets the press in Chicago'.lower().split()
# 两句话的WMD距离
>>> similarity = word_vectors.wmdistance(sentence_obama, sentence_president)
>>> print("{:.4f}".format(similarity))
3.4893
# 两个单词的距离
>>> distance = word_vectors.distance("media", "media")
>>> print("{:.1f}".format(distance))
0.0
# 两个句子相似度
>>> sim = word_vectors.n_similarity(['sushi', 'shop'], ['japanese', 'restaurant'])
>>> print("{:.4f}".format(sim))
0.7067
# 词向量
>>> vector = word_vectors['computer']  # numpy vector of a word
>>> vector.shape
(100,)
>>>
>>> vector = word_vectors.wv.word_vec('office', use_norm=True)
>>> vector.shape
(100,)
  • 5
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值