以下是我的代码:
sklearn_tfidf = TfidfVectorizer(ngram_range= (3,3),stop_words=stopwordslist, norm='l2',min_df=0, use_idf=True, smooth_idf=False, sublinear_tf=True)
sklearn_representation = sklearn_tfidf.fit_transform(documents)
它通过删除所有的停用词来生成三元组。
我希望它允许那些TRIGRAM在中间有什么禁止词(不是在开始和结束)
是否需要为此编写处理器。需要建议。
是的,您需要提供自己的分析器功能,根据您的要求将文档转换为功能。
analyzer:string,{'word','char','char_wb'}或callable
.... .... If a callable is passed it is used to extract the sequence of features out of the raw, unprocessed input.
在那个自定义callable中你需要先处理将句子拆分成不同的部分,删除逗号,大括号,符号等特殊字符,将它们转换为小写,然后将它们转换为n_grams
。
默认实现按以下顺序对单个句子起作用:
max_df
或低于min_df
的单词。如果要将自定义callable传递给TfidfVectorizer中的analyzer
param,则需要处理所有这些。
要么
您可以扩展TfidfVectorizer类,仅覆盖最后两个步骤。像这样的东西:
from sklearn.feature_extraction.text import TfidfVectorizer
class NewTfidfVectorizer(TfidfVectorizer):
def _word_ngrams(self, tokens, stop_words=None):
# First get tokens without stop words
tokens = super(TfidfVectorizer, self)._word_ngrams(tokens, None)
if stop_words is not None:
new_tokens=[]
for token in tokens:
split_words = token.split(' ')
# Only check the first and last word for stop words
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)