Doc2vec论文阅读及源码理解

article/2025/8/23 16:21:50

《Distributed representationss of Sentences and Documents》

Quoc Le and Tomas Mikolov, 2014

文章目录

  • 《Distributed representationss of Sentences and Documents》
      • 1. Distributed Memory Model of Paragraph Vectors (PV-DM).
        • 1.1 模型架构图
        • 1.2 相关代码阅读
      • 2. Distributed Bag ofWords version of Paragraph Vector (PV-DBOW)
        • 2.1 模型架构图
        • 2.2 相关代码理解
      • 3. Doc2vec的预测过程
        • 3.1 预测原理
        • 3.2 相关代码阅读

1. Distributed Memory Model of Paragraph Vectors (PV-DM).

1.1 模型架构图

有点类似word2vec中的CBOW模型,根据上下文预测当前词。
在这里插入图片描述

在PV-DM模型中,矩阵 W W W为词向量矩阵,矩阵 D D D为段落向量矩阵。

每一个段落被映射为矩阵 D D D中的一个唯一的向量,每个单词同样被映射为矩阵 W W W中的一个唯一向量。

paragraph向量和词向量通过取平均(average)或者连接(concatenate)的方法结合,预测目标词向量。

这里的context上下文是从当前段落中的滑动窗口内采样得到的固定长度的(代码中应该是通过reduced_window来实现采样的,见下面代码阅读),段落向量只在同一个paragraph中共享,词向量在paragraph之间共享。

1.2 相关代码阅读

gensim3.8.0中Doc2vec-DM模型相关代码阅读如下(如果之前学习过Word2vec的源码,那么对doc2vec源码的理解会更加容易一些)

  • 通过average计算上下文向量
    def train_document_dm(model, doc_words, doctag_indexes, alpha, work=None, neu1=None,learn_doctags=True, learn_words=True, learn_hidden=True,word_vectors=None, word_locks=None, doctag_vectors=None, doctag_locks=None):"""Update distributed memory model ("PV-DM") by training on a single document.使用一篇doc对PV-DM模型进行更新Called internally from :meth:`~gensim.models.doc2vec.Doc2Vec.train` and:meth:`~gensim.models.doc2vec.Doc2Vec.infer_vector`. This method implementsthe DM model with a projection (input) layer that is either the sum or mean ofthe context vectors, depending on the model's `dm_mean` configuration field.Notes-----This is the non-optimized, Python version. If you have cython installed, gensimwill use the optimized version from :mod:`gensim.models.doc2vec_inner` instead.Parameters----------model : :class:`~gensim.models.doc2vec.Doc2Vec`The model to train.doc_words : list of strThe input document as a list of words to be used for training. Each word will be looked up inthe model's vocabulary.doctag_indexes : list of intIndices into `doctag_vectors` used to obtain the tags of the document.alpha : floatLearning rate.work : objectUNUSED.neu1 : objectUNUSED.learn_doctags : bool, optionalWhether the tag vectors should be updated.learn_words : bool, optionalWord vectors will be updated exactly as per Word2Vec skip-gram training only if **both**`learn_words` and `train_words` are set to True.learn_hidden : bool, optionalWhether or not the weights of the hidden layer will be updated.word_vectors : iterable of list of float, optionalVector representations of each word in the model's vocabulary.word_locks : list of float, optionalLock factors for each word in the vocabulary.doctag_vectors : list of list of float, optionalVector representations of the tags. If None, these will be retrieved from the model.doctag_locks : list of float, optionalThe lock factors for each tag.Returns-------intNumber of words in the input document that were actually used for training (they were found in thevocabulary and they were not discarded by negative sampling)."""# 获取模型中的词向量if word_vectors is None:word_vectors = model.wv.syn0if word_locks is None:word_locks = model.syn0_lockf# 获取模型中的doc向量if doctag_vectors is None:doctag_vectors = model.docvecs.doctag_syn0if doctag_locks is None:doctag_locks = model.docvecs.doctag_syn0_lockf# 当前段落中词的词表信息(该词必须存在于词表中)word_vocabs = [model.wv.vocab[w] for w in doc_words if w in model.wv.vocaband model.wv.vocab[w].sample_int > model.random.rand() * 2 ** 32]# 遍历每一个词for pos, word in enumerate(word_vocabs):# 对窗口进行reducereduced_window = model.random.randint(model.window)  # `b` in the original doc2vec code# 计算窗口的起止位置start = max(0, pos - model.window + reduced_window)window_pos = enumerate(word_vocabs[start:(pos + model.window + 1 - reduced_window)], start)# 获取窗口内,除预测目标词之外,其他上下文词的idword2_indexes = [word2.index for pos2, word2 in window_pos if pos2 != pos]# 将词向量和doc向量求和成为上下文向量l1 = np_sum(word_vectors[word2_indexes], axis=0) + np_sum(doctag_vectors[doctag_indexes], axis=0)# 计算求和的向量总数count = len(word2_indexes) + len(doctag_indexes)# 这里是取向量求和之后的均值if model.cbow_mean and count > 1:l1 /= count# 计算更新的梯度,这里是复用了word2vec模型中train_cbow_pair的方法# 设置learn_vectors=False,表示不在train_cbow_pair方法内更新上下文向量# 而是获取到计算的梯度之后在本方法内更新neu1e = train_cbow_pair(model, word, word2_indexes, l1, alpha,learn_vectors=False, learn_hidden=learn_hidden)# 如果当前的方法不是取平均,说明计算的梯度是所有向量的共同梯度# 则要对梯度取平均if not model.cbow_mean and count > 1:neu1e /= count# 更新doc的向量if learn_doctags:for i in doctag_indexes:doctag_vectors[i] += neu1e * doctag_locks[i]# 更新词向量if learn_words:for i in word2_indexes:word_vectors[i] += neu1e * word_locks[i]return len(word_vocabs)
  • 通过concatenate计算上下文向量

