第一部分:論文
最近讀了一遍Doc2Vec原文,整篇文章思路清晰明了,建議在讀博客之前先看一遍文章,因?yàn)槲恼轮袑⒏鱾€(gè)部分講的很詳細(xì)。
這里只記錄文章中最最重要的一段話:
At prediction time, one needs to perform an inference step to compute the paragraph vector for a new paragraph. This
is also obtained by gradient descent. In this step, the parameters for the rest of the model, the word vectors W and the softmax weights, are fixed.
即帶優(yōu)化的推斷,所有同一個(gè)訓(xùn)練好的模型每次得到的文檔向量可能是不同的~
第二部分: 實(shí)戰(zhàn)
doc2vec的輸入是TaggedDocument向量,它包括word_list和tags兩部分,word_list是文檔的分詞列表,如['火箭','是','總冠軍',]。tags是文檔的標(biāo)簽列表。
?? 創(chuàng)建TaggedDocument對象:
document = TaggedDocdument(word_list,tags=label)
模型參數(shù)說明:
1.dm=1 PV-DM? dm=0 PV-DBOW。
2.size 所得向量的維度。
3.window 上下文詞語離當(dāng)前詞語的最大距離。
4.alpha 初始學(xué)習(xí)率,在訓(xùn)練中會下降到min_alpha。
5.min_count 詞頻小于min_count的詞會被忽略。
6.max_vocab_size 最大詞匯表size,每一百萬詞會需要1GB的內(nèi)存,默認(rèn)沒有限制。
7.sample 下采樣比例。
8.iter 在整個(gè)語料上的迭代次數(shù)(epochs),推薦10到20。
9.hs=1 hierarchical softmax ,hs=0(default) negative sampling。
10.dm_mean=0(default) 上下文向量取綜合,dm_mean=1 上下文向量取均值。
11.dbow_words:1訓(xùn)練詞向量,0只訓(xùn)練doc向量。
定義模型:
model = Doc2Vec(dm=1, min_count=1, window=3, size=size, sample=1e-3, negative=5)?
?? 訓(xùn)練模型:
model.train(x_train, total_examples=model_dm.corpus_count, epochs=epoch_num)?
保存模型:
model.save('model/model_my.model')
使用infer_vector來推理文檔的向量?(輸入text仍然是文檔的分詞列表):
vector = model.infer_vector(text)?
使用model.docvecs[tag]得到已訓(xùn)練文檔的向量。
得到與輸入文檔相似度最高的十個(gè)文檔:
sims = model.docvecs.most_similar([vector], topn=10)
參考:
https://arxiv.org/pdf/1405.4053.pdf
https://blog.csdn.net/weixin_39837402/article/details/80254868
https://radimrehurek.com/gensim/models/doc2vec.html