Векторизатор подгоняется на основе совокупности документов, которые вы передаете. Как правило, если вы работаете с большим корпусом документов, вы сначала подгоните векторизатор ко всему корпусу. Это позволяет векторизатору правильно определять частоту терминов в документах и соответствующим образом применять параметры min_df
, max_df
и max_features
. После того, как векторизатор был подогнан, вы можете просто преобразовать документ, чтобы извлечь векторы tfidf. (Этот документ не обязательно должен быть в учебном корпусе)
Например:
from nltk import word_tokenize
from nltk.stem import PorterStemmer
from sklearn.feature_extraction import TfidfVectorizer
class Tokenizer(object):
def __init__(self):
self.stemmer = PorterStemmer()
def __call__(self, doc):
return [self.stemmer.stem(w) for w in word_tokenize(doc)]
tfidf = TfidfVectorizer(stop_words='english', max_features=500, lowercase=True, tokenizer=Tokenizer)
# raw_docs can be collection of documents i.e. list, generator, etc...
raw_docs = ['The quick red fox jumped over the lazy brown dog', 'Carlos made a quick jumping catch in the game last night', 'How much wood would a woodchuck chuck if a woodchuck could chuck wood']
tfidf.fit(raw_docs[:1])
tfidf.vocabulary_
{'quick': 5, 'red': 6, 'fox': 2, 'jump': 3, 'lazi': 4, 'brown': 0, 'dog': 1}
# Notice only the first sentence in vocab
tfidf.transform(raw_docs[1:2]).todense()
matrix([[0. , 0. , 0. , 0.70710678, 0. ,
0.70710678, 0. ]])
#Vectorizing the second sentence only gives scores for 'jump' and 'quick'
tfidf.fit(raw_docs)
tfidf.vocabulary_
{'quick': 10,
'red': 11,
'fox': 5,
'jump': 7,
'lazi': 8,
'brown': 0,
'dog': 4,
'carlo': 1,
'catch': 2,
'game': 6,
'night': 9,
'wood': 12,
'woodchuck': 13,
'chuck': 3}
# Notice terms from each sentence now
matrix([[0. , 0.44036207, 0.44036207, 0. , 0. ,
0. , 0.44036207, 0.3349067 , 0. , 0.44036207,
0.3349067 , 0. , 0. , 0. ]])
# We now have twice the features 14 v 7 and the vector catches each of the terms in the sentence.