Sklearn tfidfvectorizer删除包含所有停止字的文档



我正在使用 sklearn s TfIdfVectorizer矢量化我的语料库。在我的分析中,有一些文档由于包含所有停止词而过滤所有术语。为了减少稀疏性问题,并且由于将它们包括在分析中是毫无意义的,所以我想将其删除。

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

有什么更好的方法可以实现我要寻找的东西(即删除/忽略包含所有停止字的文档)?

任何帮助将不胜感激。

您可以:

  1. 指定您的sopword,然后在TfidfVecorizer之后
  2. 过滤空排

以下代码片段显示了一个简化的示例,该示例应该使您朝正确的方向设置:

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]

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

因此,您可以使用此信息:

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