【问题标题】:Getting topic-word distribution from LDA in scikit learn在 scikit learn 中从 LDA 获取主题词分布
【发布时间】:2017-10-27 18:09:23
【问题描述】:

我想知道在 scikit learn 的 LDA 实现中是否有一种方法可以返回主题词分布。就像 genism show_topics() 方法一样。我检查了文档,但没有找到任何东西。

【问题讨论】:

    标签: python scikit-learn lda


    【解决方案1】:

    看看sklearn.decomposition.LatentDirichletAllocation.components_

    components_ : 数组,[n_topics, n_features]

    主题词分布。 components_[i, j] 表示主题 i 中的单词 j。

    这是一个最小的例子:

    import numpy as np
    from sklearn.decomposition import LatentDirichletAllocation
    from sklearn.feature_extraction.text import CountVectorizer
    
    data = ['blah blah foo bar', 'foo foo foo foo bar', 'bar bar bar bar foo',
            'foo bar bar bar baz foo', 'foo foo foo bar baz', 'blah banana', 
            'cookies candy', 'more text please', 'hey there are more words here',
            'bananas', 'i am a real boy', 'boy', 'girl']
    
    vectorizer = CountVectorizer()
    X = vectorizer.fit_transform(data)
    
    vocab = vectorizer.get_feature_names()
    
    n_top_words = 5
    k = 2
    
    model = LatentDirichletAllocation(n_topics=k, random_state=100)
    
    id_topic = model.fit_transform(X)
    
    topic_words = {}
    
    for topic, comp in enumerate(model.components_):
        # for the n-dimensional array "arr":
        # argsort() returns a ranked n-dimensional array of arr, call it "ranked_array"
        # which contains the indices that would sort arr in a descending fashion
        # for the ith element in ranked_array, ranked_array[i] represents the index of the
        # element in arr that should be at the ith index in ranked_array
        # ex. arr = [3,7,1,0,3,6]
        # np.argsort(arr) -> [3, 2, 0, 4, 5, 1]
        # word_idx contains the indices in "topic" of the top num_top_words most relevant
        # to a given topic ... it is sorted ascending to begin with and then reversed (desc. now)    
        word_idx = np.argsort(comp)[::-1][:n_top_words]
    
        # store the words most relevant to the topic
        topic_words[topic] = [vocab[i] for i in word_idx]
    

    查看结果:

    for topic, words in topic_words.items():
        print('Topic: %d' % topic)
        print('  %s' % ', '.join(words))
    
    Topic: 0
      more, blah, here, hey, words
    Topic: 1
      foo, bar, blah, baz, boy
    

    显然,您应该尝试使用更大的正文代码来尝试此代码,但这是获得给定数量主题的最有用词的一种方法。

    【讨论】:

    • 嗨。非常感谢你做的这些。你知道我怎样才能得到主题中每个单词的频率吗?
    • 我不确定信息是否直接存储在 LatentDirichletAllocation 对象本身中,但我可以想到两种(相对简单的)方法:1)如果您使用的是 @ 987654326@,只需将计数相加,逐列(即逐个令牌)并从那里查找; 2) 使用collections.Counter 之类的东西来计算整个语料库中的单个标记flattened
    猜你喜欢
    • 2016-02-27
    • 2012-12-08
    • 2015-06-27
    • 2019-09-09
    • 2019-04-27
    • 2019-02-05
    • 1970-01-01
    • 2017-12-22
    • 2016-05-17
    相关资源
    最近更新 更多