【问题标题】:Tfidvectorizer - L2 normalized vectorTfidfvectorizer - L2 归一化向量
【发布时间】:2016-05-08 22:41:37
【问题描述】:

我想确保 TfidfVectorizer 对象返回一个 l2 归一化向量。我正在对不同长度的文档进行二进制分类问题。

我正在尝试提取每个语料库的归一化向量,所以我假设我可以总结 Tfidfvectorizer 矩阵的每一行。但是总和大于 1,我认为标准化的语料库会将所有文档转换为 0-1 之间的范围。

vect = TfidfVectorizer(strip_accents='unicode',
stop_words=stopwords,analyzer='word', use_idf=True, tokenizer=tokenizer, ngram_range=(1,2),sublinear_tf= True , norm='l2')

tfidf = vect.fit_transform(X_train)
# sum norm l2 documents
vect_sum = tfidf.sum(axis=1)

vect_sum 的值大于 1,我认为使用 norm 会导致所有向量都在 0-1 之间。我刚刚知道 scikit learn 中有一个预处理对象 - preprocessing.normalizer。 那是我应该在 Gridsearch 的管道中使用的东西吗?请参见下面的示例。

pipeline = Pipeline([
    ('plb', normalize(tfidf, norm='l2')), #<-- sklearn.preprocessing
    ('tfidf', tfidf_vectorizer),
    ('clf', MultinomialNB()),  
])

preprocessing.normalizer 和 Tfidfvectorizer norm 参数有什么区别?

【问题讨论】:

    标签: python scikit-learn normalization tf-idf


    【解决方案1】:

    对于 L2,不是行之和等于 1,而是平方和等于 1。L1 范数将产生一个范数,其中值之和等于 1。

    X_train = [" This is my first sentence", "Short sentence"]
    vect = TfidfVectorizer(strip_accents='unicode',analyzer='word', use_idf=True, ngram_range=(1,2),sublinear_tf= True , norm='l2')
    
    tfidf = vect.fit_transform(X_train)
    # sum norm l2 documents
    vect_sum = tfidf.multiply(tfidf).sum(axis=1)
    vect_sum
    
    # matrix([[ 1.],
    #         [ 1.]])
    

    TF-IDF 仅适用于计数。如果在 TF-IDF 权重生成后执行normalize,则可以达到相同的效果。

    from sklearn.feature_extraction.text import normalize
    
    vect = TfidfVectorizer(strip_accents='unicode',analyzer='word', use_idf=True, ngram_range=(1,2),
                           sublinear_tf= True , norm=None)
    
    tfidf = vect.fit_transform(X_train)
    tfidf = normalize(tfidf)
    

    这相当于原始示例中的TfidfVectorizer(..., norm='l2')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-12
      • 2016-03-29
      • 2015-11-23
      • 1970-01-01
      • 2020-06-02
      • 2014-08-05
      • 2018-09-19
      • 1970-01-01
      相关资源
      最近更新 更多