2. Distributed Bag ofWords version of Paragraph Vector (PV-DBOW)

2.1 模型架构图

有点类似word2vec中的Skip-gram模型,根据paragraph向量来预测窗口内的词向量。在这里插入图片描述

2.2 相关代码理解

    def train_document_dbow(model, doc_words, doctag_indexes, alpha, work=None,train_words=False, learn_doctags=True, learn_words=True, learn_hidden=True,word_vectors=None, word_locks=None, doctag_vectors=None, doctag_locks=None):"""Update distributed bag of words model ("PV-DBOW") by training on a single document.Called internally from :meth:`~gensim.models.doc2vec.Doc2Vec.train` and:meth:`~gensim.models.doc2vec.Doc2Vec.infer_vector`.Notes-----This is the non-optimized, Python version. If you have cython installed, gensimwill use the optimized version from :mod:`gensim.models.doc2vec_inner` instead.Parameters----------model : :class:`~gensim.models.doc2vec.Doc2Vec`The model to train.doc_words : list of strThe input document as a list of words to be used for training. Each word will be looked up inthe model's vocabulary.doctag_indexes : list of intIndices into `doctag_vectors` used to obtain the tags of the document.alpha : floatLearning rate.work : np.ndarrayPrivate working memory for each worker.train_words : bool, optionalWord vectors will be updated exactly as per Word2Vec skip-gram training only if **both**`learn_words` and `train_words` are set to True.learn_doctags : bool, optionalWhether the tag vectors should be updated.learn_words : bool, optionalWord vectors will be updated exactly as per Word2Vec skip-gram training only if **both**`learn_words` and `train_words` are set to True.learn_hidden : bool, optionalWhether or not the weights of the hidden layer will be updated.word_vectors : object, optionalUNUSED.word_locks : object, optionalUNUSED.doctag_vectors : list of list of float, optionalVector representations of the tags. If None, these will be retrieved from the model.doctag_locks : list of float, optionalThe lock factors for each tag.Returns-------intNumber of words in the input document."""# doctag_vectors是否为空的判断,是为了区分当前是训练模式还是预测模式# 为空表示训练过程,从模型中直接读入# 不为空是预测过程,会预先生成一个随机向量传入if doctag_vectors is None:doctag_vectors = model.docvecs.doctag_syn0if doctag_locks is None:doctag_locks = model.docvecs.doctag_syn0_lockf# 这里复用的是word2vec中train_batch_sg方法,原理是通过当前词来预测上下文# 但是对于Docvec模型来说,当前词就是当前的paragraph vector,上下文就是段落中的每一个词# 因此context_vectors指定为当前的paragraph vectorif train_words and learn_words:train_batch_sg(model, [doc_words], alpha, work)for doctag_index in doctag_indexes:for word in doc_words:train_sg_pair(model, word, doctag_index, alpha, learn_vectors=learn_doctags, learn_hidden=learn_hidden,context_vectors=doctag_vectors, context_locks=doctag_locks)return len(doc_words)

3. Doc2vec的预测过程

3.1 预测原理

先给新的doc分配一个随机的向量,根据指定的模型,使用固定词向量和隐藏单元的向量不更新,

