【问题标题】:Error in Computing the Coherence Score – AttributeError: 'dict' object has no attribute 'id2token'计算连贯性分数时出错 – AttributeError: 'dict' object has no attribute 'id2token'
【发布时间】:2019-11-25 01:48:29
【问题描述】:

我是 NLP 的初学者,这是我第一次做主题建模。我能够生成我的模型,但是我无法生成一致性指标。

将term-document矩阵转换成新的gensim格式,来自df --> sparse matrix --> gensim corpus

sparse_counts = scipy.sparse.csr_matrix(data_dtm)
corpus = matutils.Sparse2Corpus(sparse_counts)
corpus

df_lemmatized.head()

# Gensim also requires dictionary of the all terms and their respective location in the term-document matrix
tfidfv = pickle.load(open("tfidf.pkl", "rb"))
id2word = dict((v, k) for k, v in tfidfv.vocabulary_.items())
id2word

这是我的模型:

lda = models.LdaModel(corpus=corpus, id2word=id2word, num_topics=15, passes=10, random_state=43)
lda.print_topics()

最后,这里是我尝试使用 Coherence Model 获得 Coherence Score 的地方:

# Compute Perplexity
print('\nPerplexity: ', lda.log_perplexity(corpus))  

# Compute Coherence Score
coherence_model_lda = CoherenceModel(model=lda, texts=df_lemmatized.long_title, dictionary=id2word, coherence='c_v')
coherence_lda = coherence_model_lda.get_coherence()
print('\nCoherence Score: ', coherence_lda)

这是错误:

---> 57 if not dictionary.id2token: # 可能未在标准 gensim.corpora.Dictionary 中初始化 58 setattr(字典,'id2token',{v:k为k,v在dictionary.token2id.items()}) 59 AttributeError: 'dict' 对象没有属性 'id2token'

【问题讨论】:

    标签: python scipy nlp gensim topic-modeling


    【解决方案1】:

    我没有您的数据,因此无法重现该错误。所以,我来猜一猜!问题在于您的id2word,它应该是corpora.dictionary.Dictionary 而不仅仅是dict。因此,您需要执行以下操作:

    >>> from gensim import corpora
    >>>
    >>> word2id = dict((k, v) for k, v in tfidfv.vocabulary_.items())
    >>> d = corpora.Dictionary()
    >>> d.id2token = id2word
    >>> d.token2id = word2id
    >>> #...
    >>> # change `id2word` to `d`
    >>> coherence_model_lda = CoherenceModel(model=lda, texts=df_lemmatized.long_title, dictionary=d, coherence='c_v')
    

    而且我认为它现在应该可以正常工作了!

    【讨论】:

    • 感谢您的回复...不幸的是它抛出了“KeyError:”消息
    • 您解决了 KeyError 问题吗?有同样的问题
    • @Grumpybeard 这个答案与KeyError 无关。无论如何,您遇到了什么错误?
    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 2022-12-01
    • 2018-08-26
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-18
    相关资源
    最近更新 更多