pyLDAvis:尝试可视化主题时的验证错误

问题描述 投票:4回答:1

我尝试使用gensim为300000条记录生成主题。在尝试可视化主题时,我收到验证错误。我可以在模型训练后打印主题,但是使用pyLDAvis失败了

# Running and Training LDA model on the document term matrix.
ldamodel1 = Lda(doc_term_matrix1, num_topics=10, id2word = dictionary1, passes=50, workers = 4)

(ldamodel1.print_topics(num_topics=10, num_words = 10))
 #pyLDAvis
d = gensim.corpora.Dictionary.load('dictionary1.dict')
c = gensim.corpora.MmCorpus('corpus.mm')
lda = gensim.models.LdaModel.load('topic.model')

#error on executing this line
data = pyLDAvis.gensim.prepare(lda, c, d)

在运行pyLDAvis之后尝试运行时出现以下错误

---------------------------------------------------------------------------
ValidationError                           Traceback (most recent call last)
<ipython-input-53-33fd88b65056> in <module>()
----> 1 data = pyLDAvis.gensim.prepare(lda, c, d)
      2 data

C:\ProgramData\Anaconda3\lib\site-packages\pyLDAvis\gensim.py in prepare(topic_model, corpus, dictionary, doc_topic_dist, **kwargs)
    110     """
    111     opts = fp.merge(_extract_data(topic_model, corpus, dictionary, doc_topic_dist), kwargs)
--> 112     return vis_prepare(**opts)

C:\ProgramData\Anaconda3\lib\site-packages\pyLDAvis\_prepare.py in prepare(topic_term_dists, doc_topic_dists, doc_lengths, vocab, term_frequency, R, lambda_step, mds, n_jobs, plot_opts, sort_topics)
    372    doc_lengths      = _series_with_name(doc_lengths, 'doc_length')
    373    vocab            = _series_with_name(vocab, 'vocab')
--> 374    _input_validate(topic_term_dists, doc_topic_dists, doc_lengths, vocab, term_frequency)
    375    R = min(R, len(vocab))
    376 

C:\ProgramData\Anaconda3\lib\site-packages\pyLDAvis\_prepare.py in _input_validate(*args)
     63    res = _input_check(*args)
     64    if res:
---> 65       raise ValidationError('\n' + '\n'.join([' * ' + s for s in res]))
     66 
     67 

ValidationError: 
 * Not all rows (distributions) in topic_term_dists sum to 1.
python nlp lda topic-modeling
1个回答
0
投票

发生这种情况是因为pyLDAvis程序期望模型中的所有文档主题至少出现在语料库中一次。在制作语料库/文本之后以及制作模型之前进行一些预处理时,可能会发生这种情况。

模型的内部字典中未在您提供的字典中使用的单词将导致此失败,因为现在概率略小于1。

您可以通过将缺少的单词添加到语料库字典(或将单词添加到语料库并从中创建字典)来解决此问题,或者您可以在“断言”之前将此行添加到site-packages \ pyLDAvis \ gensim.py代码中topic_term_dists.shape [0] == doc_topic_dists.shape [1]“(应该是〜第67行)

topic_term_dists = topic_term_dists / topic_term_dists.sum(axis=1)[:, None]

假设您的代码一直运行到这一点,这应该重新规范主题分布而不丢失dict项。但请注意,在语料库中包含所有术语会更好。


0
投票

在我过滤了我的字典之后,这发生在我的HDPModel中 - 我留下了很多零长度文档,这产生了这个错误。在通过corpora.MmCorpus.serialize(args.save_folder + '/gensim.mm', (x for x in corpus if len(x) > 0))将我的MmCorpus保存到磁盘之前我删除了它们,这在以后运行HDP时解决了问题。 corpus是我的文本文档的生成器。

© www.soinside.com 2019 - 2024. All rights reserved.