官網: 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,)
複製代碼