【问题标题】:TFIDIF Model Creation TypeError in GensimGensim 中的 TFIDIF 模型创建类型错误
【发布时间】:2018-03-04 06:28:00
【问题描述】:

TypeError: 'TfidfModel' 对象不可调用

为什么初始化后无法为每个 Doc 计算 TFIDF 矩阵?

我从 999 个文档开始:999 个段落,每个段落大约 5-15 个句子。 在 spaCy 对所有内容进行标记后,我创建了 dictionary(约 16k 唯一标记)和 corpus(元组列表列表)

现在我准备为一些 ML 创建 tfidf 矩阵(以及后来的 LDA 和 w2V 矩阵);但是,在使用我的语料库初始化 tfidf 模型之后(用于计算“IDF”) tfidf = models.TfidfModel(corpus) 尝试查看每个文档的 tfidf 时收到以下错误消息 tfidf(corpus[5]) TypeError: 'TfidfModel' 对象不可调用

我能够使用不同的语料库创建此模型,其中我有四个文档,每个文档仅包含一个句子。 在那里我可以确认预期的语料库格式是元组列表的列表: [doc1[(word1, count),(word2, count),...], doc2[(word3, count),(word4,count),...]...]

from gensim import corpora, models, similarities

texts = [['teenager', 'martha', 'moxley'...], ['ok','like','kris','usual',...]...]
dictionary = corpora.Dictionary(texts)
>>> Dictionary(15937 unique tokens: ['teenager', 'martha', 'moxley']...)

corpus = [dictionary.doc2bow(text) for text in texts]
>>> [[(0, 2),(1, 2),(2, 1)...],[(3, 1),(4, 1)...]...]

tfidf = models.TfidfModel(corpus)
>>> TfidfModel(num_docs=999, num_nnz=86642)

tfidf(corpus[0])
>>> TypeError: 'TfidfModel' object is not callable

corpus[0]
>>> [(0, 2),(1, 2),(2, 1)...]

print(type(corpus),type(corpus[1]),type(corpus[1][3]))
>>> <class 'list'> <class 'list'> <class 'tuple'>

【问题讨论】:

    标签: python nlp gensim tf-idf language-features


    【解决方案1】:

    扩展@whs2k 的答案,方括号语法用于围绕语料形成转换包装器,形成一种惰性处理管道。

    直到我阅读了本教程中的注释后才明白:https://radimrehurek.com/gensim/tut2.html

    调用 model[corpus] 只会在旧语料库周围创建一个包装器 文档流——实际转换是在运行中完成的,在 文档迭代。我们无法转换整个语料库 调用 corpus_transformed = model[corpus],因为这意味着 将结果存储在主存储器中,这与 gensim 的 内存独立的目标。如果你要迭代 多次变换corpus_transformed,以及变换 成本高,首先将生成的语料序列化到磁盘并继续 使用它。

    但我仍然觉得我没有完全理解底层 Python 列表的魔力。

    【讨论】:

      【解决方案2】:

      代替:tfidf(corpus[0])

      试试:tfidf[corpus[0]]

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 2019-02-26
        • 2021-08-14
        • 1970-01-01
        相关资源
        最近更新 更多