以下是使用LatentDirichletAllocation模型打印出源文档生成的自己设定个数的主题下的单词的分布概率的代码:

from sklearn.decomposition import LatentDirichletAllocation

num_topics = 5 # 设定主题个数
lda = LatentDirichletAllocation(n_components=num_topics)
lda.fit(df.content_cutted)

feature_names = vectorizer.get_feature_names() # 获取所有单词列表

for topic_idx, topic in enumerate(lda.components_):
    print("Topic #%d:" % topic_idx)
    print(", ".join([feature_names[i] + " (" + "%.3f" % topic[i] + ")" for i in topic.argsort()[:-11:-1]]))
    # 打印出每个主题下概率最高的前十个单词及其概率分布

其中,vectorizer是用于将文本转换为向量的向量化器,需要在模型训练之前进行实例化。如果没有向量化器,可以使用以下代码进行实例化:

from sklearn.feature_extraction.text import CountVectorizer

vectorizer = CountVectorizer()
X = vectorizer.fit_transform(df.content_cutted)

注意,以上代码仅能打印出每个主题下概率最高的前十个单词及其概率分布。如果需要打印出每个单词在每个主题下的概率分布,可以使用以下代码:

for topic_idx, topic in enumerate(lda.components_):
    print("Topic #%d:" % topic_idx)
    for i in topic.argsort()[:-11:-1]:
        print("%s (%.3f)" % (feature_names[i], topic[i]))
    # 打印出每个主题下所有单词的概率分布

这样可以打印出每个主题下所有单词的概率分布,但是需要注意,如果单词数量过多,输出结果会非常冗长。

对于LatentDirichletAllocation模型输入文档为dfcontent_cutted 如何打印出源文档生成的自己设定个数的主题下的单词的分布概率单词的概率分布小数点后保留三位有效数字不是每个文档的主题概率请给出代码

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

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