【问题标题】:Access dictionary in Python gensim topic modelPython gensim 主题模型中的访问字典
【发布时间】:2021-01-25 23:09:05
【问题描述】:

我想看看如何从 gensim lda 主题模型中访问字典。这在您训练 lda 模型、保存并稍后加载时尤其重要。换句话说,假设 lda_model 是在文档集合上训练的模型。要获得文档主题矩阵,可以执行以下操作或类似https://www.kdnuggets.com/2019/09/overview-topics-extraction-python-latent-dirichlet-allocation.html 中解释的操作:

def regTokenize(text):
    # tokenize the text into words
    import re
    WORD = re.compile(r'\w+')
    words = WORD.findall(text)
    return words

from gensim.corpora.dictionary import Dictionary
ttext = [regTokenize(d) for d in text]  
dic = Dictionary(ttext)
ttext = [dic.doc2bow(text) for text in ttext]
ttext = lda_model.get_document_topics(ttext)

但是,训练有素的 lda_model 中的字典可能与新数据不同,并在最后一行出现错误,例如:

"IndexError: index 41021 is out of bounds for axis 1 with size 41021"

有没有办法(或参数)从训练有素的lda_model 获取字典,用它代替dic = Dictionary(ttext)?非常感谢您的帮助和回答!

【问题讨论】:

    标签: python dictionary gensim lda topic-modeling


    【解决方案1】:

    一般方法应该是使用Dictionary.save方法将训练模型时创建的字典存储到文件中,并使用Dictionary.load将其读回以供重复使用。

    只有Dictionary.token2id 保持不变,才能用于将 id 映射到单词,反之亦然,用于预训练模型。

    【讨论】:

    • 感谢您的回复。 lda_model.get_topic_words(topicid,top_n=lda_model.nterms) 给出字典,但以排序形式 (top_n);有什么方法没有排序?有什么方法可以让我们拥有/保存一个对象的字典。
    猜你喜欢
    • 2013-11-06
    • 1970-01-01
    • 2023-04-06
    • 2018-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-03
    相关资源
    最近更新 更多