【问题标题】:CountVectorizer returning zerosCountVectorizer 返回零
【发布时间】:2021-10-24 07:43:45
【问题描述】:

我有一个词汇文本文件,其中每一行都是一个单词。词汇表中的几个单词如下所示:

AccountsAndTransactions_/get/v2/accounts/details_DELETE
AccountsAndTransactions_/get/v2/accounts/details_GET
AccountsAndTransactions_/get/v2/accounts/details_POST
AccountsAndTransactions_/get/v2/accounts/{accountId}/transactions_DELETE
AccountsAndTransactions_/get/v2/accounts/{accountId}/transactions_GET
AccountsAndTransactions_/get/v2/accounts/{accountId}/transactions_POST

重要提示:AccountsAndTransactions_/get/v2/accounts/details_DELETE这是本题中的一个词。

从文本文件中读取词汇:

with open(Path(VOCAB_FILE), "r") as f:
    vocab = f.read().splitlines()

生成doc_paths

doc_paths = [f for f in listdir(DOC_DIR) if isfile(join(DOC_DIR, f))]
r = re.compile(".*txt")
doc_paths = list(filter(r.match, doc_paths))
doc_paths = [Path(join(DOC_DIR, i)) for i in doc_paths]

我在文档上运行CountVectorizer

tf_vectorizer = CountVectorizer(input='filename', lowercase=False, vocabulary=vocab)
tf = tf_vectorizer.fit_transform(doc_paths) # doc_paths is list of pathlib.Path(...) object.
X = tf.toarray() # returns zero matrix

问题是X 中的所有值都为零。 (语料库文件不为空。)

有人可以帮我吗?我想要每个文档的词汇表中每个单词的词频。

【问题讨论】:

  • 您在哪里指定要读取的文件列表? fit_transform 需要一个字符串列表,而不是文件名列表。
  • @TimRoberts 不是 input=="filename"
  • 什么是vocab?我无法重现给定示例的问题
  • 当 CountVectorizer 的输入参数为“文件名”时,首先从文件中读取数据,因此您需要提供文件名。
  • vocab 是词汇表,上面显示了词汇表中的几个单词。

标签: python python-3.x scikit-learn countvectorizer


【解决方案1】:

我通过覆盖CountVectorizer 的默认analyzer 解决了这个问题:

def analyzer_custom(doc):
    return doc.split()

tf_vectorizer = CountVectorizer(input='filename',
                                lowercase=False,
                                vocabulary=vocab,
                                analyzer=analyzer_custom)

感谢@Chris 解释 CountVectorizer 的内部细节。

【讨论】:

    猜你喜欢
    • 2017-07-26
    • 2018-01-04
    • 2018-11-07
    • 2016-05-18
    • 2021-12-24
    • 2021-09-23
    • 2016-11-24
    • 2017-11-19
    • 2015-01-23
    相关资源
    最近更新 更多