3.2 相关代码阅读

    def infer_vector(self, doc_words, alpha=None, min_alpha=None, epochs=None, steps=None):"""Infer a vector for given post-bulk training document.Notes-----Subsequent calls to this function may infer different representations for the same document.For a more stable representation, increase the number of steps to assert a stricket convergence.Parameters----------doc_words : list of strA document for which the vector representation will be inferred.预测的doc,是一个string类型的listalpha : float, optionalThe initial learning rate. If unspecified, value from model initialization will be reused.min_alpha : float, optionalLearning rate will linearly drop to `min_alpha` over all inference epochs. If unspecified,value from model initialization will be reused.epochs : int, optionalNumber of times to train the new document. Larger values take more time, but may improvequality and run-to-run stability of inferred vectors. If unspecified, the `epochs` valuefrom model initialization will be reused.steps : int, optional, deprecatedPrevious name for `epochs`, still available for now for backward compatibility: if`epochs` is unspecified but `steps` is, the `steps` value will be used.Returns-------np.ndarrayThe inferred paragraph vector for the new document."""if isinstance(doc_words, string_types):raise TypeError("Parameter doc_words of infer_vector() must be a list of strings (not a single string).")alpha = alpha or self.alphamin_alpha = min_alpha or self.min_alphaepochs = epochs or steps or self.epochs# 给一个新的doc生成一个随机的向量doctag_vectors, doctag_locks = self.trainables.get_doctag_trainables(doc_words, self.docvecs.vector_size)doctag_indexes = [0]work = zeros(self.trainables.layer1_size, dtype=REAL)if not self.sg:neu1 = matutils.zeros_aligned(self.trainables.layer1_size, dtype=REAL)alpha_delta = (alpha - min_alpha) / max(epochs - 1, 1)# 根据参数选择对应的模型:DM/DM-CONCAT/DBOWfor i in range(epochs):# 预测的过程中,固定词向量和隐藏单元不更新,只更新doc的向量:doctag_vectorsif self.sg:train_document_dbow(self, doc_words, doctag_indexes, alpha, work,learn_words=False, learn_hidden=False, doctag_vectors=doctag_vectors, doctag_locks=doctag_locks)# neu1参数目前是没有用的:unusedelif self.dm_concat:train_document_dm_concat(self, doc_words, doctag_indexes, alpha, work, neu1,learn_words=False, learn_hidden=False, doctag_vectors=doctag_vectors, doctag_locks=doctag_locks)else:train_document_dm(self, doc_words, doctag_indexes, alpha, work, neu1,learn_words=False, learn_hidden=False, doctag_vectors=doctag_vectors, doctag_locks=doctag_locks)alpha -= alpha_delta# 返回更新完成的paragraph vectorreturn doctag_vectors[0]

http://chatgpt.dhexx.cn/article/uVBF4KW4.shtml

相关文章

doc2vec介绍和实践

简介 与其他方法的比较 bag of words (BOW):不会考虑词语出现的先后顺序。 Latent Dirichlet Allocation (LDA):更偏向于从文中提取关键词和核心思想extracting topics/keywords out of texts,但是非常难调参数并且难以评价模型的好坏。 …

doc2vec java_word2vec和doc2vec

word2vec基本思想 通过训练每个词映射成k维实数向量(k一般为模型中的超参数),通过词之间的距离来判断语义相似度。 word2vec采用一个三层的神经网络。 训练的时候按照词频将每个词语Huffman编码,词频越高的词语对应的编码越短。这三层的神经网络本身是对…

Doc2vec

目录 一:背景 二:基本原理 2.1:PV-DM 2.2:PV-DBOW 2.3:和word2vec区别 2.4:预测新文本的向量 三:代码实战 3.1:接口介绍 3.2:主要代码 一:背景 之前总结了Word2vec训练词向量的细节,讲解了一个词是如何通过wor…

关于doc2vec

原文地址:https://blog.csdn.net/john_xyz/article/details/79208564 1.“句向量”简介 word2vec提供了高质量的词向量,并在一些任务中表现良好。 关于word2vec的原理可以参考这几篇论文: https://arxiv.org/pdf/1310.4546.pdfhttps://arx…

doc2vec java_doc2vec

gensim 是处理文本的很强大的工具包,基于python环境下: 1.gensim可以做什么? 它可以完成的任务,参加gensim 主页API中给出的介绍,链接如下: http://radimrehurek.com/gensim/apiref.html 2.word2vec的使用 …

Doc2Vec的简介及应用(gensim)

作者:Gidi Shperber 在本文中,你将学习什么是doc2vec,它是如何构建的,它与word2vec有什么关系,你能用它做什么,并且没有复杂的数学公式。 介绍 文本文档的量化表示在机器学习中是一项具有挑战性的任务。很多应用都…

Doc2Vec模型介绍及使用

Doc2Vec模型 Doc2Vec模型 摘要背景段落向量 PV-DM模型PV-DBOW模型gensim实现Doc2Vec说明参考文献摘要 通过本文,你将了解到: Doc2Vec模型是如何产生的Doc2Vec模型细节Doc2Vec模型的特点Doc2Vec的使用及代码(gensim)背景 Doc2Vec模型的产生要从词向量表示(论文word2vec模型)开…

