这段代码演示了如何使用sklearn的LatentDirichletAllocation模型进行主题建模,并提取每个主题的前20个最高概率单词。

from sklearn.feature_extraction.text import CountVectorizer lda.fit(tf) topic_word_prob = lda.components_ / lda.components_.sum(axis=1)[:, np.newaxis] for i, topic_prob in enumerate(topic_word_prob): top_words_idx = topic_prob.argsort()[:-21:-1] top_words = [tf_feature_names[idx] for idx in top_words_idx] print(f'Topic {i}: {', '.join(top_words)}') print(f'Word Prob: {', '.join([str(prob) for prob in topic_prob[top_words_idx]])} '

若要指定主题数量,您可以在定义LDA模型时设置n_components参数。例如,以下代码创建一个包含5个主题的LDA模型:

lda = LatentDirichletAllocation(n_components=5, random_state=42)

n_components设置为任何您想要的整数值。然后,您可以运行相同的代码来打印每个主题的前20个最高概率单词。

注意:

  • tf是文本数据的词频矩阵。
  • tf_feature_names是词频矩阵中每个特征(单词)的名称列表。
  • random_state用于确保结果的可重复性。

通过调整n_components参数,您可以根据您的需求创建不同数量的主题。

如何使用sklearn的LatentDirichletAllocation模型指定主题数量

原文地址: https://www.cveoy.top/t/topic/m0bR 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录