【问题标题】:How can I get the dominant topic for all documents?如何获得所有文档的主导主题?
【发布时间】:2022-01-11 13:43:14
【问题描述】:

我创建了一个标识 15 个主题的 lda 模型。当我运行代码以获取所有文档的主要主题时,它给了我 10 个主题而不是 15 个。 如何根据 lda 模型的 15 个主题获取所有文档的主导主题?

LDA model
    lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
                                               id2word=id2word,
                                               num_topics=15,
                                               random_state=100,
                                               update_every=1,
                                               chunksize=100,
                                               passes=20,
                                               alpha="auto",
                                               per_word_topics=True)

查找所有文档的主要主题的代码:

def format_topics_sentences(ldamodel=lda_model, corpus=corpus, texts=data):
    # Init output
    sent_topics_df = pd.DataFrame()

    # Get main topic in each document
    for i, row_list in enumerate(ldamodel[corpus]):
        row = row_list[0] if ldamodel.per_word_topics else row_list            
        # print(row)
        row = sorted(row, key=lambda x: (x[1]), reverse=True)
        # Get the Dominant topic, Perc Contribution and Keywords for each document
        for j, (topic_num, prop_topic) in enumerate(row):
            if j == 0:  # => dominant topic
                wp = ldamodel.show_topic(topic_num)
                topic_keywords = ", ".join([word for word, prop in wp])
                sent_topics_df = sent_topics_df.append(pd.Series([int(topic_num), round(prop_topic,4), topic_keywords]), ignore_index=True)
            else:
                break
    sent_topics_df.columns = ['Dominant_Topic', 'Perc_Contribution', 'Topic_Keywords']

    # Add original text to the end of the output
    contents = pd.Series(texts)
    sent_topics_df = pd.concat([sent_topics_df, contents,df1, df2], axis=1)
    return(sent_topics_df)


df_topic_sents_keywords = format_topics_sentences(ldamodel=lda_model, corpus=corpus, texts=data)

# Format
df_dominant_topic = df_topic_sents_keywords.reset_index()
df_dominant_topic.columns = ['Document_No', 'Dominant_Topic', 'Topic_Perc_Contrib', 'Keywords', 'Text', 'id', 'datum']
#df_dominant_topic.head(20)

#save
df_dominant_topic.to_csv('data/dominant_topic.csv', sep=',')

【问题讨论】:

    标签: python gensim lda


    【解决方案1】:

    您是否尝试过使用minimum_probability=0.0 初始化模型,或者使用minimum_probability=0.0 显式调用get_document_topics()[…]-indexing 所依赖的方法),这样您的主题结果就不会被裁剪为那些比默认minimum_probability=0.01概率更大的那些?

    请注意,show_topic() 也有一个默认参数 topn=10,它只会显示前 10 个相关词,除非您提供更大的值。

    【讨论】:

      猜你喜欢
      • 2020-10-02
      • 2021-12-12
      • 1970-01-01
      • 2019-01-12
      • 2014-05-26
      • 2023-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多