官网: gensim: Topic modelling for humanshtml
Gensim
是一款开源的第三方Python工具包,用于从原始的非结构化的文本中,无监督地学习到文本隐层的主题向量表达。支持包括TF-IDF
, LSA
, LDA
, Word2Vec
在内的多种主题模型算法,支持分布式训练,提供了类似度计算、信息检索等一些经常使用的API接口。算法
上述算法是无监督的,意味着不须要人工输入,只须要一个纯文本语料库。api
特色数组
Word2Vec
, Doc2Vec
, FastText
, TF-IDF
,潜在语义分析(LSI
, LSA
等),LDA
等。设计目标分布式
注意区分:保存与加载模型,仍是保存与加载词向量文件ide
- 模型的保存与加载:保留了模型训练的全部状态信息,如权重文件,二叉树和词汇频率等,加载后能够进行
再/追加训练
- 词向量文件的保存与加载:丢弃了模型训练的状态信息,加载后不能够进行
再/追加训练
具体的API可参考:gensim: API Reference工具
使用model.save()
方法, 以该方式保存的模型能够在读取后进行再训练(追加训练),由于保存了训练的所有信息学习
from gensim.models import Word2Vec
# 训练Word2Vec向量
model = Word2Vec(texts, size=100, window=5, min_count=1, workers=4)
# 保存模型
model.save("word2vec.model")
复制代码
若是须要继续训练,须要完整的Word2Vec
对象状态,由save()
存储,而不单单是KeyedVectors
。spa
使用load
方式加载模型,能够进行再训练设计
from gensim.models import Word2Vec
model = Word2Vec.load("word2vec.model")
model.train([["hello", "world"]], total_examples=1, epochs=1)
复制代码
训练后的词向量可使用model.wv
保存在一个KeyedVectors
实例中,以下:
vector = model.wv['computer'] # numpy vector of a word
复制代码
若是已经完成模型的训练(即再也不进行模型的更新,仅仅是查询),则可切换到KeyedVectors
实例:
word_vectors = model.wv
del model
复制代码
保存训练好的词向量文件
mdoel.wv.save
以KededVectors
实例的形式保存词向量文件,以该方式保存的模型丢失了完整的模型状态,没法再训练,保存的对象更小更快。model.wv.save("model.wv")
复制代码
wv.save_word2vec_format
保存词向量文件(以前是model.save_word2vec_format()
,已弃用)model.wv.save_word2vec_format("model.bin", binary=True)
复制代码
KeyedVectors.load
加载词向量文件,保存在KeyedVectors
实例中(适用于不须要完整的模型状态,再也不进行训练)from gensim.models import KeyedVectors
wv = KeyedVectors.load("model.wv", mmap='r')
vector = wv['computer'] # numpy vector of a word
复制代码
word2vec C format
加载词向量,保存在KeyedVectors
实例中 使用KeyedVector.load_word2vec_format()
能够加载两种格式的词向量文件:C 文本格式和C bin格式(二进制)from gensim.models import KeyedVectors
wv_from_text = KeyedVectors.load_word2vec_format("model_kv_c", binary=False) # C text format
wv_from_bin = KeyedVectors.load_word2vec_format("model_kv.bin", binary=True) # C bin format
复制代码
因为权重文件,二叉树和词汇频率的缺失,没法从C格式加载的向量继续训练。
models.keyedVectors
模块实现了词向量及其类似性查找。训练好的此线路与训练方式无关,所以他们能够由独立结构表示。
该结构称为KeyedVectors
,实质上是实体和向量之间的映射。每一个实体由其字符串id标识,所以是字符串和1维数组之间的映射关系。 实体一般对应一个单词,所以是将单词映射到一维向量,对于某些某些,值也能够对应一篇文档,一个图像或其余。
KeyedVectors
和完整模型的区别在于没法进一步的训练,及更小的RAM占用,更简单的接口。
训练一个完整的模型,而后获取它的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
复制代码
能够执行各类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,)
复制代码