第一部分:论文
最近读了一遍Doc2Vec原文,整篇文章思路清晰明了,建议在读博客之前先看一遍文章,因为文章中将各个部分讲的很详细。
这里只记录文章中最最重要的一段话:
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.
即带优化的推断,所有同一个训练好的模型每次得到的文档向量可能是不同的~
第二部分: 实战
doc2vec的输入是TaggedDocument向量,它包括word_list和tags两部分,word_list是文档的分词列表,如['火箭','是','总冠军',]。tags是文档的标签列表。
创建TaggedDocument对象:
document = TaggedDocdument(word_list,tags=label)
模型参数说明:
1.dm=1 PV-DM dm=0 PV-DBOW。
2.size 所得向量的维度。
3.window 上下文词语离当前词语的最大距离。
4.alpha 初始学习率,在训练中会下降到min_alpha。
5.min_count 词频小于min_count的词会被忽略。
6.max_vocab_size 最大词汇表size,每一百万词会需要1GB的内存,默认没有限制。
7.sample 下采样比例。
8.iter 在整个语料上的迭代次数(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训练词向量,0只训练doc向量。
定义模型:
model = Doc2Vec(dm=1, min_count=1, window=3, size=size, sample=1e-3, negative=5)
训练模型:
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]得到已训练文档的向量。
得到与输入文档相似度最高的十个文档:
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