Doc2Vec - 计算文档之间的相似性

本文旨在向您介绍 Doc2Vec 模型,以及它在计算文档之间的相似性时如何提供帮助。 目录 前言 一、Word2Vec 1.Skip-Gram 2.Continuous Bag-of-Words (CBOW) 二、Doc2Vec 1.Distributed Memory version of Paragraph Vector (PV-DM) 2.Words version of Paragra…

Doc2Vec模型的介绍与gensim中Doc2Vec的使用

文章目录 一、Doc2Vec模型1 、PV-DM2 、PV-DBOW 二、gensim实现1、gensim实现Doc2Vec(IMDB数据集)2、gensim实现Doc2Vec(中文数据集) 三、总结四、程序编写时遇到的错误:gensim包中相关函数说明: 参考资料&…

如何自学游戏引擎的开发?

PS:题猪分得清游戏和游戏引擎的区别,所以各位答主不需要劳神解释两者的区别关系什么的了 PS:这里的游戏引擎暂时指图形模块,其他的声音,物理,网络,UI等等模块暂时不考虑 题猪一直自学编程&#…

游戏开发完整学习路线(各个版本都有)

来自:微浪科技 作者:若朝若曦 在软件开发中,游戏开发这个方向看起来目标很明确,但其实是个领域很广的方向,入门的时候如果得不到指点一二,很容易误入歧途,相反,如果走这条路之前能…

智力开发小游戏集含游戏过程中数据存取-C#入门教学程序

对于初学C#程序开发的学员,一般进行采取开发小游戏程序,这样做首先不会让学员失去学习的兴趣,其次可以将C#中基本的控件与类的写法整合到这些游戏程序中,再次将对数据库的操作也教给学员。通过几年的观察这样的教学有它的好处。所…

游戏开发所需要的知识

从放弃求职回家已经一个半月了,一直都在备考事业编。发现这玩意比游戏开发简单太多了,没有人刁难,没有人催促,几个月举办一次,一天只需要学习3-4个小时,其余时间都是自由安排,太舒服了。考上编后…

零基础游戏开发笔记1——游戏开发流程

万事开头难,多学多练习,熟悉游戏开发的主要流程,莫要强行记忆。 首先,我们来了解一下游戏的开发流程。 第一就是立案,建立策划案。 策划案包含很多东西,包括游戏介绍、游戏内容、游戏模型介绍、游戏数值、…

游戏开发流程之完整指南

“现在,是时候改进您的游戏开发流程了。在这里,无论您是在独立的初创公司亦或大型游戏工作室中,我们都可以调度资源,使您的工作室的开发和设计工作晋升一个层次。” 您可以把本指引当做游戏开发流程改进的参考 我们将覆盖所有您…

游戏开发笔记(二)——开发流程和项目管理

前一篇说到分工,这里再说说流程和开发管理。 组织形式 从公司角度来看一个游戏工作室是一个业务比较独立的研发部门,研发方面的大小事务(除了立项)拥有高度自治权。而从一个工作室角度来看,通常内部又由多个项目组组成…

游戏开发 - 开发流程 - 收集

1.应用场景 主要用于了解,掌握游戏开发的整个流程。 2.学习/操作 1.文档阅读 复习课 | 带你梳理客户端开发的三个重点-极客时间 2.整理输出 2.1 游戏开发流程 -- 参考 按照游戏开发中的三大模块策划、程序、美术,画了一个图。 开发游戏的时候&#xf…

游戏开发完整流程

1. 立项 一个项目立项的原因可能性非常多,有可能是公司拿到一个好的IP,也有可能是几个负责人有个很棒的idea,亦或是老板的梦想是做一个XX类型的游戏,这边不做过多的讨论。 立项过程中应该包含市场调查和产品定位&#xff0c…

如何开发一款游戏?【游戏开发所需技能和开发流程】

开发一款游戏需要的技能包括:编程、设计、音效和项目管理。每个角色都需要掌握其特定领域的知识和技能,并与其他团队成员合作。在本文中,我们将深入探讨如何开发一款游戏。 1. 游戏开发流程 游戏开发流程可以分为以下几个阶段: …

如何开发一款游戏:游戏开发流程及所需工具

本文来自作者 goto先生 在 GitChat 上分享 「如何开发一款游戏:游戏开发流程及所需工具」 编辑 | 哈比 游戏作为娱乐生活的一个方面,参与其中的人越来越多,而大部分参与其中的人都是以玩家的身份。 他们热爱一款游戏,或是被游戏的…