【问题标题】:Sklearn TfIdfVectorizer remove docs containing all stopwordsSklearn TfIdfVectorizer 删除包含所有停用词的文档
【发布时间】:2019-07-29 03:17:29
【问题描述】:

我正在使用sklearnTfIdfVectorizer 来向量化我的语料库。在我的分析中,有一些文档由于包含所有停用词而被过滤掉了所有术语。为了减少稀疏性问题,并且因为将它们包含在分析中没有意义,我想将其删除。

查看TfIdfVectorizer 文档,没有可以设置的参数来执行此操作。因此,我正在考虑在将语料库传递到矢量化器之前手动删除它。但是,这有一个潜在的问题,即我得到的停用词与矢量化器使用的列表不同,因为我还使用min_dfmax_df 选项来过滤掉术语。

有没有更好的方法来实现我正在寻找的内容(即删除/忽略包含所有停用词的文档)?

任何帮助将不胜感激。

【问题讨论】:

    标签: python python-3.x scikit-learn tfidfvectorizer


    【解决方案1】:

    所以,你可以使用这个:

    import nltk
    from sklearn.feature_extraction.text import TfidfVectorizer
    
    def tokenize(text):
        # first tokenize by sentence, then by word to ensure that punctuation is caught as it's own token
        tokens = [word for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)]
        filtered_tokens = []
        # filter out any tokens not containing letters (e.g., numeric tokens, raw punctuation)
        punctuations="?:!.,;'�۪"
        for token in tokens:
            if token in punctuations:
                tokens.remove(token)
            if re.search('[a-zA-Z0-9]', token):
                filtered_tokens.append(token)
    
        st = ' '.join(filtered_tokens)
        return st
    tokenize(data)
    
    tfidf_vectorizer = TfidfVectorizer(max_df=0.8,min_df=0.01,stop_words='english',
        use_idf=True,tokenizer=tokenize)
    
    tfidf_matrix = tfidf_vectorizer.fit_transform(df['text'])
    ids = np.array(tfidf_matrix.sum(axis=1)==0).ravel()
    tfidf_filtered = tfidf_matrix[~ids]
    

    这样您可以删除stopwordsempty rows 并使用min_dfmax_df

    【讨论】:

    • 这是我现在的方法,使用我自己的tokenizer,但是如果在删除停用词后没有任何内容,这并没有删除空文档。
    • 应用此函数后,您可以对 tfidf 行值求和,如果它们为零,则删除它们。 (脚本更新)
    【解决方案2】:

    你可以:

    1. 指定你的sopwords,然后在TfidfVecorizer之后
    2. 过滤掉空行

    以下代码 sn-p 显示了一个简化的示例,该示例应为您指明正确的方向:

    from sklearn.feature_extraction.text import TfidfVectorizer
    corpus = ["aa ab","aa ab ac"]
    stop_words = ["aa","ab"]
    
    tfidf = TfidfVectorizer(stop_words=stop_words)
    corpus_tfidf = tfidf.fit_transform(corpus)
    idx = np.array(corpus_tfidf.sum(axis=1)==0).ravel()
    corpus_filtered = corpus_tfidf[~idx]
    

    如果您还有任何问题,请随时提出问题!

    【讨论】:

      猜你喜欢
      • 2018-08-07
      • 2013-11-14
      • 2021-03-09
      • 2018-09-19
      • 1970-01-01
      • 2014-01-22
      • 2015-07-14
      • 2019-08-11
      相关资源
      最近更新 更多