2

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

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

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

任何帮助将不胜感激。

4

2 回答 2

2

你可以:

  1. 指定你的sopwords,然后,之后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]

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

于 2019-03-07T10:24:50.497 回答
0

所以,你可以使用这个:

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]

这样您就可以删除stopwords,empty rows并使用min_dfand max_df

于 2019-03-07T10:31:55.477 回答