是的,您需要提供自己的分析器函数,该函数将根据您的需求将文档转换为特征。
根据
文档所述:
analyzer : string, {‘word’, ‘char’, ‘char_wb’} or callable
....
....
If a callable is passed it is used to extract the sequence of
features out of the raw, unprocessed input.
在自定义的可调用函数中,您需要先将句子分成不同部分,去除逗号、括号、符号等特殊字符,将它们转换为小写,然后转换为
n_grams
。
默认实现按以下顺序处理单个句子:
- 解码:根据给定编码(默认为'utf-8')解码句子。
- 预处理:将句子转换为小写。
- 分词:从句子中获取单个单词标记(默认正则表达式选择2个或多个字母数字字符的标记)。
- 去停用词:删除前一步中出现在停用词中的单个单词标记。
- N_gram生成:在去掉停用词后,剩余的标记将按所需的n_grams排列。
- 删除过于稀有或过于普遍的特征:删除频率大于
max_df
或小于min_df
的单词。
如果要将自定义可调用函数传递给TfidfVectorizer中的
analyzer
参数,则需要处理所有这些内容。
或者
您可以扩展TfidfVectorizer类,并仅覆盖最后2个步骤。像这样:
from sklearn.feature_extraction.text import TfidfVectorizer
class NewTfidfVectorizer(TfidfVectorizer):
def _word_ngrams(self, tokens, stop_words=None):
tokens = super(TfidfVectorizer, self)._word_ngrams(tokens, None)
if stop_words is not None:
new_tokens=[]
for token in tokens:
split_words = token.split(' ')
if split_words[0] not in stop_words and split_words[-1] not in stop_words:
new_tokens.append(token)
return new_tokens
return tokens
然后,像这样使用它:
vectorizer = NewTfidfVectorizer(stop_words='english', ngram_range=(3,3))
vectorizer.fit(data)