如何将预处理器传递给TfidfVectorizer? - sklearn - python
我该如何将一个预处理函数传递给TfidfVectorizer?我写了一个函数,它接收一个字符串并返回一个经过处理的字符串。然后我把处理器参数设置为这个函数“preprocessor=preprocess”,但它没有效果。我搜索了很多次,但没有找到任何例子,好像没有人使用它。
我还有另一个问题。这个(预处理器参数)会覆盖使用stop_words和lowercase参数来去除停用词和转换为小写字母的功能吗?
1 个回答
32
你只需要定义一个函数,这个函数接收一个字符串作为输入,然后返回你想要处理的结果。比如说,一个简单的将字符串变成大写的函数可以这样写:
def preProcess(s):
return s.upper()
一旦你写好了这个函数,就可以把它传递给你的 TfidfVectorizer
对象。比如:
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = [
'This is the first document.',
'This is the second second document.',
'And the third one.',
'Is this the first document?'
]
X = TfidfVectorizer(preprocessor=preProcess)
X.fit(corpus)
X.get_feature_names()
这样就会得到:
[u'AND', u'DOCUMENT', u'FIRST', u'IS', u'ONE', u'SECOND', u'THE', u'THIRD', u'THIS']
这也间接回答了你后面的问题,因为即使把小写设置为真,处理函数将字符串变成大写的设置会覆盖这个选项。这一点在文档中也有提到:
preprocessor : 可调用对象或 None(默认) 在保留分词和 n-grams 生成步骤的同时,覆盖预处理(字符串转换)阶段。