首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在sklearn的TfidfVectorizer中添加单词到stop_words列表

在sklearn的TfidfVectorizer中添加单词到stop_words列表
EN

Stack Overflow用户
提问于 2014-11-09 15:24:49
回答 3查看 40.7K关注 0票数 22

我想向TfidfVectorizer中的stop_words再添加几个单词。我遵循了Adding words to scikit-learn's CountVectorizer's stop list中的解决方案。我的停用词列表现在包含'english‘停用词和我指定的停用词。但TfidfVectorizer仍然不接受我的停用词列表,我仍然可以在我的功能列表中看到这些词。下面是我的代码

代码语言:javascript
运行
复制
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。但它仍然不起作用。请帮帮忙。

EN

回答 3

Stack Overflow用户

发布于 2017-07-14 14:30:04

你可以这样做:

代码语言:javascript
运行
复制
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向量:

代码语言:javascript
运行
复制
"This is a green apple."
"This is a machine learning book."

默认情况下,thisisaan都在ENGLISH_STOP_WORDS列表中。而且,我还将book添加到了停用词列表中。这是输出:

代码语言:javascript
运行
复制
(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确实接受手动添加的单词作为停用词,并在创建向量时忽略该单词。

票数 20
EN

Stack Overflow用户

发布于 2017-02-01 22:06:24

答案在这里:https://stackoverflow.com/a/24386751/732396

即使sklearn.feature_extraction.text.ENGLISH_STOP_WORDS是一个冻结集,您也可以复制它并添加您自己的单词,然后将该变量作为列表传递给stop_words参数。

票数 4
EN

Stack Overflow用户

发布于 2020-03-10 07:54:34

为了配合scikit-learn使用,你也可以使用一个列表:

代码语言:javascript
运行
复制
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的参数时将其转换回来的原因

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26826002

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档