【问题标题】:How to get TF-IDF scores for the words?如何获得单词的 TF-IDF 分数?
【发布时间】:2019-04-17 01:57:46
【问题描述】:

我有一个庞大的语料库(大约 40 万个独特的句子)。我只想获得每个单词的 TF-IDF 分数。我试图通过扫描每个单词并计算频率来计算每个单词的分数,但它花费的时间太长。

我用过:

  X= tfidfVectorizer(corpus)

来自 sklearn,但它直接返回句子的向量表示。有什么方法可以得到语料库中每个单词的 TF-IDF 分数?

【问题讨论】:

  • TF-IDF 不是整个语料库中的每个单词,而是每个文档的每个单词,因此您无法获得语料库中每个唯一单词的值。另外,你能具体说明一下你是如何使用TfidfVectorizer的吗?
  • 这正是我所需要的。每个文档/语料库的每个单词的分数。 @Tomothy32
  • 再一次,你能具体说明一下你是如何使用TfidfVectorizer的吗?
  • 和我上面评论的一样。 corpus = list(文档中的句子)。但它返回每个句子的唯一向量表示。但是,您不知道文档中每个单词的确切分数。
  • 使用vectorizer.get_feature_names()vectorizer.idf_ 获取每个单词的分数。参考documentation

标签: python nlp tf-idf tfidfvectorizer


【解决方案1】:

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

因此,您将分数映射到这样的单词:

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}

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 2016-08-07
    • 2021-10-27
    • 2019-11-16
    • 2019-06-12
    • 2019-03-09
    • 2020-05-11
    • 1970-01-01
    • 2020-07-02
    相关资源
    最近更新 更多