Tfidfvectorizer - 如何查看已处理的令牌?

问题描述 投票:1回答:3

如何检查TfidfVertorizer()中标记的字符串?如果我没有在参数中传递任何内容,TfidfVertorizer()将使用一些预定义的方法对字符串进行标记。我想观察它如何标记字符串,以便我可以更轻松地调整我的模型。

from sklearn.feature_extraction.text import TfidfVectorizer
corpus = ['This is the first document.',
          'This document is the second document.',
          'And this is the third one.',
          'Is this the first document?']
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(corpus)

我想要这样的东西:

>>>vectorizer.get_processed_tokens()
[['this', 'is', 'first', 'document'],
 ['this', 'document', 'is', 'second', 'document'],
 ['this', 'is', 'the', 'third', 'one'],
 ['is', 'this', 'the', 'first', 'document']]

我怎样才能做到这一点?

python scikit-learn nlp tf-idf tfidfvectorizer
3个回答
2
投票

build_tokenizer()将完全符合这一目的。

试试这个!

tokenizer = lambda docs: [vectorizer.build_tokenizer()(doc) for doc in docs]

tokenizer(corpus)

输出:

[['This', 'is', 'the', 'first', 'document'],
 ['This', 'document', 'is', 'the', 'second', 'document'],
 ['And', 'this', 'is', 'the', 'third', 'one'],
 ['Is', 'this', 'the', 'first', 'document']]

一个班轮解决方案将是

list(map(vectorizer.build_tokenizer(),corpus))

2
投票

我不确定是否有内置的sklearn函数来获取该格式的输出,但我很确定拟合的TfidfVectorizer实例具有vocabulary_属性,该属性返回术语到特征索引的映射字典。阅读更多here.

这个和get_feature_names方法的输出的组合应该能够为你做到这一点。希望能帮助到你。


1
投票

这可能在语法上不正确(在内存上执行此操作),但它的一般想法:

Y = X.to_array()
Vocab = vectorizer.get_feature_names()
fake_corpus = []
for doc in Y:
    l = [Vocab[word_index] for word_index in doc]
    fake_corpus.append(l)

使用Y,您可以为语料库中的每个文档添加单词的索引,使用词汇表,您可以获得给定索引所对应的单词,因此您基本上只需要将它们组合在一起。

© www.soinside.com 2019 - 2024. All rights reserved.