【问题标题】:Topic wise document distribution in Gensim LDAGensim LDA 中的主题文档分发
【发布时间】:2020-12-25 20:20:23
【问题描述】:

python 中有没有办法映射属于某个主题的文档。例如,主要是“主题 0”的文档列表。我知道有一些方法可以列出每个文档的主题,但我该如何做呢?

编辑:

我正在为 LDA 使用以下脚本:

    doc_set = []
    for file in files:
        newpath = (os.path.join(my_path, file)) 
        newpath1 = textract.process(newpath)
        newpath2 = newpath1.decode("utf-8")
        doc_set.append(newpath2)

    texts = []
    for i in doc_set:
        raw = i.lower()
        tokens = tokenizer.tokenize(raw)
        stopped_tokens = [i for i in tokens if not i in stopwords.words()]
        stemmed_tokens = [p_stemmer.stem(i) for i in stopped_tokens]
        texts.append(stemmed_tokens)

    dictionary = corpora.Dictionary(texts)
    corpus = [dictionary.doc2bow(text) for text in texts]
    ldamodel = gensim.models.ldamodel.LdaModel(corpus, num_topics=2, random_state=0, id2word = dictionary, passes=1)

【问题讨论】:

标签: python gensim lda


【解决方案1】:

你有一个工具/API (Gensim LDA),当给你一个文档时,它会给你一个主题列表。

但你想要相反:一个主题的文档列表。

基本上,您需要自己构建反向映射。

幸运的是,Python 用于处理映射的本机 dicts 和 idioms 使这非常简单 - 只需几行代码 - 只要您处理完全适合内存的数据。

大致的方法是:

  • 创建一个新结构(dictlist)用于将主题映射到文档列表
  • 遍历所有文档,将它们(可能带有分数)添加到主题到文档的映射中
  • 最后,针对每个感兴趣的主题查找(或许还可以排序)这些文档列表

如果可以编辑您的问题以包含有关文档/主题的格式/ID 以及您如何训练 LDA 模型的更多信息,则可以使用更具体的示例代码扩展此答案以构建反向-您需要的映射。

代码更新更新:

好的,如果您的模型在 ldamodel 中并且您的 BOW 格式的文档在 corpus 中,您可以执行以下操作:

# setup: get the model's topics in their native ordering...
all_topics = ldamodel.print_topics()
# ...then create a empty list per topic to collect the docs:
docs_per_topic = [[] for _ in all_topics]

# now, for every doc...
for doc_id, doc_bow in enumerate(corpus):
    # ...get its topics...
    doc_topics = ldamodel.get_document_topics(doc_bow)
    # ...& for each of its topics...
    for topic_id, score in doc_topics:
        # ...add the doc_id & its score to the topic's doc list
        docs_per_topic[topic_id].append((doc_id, score))

在此之后,您可以看到某个主题的所有(doc_id, score) 值的列表,如下所示(对于主题0):

print(docs_per_topic[0])

如果您对每个主题的顶级文档感兴趣,可以进一步按每个列表对的分数对它们进行排序:

for doc_list in docs_per_topic:
    doc_list.sort(key=lambda id_and_score: id_and_score[1], reverse=True)

然后,您可以获得主题 0 的前 10 个文档,例如:

print(docs_per_topic[0][:10])

请注意,这一切都使用内存中的列表,这对于非常大的语料库可能变得不切实际。在某些情况下,您可能需要将每个主题的列表编译成磁盘支持的结构,例如文件或数据库。

【讨论】:

  • 我已经编辑了我的问题以添加我用来运行 gensim LDA 的脚本。你能看看它并建议我可以使用的代码吗?非常感谢。
  • 非常感谢,它有效!不过只是一个小问题。我无法使用文档 ID 追溯到我的文件夹中的文档。看起来 gensim 没有按照与我文件夹中的文档相同的顺序分配文档 ID。我已经尝试按名称/类型/添加/修改重新排列我的文件夹中的文档,但它仍然不符合 gensim
  • 如果您的文档仅由文件名/文件路径标识,您需要记住您自己的 doc_id 到原始文件路径的映射。例如,您可以将代码扩展到第一个,在顶部创建另一个list,如id_to_path = []。然后,在for file in files: 循环的底部,记住文件路径的顺序与创建文档的顺序相同,即id_to_path.append[newpath)。然后,最后,您可以在id_to_path 中查找任何doc_id 以找到原始文件。
  • 谢谢。我已经完成了您所说的操作,但一直在努力弄清楚如何查找 doc-id 并输出相应的路径/文件名
  • 明白你所说的。非常感谢您的帮助。接受你的回答。
猜你喜欢
  • 2022-01-14
  • 2017-02-19
  • 2016-07-11
  • 2018-03-16
  • 2013-06-23
  • 2017-12-31
  • 2014-11-06
  • 1970-01-01
  • 2015-06-27
相关资源
最近更新 更多