首页 > 解决方案 > 使用 Gensim LDA 模型对文本进行分类

问题描述

作为参考,我已经看过以下问题:

  1. Gensim LDA 用于文本分类
  2. Python Gensim LDA 模型 show_topics 函数

我希望通过 Gensim 训练我的 LDA 模型,在模型创建的主题之一下对句子进行分类。长长的线条

lda = models.LdaModel(corpus=corpus, id2word=id2word, num_topics=7, passes=20)
lda.print_topics()
for line in document: # where each line in the document is its own sentence for simplicity
    print('Sentence: ', line)
    topic = lda.parse(line) # where the classification would occur
    print('Topic: ', topic)

我知道 gensim 没有parse功能,但是如何实现呢?这是我一直在关注的文档,但我没有得到任何地方:

https://radimrehurek.com/gensim/auto_examples/core/run_topics_and_transformations.html#sphx-glr-auto-examples-core-run-topics-and-transformations-py

提前致谢。

编辑:更多文档 - https://radimrehurek.com/gensim/models/ldamodel.html

标签: pythonpython-3.xgensimlda

解决方案


让我来解决你的问题:你想在一些文档上训练一个 LDA 模型并检索 7 个主题。然后,您想在这些主题中的一个(或多个?)中对新文档进行分类,这意味着您想推断新的、未见文档的主题分布。

如果是这样,gensim 文档会提供答案。

lda = models.LdaModel(corpus=corpus, id2word=id2word, num_topics=7, passes=20)
lda.print_topics()
count = 1
for line in document: # where each line in the document is its own sentence for simplicity
    print('\nSentence: ', line)
    line = line.split()
    line_bow = id2word.doc2bow(line)
    doc_lda = lda[line_bow]
    print('\nLine ' + str(count) + ' assigned to Topic ' + str(max(doc_lda)[0]) + ' with ' + str(round(max(doc_lda)[1]*100,2)) + ' probability!')
    count += 1

推荐阅读