如何使用Sklearn LDA模型指定主题数目

要将主题数目改为指定数目,需要在创建LDA模型时指定主题数目。以下是修改后的代码:

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.decomposition import LatentDirichletAllocation

n_topics = 5 # 设置主题数目为5

tf_vectorizer = CountVectorizer(max_df=0.95, min_df=2, stop_words='english')
tf = tf_vectorizer.fit_transform(data)

lda = LatentDirichletAllocation(n_components=n_topics, random_state=0)
lda.fit(tf)

tf_feature_names = tf_vectorizer.get_feature_names()

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]])}
')

在这个代码中,我们首先定义了一个变量n_topics,并将它设置为所需的主题数量。然后,我们在创建LatentDirichletAllocation模型时将n_components参数设置为n_topics。这样,LDA模型就会根据指定的主题数量进行训练。

注意:

  • data 应该是一个包含您想要进行主题建模的文本数据的列表。
  • 您可能需要调整 max_dfmin_dfstop_words 参数以获得最佳结果。

通过这种方式,您就可以轻松地使用Sklearn LDA模型指定主题数目,并进行主题建模。

如何使用Sklearn LDA模型指定主题数目

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

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