我想向TfidfVectorizer中的stop_words再添加几个单词。我遵循了Adding words to scikit-learn's CountVectorizer's stop list中的解决方案。我的停用词列表现在包含'english‘停用词和我指定的停用词。但TfidfVectorizer仍然不接受我的停用词列表,我仍然可以在我的功能列表中看到这些词。下面是我的代码
from sklearn.feature_extraction import text
my_stop_words = text.ENGLISH_STOP_WORDS.union(my_words)
vectorizer = TfidfVectorizer(analyzer=u'word',max_df=0.95,lowercase=True,stop_words=set(my_stop_words),max_features=15000)
X= vectorizer.fit_transform(text)
我还尝试将TfidfVectorizer中的stop_words设置为stop_words=my_stop_words。但它仍然不起作用。请帮帮忙。
发布于 2017-07-14 14:30:04
你可以这样做:
from sklearn.feature_extraction import text
from sklearn.feature_extraction.text import TfidfVectorizer
my_stop_words = text.ENGLISH_STOP_WORDS.union(["book"])
vectorizer = TfidfVectorizer(ngram_range=(1,1), stop_words=my_stop_words)
X = vectorizer.fit_transform(["this is an apple.","this is a book."])
idf_values = dict(zip(vectorizer.get_feature_names(), vectorizer.idf_))
# printing the tfidf vectors
print(X)
# printing the vocabulary
print(vectorizer.vocabulary_)
在本例中,我为两个示例文档创建了tfidf向量:
"This is a green apple."
"This is a machine learning book."
默认情况下,this
、is
、a
和an
都在ENGLISH_STOP_WORDS
列表中。而且,我还将book
添加到了停用词列表中。这是输出:
(0, 1) 0.707106781187
(0, 0) 0.707106781187
(1, 3) 0.707106781187
(1, 2) 0.707106781187
{'green': 1, 'machine': 3, 'learning': 2, 'apple': 0}
正如我们所看到的,单词book
也从功能列表中删除,因为我们将其列为停用词。因此,tfidfvectorizer确实接受手动添加的单词作为停用词,并在创建向量时忽略该单词。
发布于 2017-02-01 22:06:24
答案在这里:https://stackoverflow.com/a/24386751/732396
即使sklearn.feature_extraction.text.ENGLISH_STOP_WORDS
是一个冻结集,您也可以复制它并添加您自己的单词,然后将该变量作为列表传递给stop_words
参数。
发布于 2020-03-10 07:54:34
为了配合scikit-learn使用,你也可以使用一个列表:
from nltk.corpus import stopwords
stop = list(stopwords.words('english'))
stop.extend('myword1 myword2 myword3'.split())
vectorizer = TfidfVectorizer(analyzer = 'word',stop_words=set(stop))
vectors = vectorizer.fit_transform(corpus)
...
对于集合,此方法唯一的缺点是列表可能最终包含重复项,这就是为什么我在将其用作TfidfVectorizer
的参数时将其转换回来的原因
https://stackoverflow.com/questions/26826002
复制相似问题