1.主题模型LDA(Latent Dirichlet allocation)

其基本思想是把文档看成各种隐含主题的混合,而每个主题则表现为跟该主题相关的词项的概率分布

LDA基于词袋(bag of words)模型构建,认为文档和单词都是可以交换的,忽略单词在文档中的顺序和文档在语料库中的顺序,从而将文本信息转化为易于建模的数字信息

  • 主题就是一个桶,里面装了出现概率较高的单词,这些单词与这个主题有很强的相关性

LDA模型包含此项、主题和文档三层结构

  • 本质上,LDA简单粗暴地认为:文章中的每个词都是通过“以一定概率选择某个主题,再从该主题中以一定概率选择某个词”得到的
  • 一个词可能会关联多个主题,因此需要计算各种情况下的概率分布,来确定最可能出现的主题是哪种
  • 一篇文章可能会涉及到几个主题,因此也需要计算多个主题的概率

 


2.sklearn实现

# sklearn实现主题模型
# 使用词频矩阵计算得到TF-IDF
# 设定LDA模型
from sklearn.decomposition import LatentDirichletAllocation

n_topics = 10
ldamodel = LatentDirichletAllocation(n_topics)
# 拟合LDA模型
ldamodel.fit(tfidf)
# 
print(ldamodel.components_.shape)
ldamodel.components_[:2]

文本挖掘学习(四) 主题模型、LDA

# 主题词打印
def print_top_words(model, feature_names, n_top_words):
    for topic_idx, topic in enumerate(model.components_):
        print('Topic #%d:' % topic_idx)
        print(' '.join([feature_names[i] for i in topic.argsort()[:-n_top_words-1:-1]]))
    print()
    
n_top_words = 12
tf_feature_names = countvec.get_feature_names()
print_top_words(ldamodel, tf_feature_names, n_top_words)

 

文本挖掘学习(四) 主题模型、LDA

相关文章: