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