首页 > 解决方案 > CountVectorizer 返回零

问题描述

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

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都为零。(语料库文档不为空。)

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

标签: pythonpython-3.xscikit-learncountvectorizer

解决方案


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

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

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

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


推荐阅读