【问题标题】:Gensim Doc2Vec model only generates a limited number of vectorsGensim Doc2Vec 模型只生成有限数量的向量
【发布时间】:2023-12-02 18:31:01
【问题描述】:

我正在使用 gensim Doc2Vec 模型来生成我的特征向量。这是我正在使用的代码(我已经在代码中解释了我的问题):

cores = multiprocessing.cpu_count()

# creating a list of tagged documents
training_docs = []

# all_docs: a list of 53 strings which are my documents and are very long (not just a couple of sentences)
for index, doc in enumerate(all_docs):
    # 'doc' is in unicode format and I have already preprocessed it
    training_docs.append(TaggedDocument(doc.split(), str(index+1)))

# at this point, I have 53 strings in my 'training_docs' list 

model = Doc2Vec(training_docs, size=400, window=8, min_count=1, workers=cores)

# now that I print the vectors, I only have 10 vectors while I should have 53 vectors for the 53 documents that I have in my training_docs list.
print(len(model.docvecs))
# output: 10

我只是想知道我是否做错了,或者我是否应该设置任何其他参数?

UPDATE:我在玩 TaggedDocument 中的 tags 参数,当我将其更改为文本和数字的混合时,例如:Doc1、Doc2、... 我看到生成向量的数量不同,但我仍然没有相同数量的符合预期的特征向量。

【问题讨论】:

    标签: python nlp gensim doc2vec


    【解决方案1】:

    查看它在您的语料库中发现的实际标签:

    print(model.docvecs.offset2doctag)
    

    你看到模式了吗?

    每个文档的tags 属性应该是一个标签列表,而不是单个标签。如果您提供一个简单的整数字符串,它会将其视为数字列表,因此只学习标签'0''1'、...、'9'

    您可以将str(index+1) 替换为[str(index+1)] 并获得您期望的行为。

    但是,由于您的文档 ID 只是升序整数,您也可以只使用纯 Python 整数作为您的文档标签。这将节省一些内存,避免创建从字符串标签到数组槽(int)的查找字典。为此,请将str(index+1) 替换为[index]。 (这会从 0 开始 doc-ID——这有点像 Pythonic,也避免了在保存训练向量的原始数组中浪费未使用的 0 位置。)

    【讨论】: