【问题标题】:How to use TaggedDocument in gensim?如何在 gensim 中使用 TaggedDocument?
【发布时间】:2017-12-20 21:39:38
【问题描述】:

我有两个目录,我想从中读取它们的文本文件并标记它们,但我不知道如何通过TaggedDocument 执行此操作。我认为它可以作为 TaggedDocument([Strings],[Labels]) 工作,但这显然不起作用。

这是我的代码:

from gensim import models
from gensim.models.doc2vec import TaggedDocument
import utilities as util
import os
from sklearn import svm
from nltk.tokenize import sent_tokenize
CogPath = "./FixedCog/"
NotCogPath = "./FixedNotCog/"
SamplePath ="./Sample/"
docs = []
tags = []
CogList = [p for p in os.listdir(CogPath) if p.endswith('.txt')]
NotCogList = [p for p in os.listdir(NotCogPath) if p.endswith('.txt')]
SampleList = [p for p in os.listdir(SamplePath) if p.endswith('.txt')]
for doc in CogList:
     str = open(CogPath+doc,'r').read().decode("utf-8")
     docs.append(str)
     print docs
     tags.append(doc)
     print "###########"
     print tags
     print "!!!!!!!!!!!"
for doc in NotCogList:
     str = open(NotCogPath+doc,'r').read().decode("utf-8")
     docs.append(str)
     tags.append(doc)
for doc in SampleList:
     str = open(SamplePath + doc, 'r').read().decode("utf-8")
     docs.append(str)
     tags.append(doc)

T = TaggedDocument(docs,tags)

model = models.Doc2Vec(T,alpha=.025, min_alpha=.025, min_count=1,size=50)

这是我得到的错误:

Traceback (most recent call last):
  File "/home/farhood/PycharmProjects/word2vec_prj/doc2vec.py", line 34, in <module>
    model = models.Doc2Vec(T,alpha=.025, min_alpha=.025, min_count=1,size=50)
  File "/home/farhood/anaconda2/lib/python2.7/site-packages/gensim/models/doc2vec.py", line 635, in __init__
    self.build_vocab(documents, trim_rule=trim_rule)
  File "/home/farhood/anaconda2/lib/python2.7/site-packages/gensim/models/word2vec.py", line 544, in build_vocab
    self.scan_vocab(sentences, progress_per=progress_per, trim_rule=trim_rule)  # initial survey
  File "/home/farhood/anaconda2/lib/python2.7/site-packages/gensim/models/doc2vec.py", line 674, in scan_vocab
    if isinstance(document.words, string_types):
AttributeError: 'list' object has no attribute 'words'

【问题讨论】:

  • 与您的主要问题分开:使结尾min_alpha 与开头alpha 具有相同的值意味着您的训练没有进行适当的随机梯度下降。此外,min_count=1 很少对 Word2Vec/Doc2Vec 训练有帮助 - 保留这些稀有词只会使训练花费更长的时间并干扰剩余 word-vecs/doc-vecs 的质量。
  • 关于min_alpha,我从一个示例代码中复制了它,然后是这个代码:for epoch in range(10): model.train(docs) model.alpha -= 0.002 # decrease the learning rate model.min_alpha = model.alpha # fix the learning rate, no decay 和关于min_count:我的数据集非常有限,有些词不是那么多频繁但意义重大,我也过滤了大多数停用词和日常常用词。
  • 这是一个不好的样本。如果您在创建 Doc2Vec 实例时传入您的语料库,它将自动完成所有训练过程,并自动管理从 alphamin_alpha 的学习率,并且您不应该自己调用 train()。 (如果你这样做了,就像你在没有任何其他细节的情况下展示的那样,最新的 gensim 版本会抛出一个错误,因为这是一个非常常见的错误。)你自己或默认调用 train() 是罕见的,专家级的事情alpha/min_alpha.

标签: python nltk gensim word2vec doc2vec


【解决方案1】:

Doc2Vec 模型的输入应该是 TaggedDocument(['list','of','word'], [TAG_001]) 的列表。一个好的做法是使用句子的索引作为标签。 例如,用两个句子(即文档、段落)训练一个 Doc2Vec 模型:

s1 = 'the quick fox brown fox jumps over the lazy dog'
s1_tag = '001'
s2 = 'i want to burn a zero-day'
s2_tag = '002'

docs = []
docs.append(TaggedDocument(words=s1.split(), tags=[s1_tag])
docs.append(TaggedDocument(words=s2.split(), tags=[s2_tag])

model = gensim.models.Doc2Vec(vector_size=300, window=5, min_count=5, workers=4, epochs=20)
model.build_vocab(docs)

print 'Start training process...'
model.train(docs, total_examples=model.corpus_count, epochs=model.iter)

#save model
model.save(model_path)

【讨论】:

    【解决方案2】:

    所以我只是试验了一下,在github上找到了这个:

    class TaggedDocument(namedtuple('TaggedDocument', 'words tags')):
        """
        A single document, made up of `words` (a list of unicode string tokens)
        and `tags` (a list of tokens). Tags may be one or more unicode string
        tokens, but typical practice (which will also be most memory-efficient) is
        for the tags list to include a unique integer id as the only tag.
    
        Replaces "sentence as a list of words" from Word2Vec.
    

    所以我决定通过为每个文档生成一个 TaggedDocument 类来更改我使用 TaggedDocument 函数的方式,重要的是您必须将标签作为列表传递。

    for doc in CogList:
         str = open(CogPath+doc,'r').read().decode("utf-8")
         str_list = str.split()
         T = TaggedDocument(str_list,[doc])
         docs.append(T)
    

    【讨论】:

    • 是的:Doc2Vec 期望语料库是一个可迭代的集合,其中每个单独的项目(文档)的形状都像 TaggedDocument。 (也就是说,它有一个words 列表和tags 列表。)
    【解决方案3】:

    可以使用gensim的common_texts为例:

    from gensim.test.utils import common_texts
    from gensim.models.doc2vec import Doc2Vec, TaggedDocument
    
    documents = [TaggedDocument(doc, [i]) for i, doc in enumerate(common_texts)]
    model = Doc2Vec(documents, vector_size=5, window=2, min_count=1, workers=4)
    

    这将使用 common_texts 和 TaggedDocument 来创建 Doc2Vec 算法所期望的文档表示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-02
      • 1970-01-01
      • 2017-12-16
      • 1970-01-01
      • 1970-01-01
      • 2017-04-19
      • 2018-12-31
      • 2016-08-03
      相关资源
      最近更新 更多