【问题标题】:Access Term Topic Matrix generated by Gensim LDA访问 Gensim LDA 生成的术语主题矩阵
【发布时间】:2017-11-21 23:19:15
【问题描述】:

我已经使用 gensim 训练了一个 LDA 模型。我的印象是 Lda 将数据减少到两个较低级别的矩阵(参考:https://www.analyticsvidhya.com/blog/2016/08/beginners-guide-to-topic-modeling-in-python/),但我似乎无法弄清楚如何访问术语主题矩阵。我可以在 gensim 的文档中找到的唯一参考是 .get_topics() 属性,但是它提供的格式对我来说毫无意义。

应用转换来检索文档主题矩阵很容易,如下所示:

doc_topic_matrix = lda_model[doc_term_matrix]

所以我希望有一种类似的功能方法来生成主题词矩阵。

理想情况下,输出应如下所示:

         word1  word2  word3  word4  word5
topic_a   .12    .38    .07    .24    .19
topic_b   .41    .11    .04    .14    .30

对这是否可能有任何想法?

【问题讨论】:

    标签: python gensim lda


    【解决方案1】:

    很简单,你可以这样搞定:

    #get raw topic > word estimates
    topics_terms = model.state.get_lambda() 
    
    #convert estimates to probability (sum equals to 1 per topic)
    topics_terms_proba = np.apply_along_axis(lambda x: x/x.sum(),1,topics_terms)
    
    # find the right word based on column index
    words = [model.id2word[i] for i in range(topics_terms_proba.shape[1])]
    
    #put everything together
    pd.DataFrame(topics_terms_proba,columns=words)
    

    【讨论】:

      【解决方案2】:

      你已经提到了合适的方法get_topics()

      您可以通过以下方式解释使用 pandas 的结果:

      import pandas as pd
      from gensim.models import LdaModel
      from gensim.test.utils import common_dictionary, common_corpus
      
      model = LdaModel(common_corpus, id2word=common_dictionary, num_topics=2)
      pd.DataFrame(model.get_topics(), columns=model.id2word.values(), index=[f'topic {i}' for i in range(model.num_topics)])
      

      最终结果如下:

      【讨论】:

        猜你喜欢
        • 2015-01-29
        • 2016-07-11
        • 2018-07-13
        • 2017-02-19
        • 1970-01-01
        • 2011-03-15
        • 2015-08-19
        • 1970-01-01
        • 2015-01-26
        相关资源
        最近更新 更多