【问题标题】:What is the difference between Tfidftransformer and Tfidfvectorizer?Tfidftransformer 和 Tfidfvectorizer 有什么区别?
【发布时间】:2020-09-26 04:39:56
【问题描述】:

我对@9​​87654321@ 和Tfidfvectorizer 的使用有点困惑,因为它们看起来很相似。一个使用单词转换矩阵(Tfidfvectorizer),另一个使用已经转换的文本(使用CountVectorizer)到矩阵。

谁能解释一下这两者的区别?

【问题讨论】:

    标签: python pandas scikit-learn tf-idf tfidfvectorizer


    【解决方案1】:

    CountVectorizer + TfidfTransformer = TfidfVectorizer这是简单实用的理解方式。 TfidfVectorizer 一步完成 CountVectorizer 和 TfidfTransformer。

    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.feature_extraction.text import TfidfTransformer
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.pipeline import Pipeline
    
    # transformer a
    a = Pipeline(steps =[
            ('count_verctorizer',  CountVectorizer()),  
            ('tfidf', TfidfTransformer()),
    ])
    
    # transformer b
    b = TfidfVectorizer()
    

    ab 转换器将执行相同的转换。

    如果在向模型提供特征之前预处理只包括 TFIDF,那么b 将是最佳选择。但有时我们想拆分预处理。例如,我们希望在执行 Inverses Document Frequency 之前只保留最佳术语。在这种情况下,我们会选择a。因为我们可以执行 CountVectorizer 然后在 IDF 之前进行额外的预处理。例如

    
    from sklearn.feature_extraction.text import CountVectorizer
    from sklearn.feature_extraction.text import TfidfTransformer
    from sklearn.feature_extraction.text import TfidfVectorizer
    from sklearn.feature_selection import chi2
    from sklearn.feature_selection import SelectKBest
    from sklearn.pipeline import Pipeline
    from sklearn.linear_model import  LogisticRegressionCV
    
    # do counter terms and allow max 150k terms with 1-2 Ngrams
    # select the best 10K (reducing the size of our features)
    # do the IDF and the pass to our model
    
    hisia = Pipeline(steps =[
            ('count_verctorizer',  CountVectorizer(ngram_range=(1, 2), 
                                     max_features=150000,
    
                                    )
            ),
            ('feature_selector', SelectKBest(chi2, k=10000)),
            ('tfidf', TfidfTransformer(sublinear_tf=True)),
            ('logistic_regression', LogisticRegressionCV(cv=5,
                                                        solver='saga',
                                                        scoring='accuracy',
                                                        max_iter=200,
                                                        n_jobs=-1,
                                                        random_state=42, 
                                                        verbose=0))
    ])
    

    在示例中,我们在将术语传递给 IDF 之前对其进行了特征选择。这是可能的,因为我们可以通过首先执行 CountVectorizerTfidfTransformer 来拆分 TFIDF

    【讨论】:

      猜你喜欢
      • 2021-02-09
      • 2010-10-02
      • 2011-12-12
      • 2010-09-16
      • 2012-03-14
      • 2012-02-06
      • 2011-02-25
      • 2011-11-22
      • 2015-03-26
      相关资源
      最近更新 更多