【问题标题】:Displaying topics associated with a document/query in Gensim在 Gensim 中显示与文档/查询相关的主题
【发布时间】:2017-08-17 03:08:00
【问题描述】:

Gensim 有一个教程,说明如何在给定文档/查询字符串的情况下,按降序说明与它最相似的其他文档:

http://radimrehurek.com/gensim/tut3.html

它还可以显示与整个模型相关联的主题

How to print the LDA topics models from gensim? Python

但是您如何找到与给定文档/查询字符串相关联的主题?理想情况下,每个主题都有一些数字相似度指标?我找不到任何关于它的东西。

【问题讨论】:

  • 主题是否可以包含在查询字符串中,或​​者它们是互斥的?
  • @NathanMcCoy 互斥; gensim谈话题的时候,并不是指普通英语意义上的单词,而是指由单词向量和浮点权重组成的数据结构。

标签: python nlp gensim lda topic-modeling


【解决方案1】:

如果要查找未见文档的主题分布,则需要将感兴趣的文档转换为词袋表示

from gensim import utils, models
from gensim.corpora import Dictionary
lda = models.LdaModel.load('saved_lda.model') # load saved model
dictionary = Dictionary.load('saved_dictionary.dict') # load saved dict
text = ' '
with open('document', 'r') as inp: # convert file to string
    for line in inp:
        text += line + ' '
tkn_doc = utils.simple_preprocess(text) # filter & tokenize words
doc_bow = dictionary.doc2bow(tkn_doc) # use dictionary to create bow
doc_vec = lda[doc_bow] # this is the topic probability distribution for the document of interest

从这段代码中,您可以得到一个稀疏向量,其中索引代表主题 0....n,每个“权重”是文档中的单词属于模型中该主题的概率。 您可以通过使用 matplotlib 创建条形图来可视化分布。

y_axis = []
x_axis = []
for topic_id, dist in enumerate(doc_vec):
    x_axis.append(topic_id + 1)
    y_axis.append(dist)
width = 1 
plt.bar(x_axis, y_axis, width, align='center', color='r')
plt.xlabel('Topics')
plt.ylabel('Probability')
plt.title('Topic Distribution for doc')
plt.xticks(np.arange(2, len(x_axis), 2), rotation='vertical', fontsize=7)
plt.subplots_adjust(bottom=0.2)
plt.ylim([0, np.max(y_axis) + .01])
plt.xlim([0, len(x_axis) + 1])
plt.savefig(output_path)
plt.close()

如果您想查看每个主题中的 topn 术语,您可以print them like this。参考该图,您可以查找您打印的前 n 个单词并确定该文档是如何被模型解释的。 您还可以通过使用 hellinger distance、euclidean、jensen shannon 等向量计算来找到两个不同文档概率分布向量之间的距离。

【讨论】:

    猜你喜欢
    • 2014-05-26
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多