如何获取单词的TF-IDF分数?

4

我有一个大语料库(约400k个唯一的句子)。我只想得到每个单词的TF-IDF分数。我尝试通过扫描每个单词并计算频率来计算每个单词的分数,但这太耗时了。

我使用了:

  X= tfidfVectorizer(corpus)

我想知道如何在sklearn中获取语料库中每个单词的TF-IDF得分,因为它直接返回句子的向量表示。


2
TF-IDF不是针对整个语料库的每个单词,而是针对每个文档的每个单词,因此您无法获得语料库中每个唯一单词的值。另外,您能否准确地展示您如何使用“TfidfVectorizer”? - iz_
这正是我所需要的。每个文档/语料库的单词得分。@Tomothy32 - Bharath kumar k
请问您能再讲一下您如何使用TfidfVectorizer吗? - iz_
这与我之前评论的方式相同。语料库=列表(文档中的句子)。但它返回每个句子的唯一向量表示。但是,您不知道每个单词针对文档的确切分数。 - Bharath kumar k
使用 vectorizer.get_feature_names()vectorizer.idf_ 获取每个单词的分数。请参考文档 - Sociopath
@AkshayNevrekar 用户需要的是TF-IDF,而不仅仅是IDF。 - iz_
2个回答

28

要使用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]]

这个2D数组中的每一行都是一个文档,而行中的每个元素都指代相应单词的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']
因此,您可以按以下方式将分数映射到单词:
dict(zip(vectorizer.get_feature_names(), X.toarray()[0]))
{'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}

2
在你最后的代码片段中,为什么要将语料库中第一句话的向量映射到 vectorizer.get_feature_names() 上?后者只是返回用于构建向量空间的所有唯一标记。 - Chingiz K.

1
正如评论者所指出的,给出的答案是错误的。以下方法按标记获取稀疏数组的总和。
# initialise vectoriser
tfidf = TfidfVectorizer()
# apply to corpus of documents
X = tfidf.fit_transform(docs)  
# map feature names to sum of vector array
tfidf_dict = dict(zip(tfidf.get_feature_names_out(), X.toarray().sum(axis=0)))
# sort in descending order
tfidf_dict = dict(sorted(tfidf_dict.items(), key=lambda x: x[1], reverse=True))

然后,您可以选择将其显示为Pandas数据框...
# initialise dataframe
tfidf_df = pd.DataFrame.from_dict(tfidf_dict, orient='index', columns=['tfidf'])
# name the index
tfidf_df.index = tfidf_df.index.rename('token')
# display first 5 rows
tfidf_df.head()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接