gpt4 book ai didi

gensim - 从gensim LDA模型中提取主题分布

转载 作者:行者123 更新时间:2023-12-03 08:59:29 28 4
gpt4 key购买 nike

我使用 python 中的 gensim 包为一些文本文件创建了一个 LDA 模型。我想获得学习模型的主题分布。 gensim ldamodel 类中是否有任何方法或解决方案可以从模型中获取主题的分布?例如,我使用一致性模型来查找具有最佳一致性值的模型,该模型受主题数量在 1 到 5 范围内的影响。获得最佳模型后,我使用 get_document_topics 方法(感谢 kenhbs )来获取主题分布用于创建模型的文档。

id2word = corpora.Dictionary(doc_terms)

bow = id2word.doc2bow(doc_terms)

max_coherence = -1
best_lda_model = None

for num_topics in range(1, 6):

lda_model = gensim.models.ldamodel.LdaModel(corpus=bow, num_topics=num_topics)

coherence_model = gensim.models.CoherenceModel(model=lda_model, texts=doc_terms,dictionary=id2word)

coherence_value = coherence_model.get_coherence()

if coherence_value > max_coherence:
max_coherence = coherence_value
best_lda_model = lda_model

最好的有 4 个主题

print(best_lda_model.num_topics)

4

但是当我使用 get_document_topics 时,我得到的文档分布值少于 4 个。

topic_ditrs = best_lda_model.get_document_topics(bow)

print(len(topic_ditrs))

3

我的问题是:对于一个文档有 4 个主题(使用一致性模型)的最佳 lda 模型,为什么 get_document_topics 对于同一文档返回更少的主题?为什么有些主题的分布非常小(小于 1-e8)?

最佳答案

来自the documentation ,您可以使用两种方法来实现此目的。

如果您的目标是获取特定主题中的主要术语,请使用 get_topic_terms:

from gensim.model.ldamodel import LdaModel

K = 10
lda = LdaModel(some_corpus, num_topics=K)

lda.get_topic_terms(5, topn=10)
# Or for all topics
for i in range(K):
lda.get_topic_terms(i, topn=10)

您还可以打印整个底层np.ndarray(在标准 LDA 论文中称为 beta 或 phi,维度为 (K, V) 或 (V, K))。

phi = lda.get_topics()

编辑:从我在原始答案中包含的链接:如果您正在寻找文档的主题分布,请使用

res = lda.get_document_topics(bow)

从文档中可以看出,生成的对象包含以下三个列表:

  • list of (int, float) – Topic distribution for the whole document. Each element in the list is a pair of a topic’s id, and the probability that was assigned to it.

  • list of (int, list of (int, float), optional – Most probable topics per word. Each element in the list is a pair of a word’s id, and a list of topics sorted by their relevance to this word. Only returned if per_word_topics was set to True.

  • list of (int, list of float), optional – Phi relevance values, multipled by the feature length, for each word-topic combination. Each element in the list is a pair of a word’s id and a list of the phi values between this word and each topic. Only returned if per_word_topics was set to True.

现在,

tops, probs = zip(*res[0])

probs 将包含 K(对您来说是 4)个概率。有些可能为零,但它们的总和应该为 1

关于gensim - 从gensim LDA模型中提取主题分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52077016/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com