使用gensim实现LDA代码

使用gensim实现LDA代码

第一步,加载

from gensim.models import LdaModel
from gensim.test.utils import common_texts
from gensim.corpora.dictionary import Dictionary
from gensim import similarities
from pprint import pprint

import logging
logging.basicConfig(format=’%(asctime)s : %(levelname)s : %(message)s’, level=logging.INFO)

第二步,数据处理

num_topics = 10
common_dictionary = Dictionary(common_texts)
#pprint(common_dictionary.token2id)
common_corpus = [common_dictionary.doc2bow(text) for text in common_texts]

第三部,训练模型

lda = LdaModel(
corpus=common_corpus,
id2word=common_dictionary,
#模型训练时转换成word输出,感觉很方便
#chunksize=chunksize,
#alpha=‘auto’,
#eta=‘auto’,
#iterations=iterations,
num_topics=num_topics
#passes=passes,
#eval_every=eval_every
)

save_file = (’./lda_model_save/model_0’)
lda.save(save_file)

第四步,模型预测

model_file = (’./lda_model_save/model_0’)
lda = LdaModel.load(model_file)

top_topics = lda.top_topics(corpus = common_corpus, dictionary = common_dictionary, topn=3)

#每个主题的前topn个词,top是用来预测的,与show不同
avg_topic_coherence = sum([t[1] for t in top_topics]) / num_topics
print(‘Average topic coherence: %.4f.’ % avg_topic_coherence)

疑问:gensim训练的lda并不能展示文档-主题分布,只有一个lda.show_topics(num_words=3)
可以展示训练好的主题-词分布,所以要观察训练数据中的文档-主题必须重新预测。

docs_topic = [doc_topic for doc_topic in lda[common_corpus]]
pprint(docs_topic)

新文档要重新预测我可以理解。但是训练数据,既然已经训好了,并且得到了两个分布,该如何直接输出呢,为什么不能方便的输出,希望有了解的同学帮忙解答。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值