Для использования sklearn.feature_extraction.text.TfidfVectorizer
(взято из документов):
>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> corpus = [
... 'This is the first document.',
... 'This document is the second document.',
... 'And this is the third one.',
... 'Is this the first document?',
... ]
>>> vectorizer = TfidfVectorizer()
>>> X = vectorizer.fit_transform(corpus)
>>> print(vectorizer.get_feature_names())
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
>>> print(X.shape)
(4, 9)
Теперь, если я напечатаю X.toarray()
:
[[0. 0.46979139 0.58028582 0.38408524 0. 0.
0.38408524 0. 0.38408524]
[0. 0.6876236 0. 0.28108867 0. 0.53864762
0.28108867 0. 0.28108867]
[0.51184851 0. 0. 0.26710379 0.51184851 0.
0.26710379 0.51184851 0.26710379]
[0. 0.46979139 0.58028582 0.38408524 0. 0.
0.38408524 0. 0.38408524]]
Каждая строка в этом двумерном массиве относится к документу, а каждый элемент в строке ссылается на оценку TF-IDF соответствующего слова. Чтобы узнать, какое слово представляет каждый элемент, посмотрите на функцию .get_feature_names()
. Он распечатает список слов. Например, в этом случае посмотрите строку первого документа:
[0., 0.46979139, 0.58028582, 0.38408524, 0., 0., 0.38408524, 0., 0.38408524]
В примере .get_feature_names()
возвращает это:
['and', 'document', 'first', 'is', 'one', 'second', 'the', 'third', 'this']
Таким образом, вы сопоставляете оценки со словами, подобными этим:
{'and': 0.0, 'document': 0.46979139, 'first': 0.58028582, 'is': 0.38408524, 'one': 0.0, 'second': 0.0, 'the': 0.38408524, 'third': 0.0, 'this': 0.38408524}