如果要查找未见文档的主题分布,则需要将感兴趣的文档转换为词袋表示
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 等向量计算来找到两个不同文档概率分布向量之间的距离。