如何从 LDA 模型创建词云?

How to create wordcloud from LDA model?

根据 ?gensim.models.ldamodel 的文档,我想训练一个 ldamodel 和(来自 this SO answer 从中创建一个 worcloud)。我正在使用来自两个来源的以下代码:

from gensim.test.utils import common_texts
from gensim.corpora.dictionary import Dictionary
import gensim
import matplotlib.pyplot as plt
from wordcloud import WordCloud

common_dictionary = Dictionary(common_texts) # create corpus
common_corpus = [common_dictionary.doc2bow(text) for text in common_texts]

lda = gensim.models.LdaModel(common_corpus, num_topics=10) # train model on corpus
for t in range(lda.num_topics):
    plt.figure()
    plt.imshow(WordCloud().fit_words(lda.show_topic(t, 200)))
    plt.axis("off")
    plt.title("Topic #" + str(t))
    plt.show()

但是,我在 plt.imshow(...)

行得到一个 AttributeError: 'list' object has no attribute 'items'

有人可以帮我吗? (类似问题的答案对我没有用,我正在尝试用它编译一个最小的管道。)

根据文档,方法 WordCloud.fit_words() 需要字典作为输入。

您的错误似乎强调它正在寻找属性 'items',通常是字典的属性,但却找到了 list 对象。

所以问题是:lda.show_topic(t, 200) returns 列表而不是字典。使用dict()施放!

最后:

plt.imshow(WordCloud().fit_words(dict(lda.show_topic(t, 200))))