【问题标题】:Tfidfvectorizer - How can I check out processed tokens?Tfidfvectorizer - 如何查看已处理的令牌?
【发布时间】:2019-08-16 13:12:23
【问题描述】:

如何检查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


    【解决方案1】:

    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 方法的输出结合起来应该可以为您完成此操作。希望对您有所帮助。

      【讨论】:

        【解决方案3】:

        这可能在语法上不正确(在内存中执行此操作),但它的总体思路:

        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 可以获得语料库中每个文档的单词索引,使用 vocab 可以获得给定索引对应的单词,因此您基本上只需将它们组合起来即可。

        【讨论】:

          猜你喜欢
          • 2021-10-06
          • 1970-01-01
          • 2016-05-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多