繁体   English   中英

使用sklearn查找文档中特定单词的tf-idf分数

[英]Find the tf-idf score of specific words in documents using sklearn

我有在文档集合上运行基本 TF-IDF 向量化器的代码,返回 DXF 的稀疏矩阵,其中 D 是文档数,F 是术语数。 没问题。

但是如何找到文档中特定术语的 TF-IDF 分数呢? 即术语(在它们的文本表示中)和它们在生成的稀疏矩阵中的位置之间是否存在某种字典?

是的。 在您的拟合/转换 TF-IDF 向量化.vocabulary_上查看.vocabulary_

In [1]: from sklearn.datasets import fetch_20newsgroups

In [2]: data = fetch_20newsgroups(categories=['rec.autos'])

In [3]: from sklearn.feature_extraction.text import TfidfVectorizer

In [4]: cv = TfidfVectorizer()

In [5]: X = cv.fit_transform(data.data)

In [6]: cv.vocabulary_

它是以下形式的字典:

{word : column index in array}

这是另一种使用CountVectorizerTfidfTransformer解决方案,用于查找给定单词的Tfidf分数:

from sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer
# our corpus
data = ['I like dog', 'I love cat', 'I interested in cat']

cv = CountVectorizer()

# convert text data into term-frequency matrix
data = cv.fit_transform(data)

tfidf_transformer = TfidfTransformer()

# convert term-frequency matrix into tf-idf
tfidf_matrix = tfidf_transformer.fit_transform(data)

# create dictionary to find a tfidf word each word
word2tfidf = dict(zip(cv.get_feature_names(), tfidf_transformer.idf_))

for word, score in word2tfidf.items():
    print(word, score)

输出

(u'love', 1.6931471805599454)
(u'like', 1.6931471805599454)
(u'i', 1.0)
(u'dog', 1.6931471805599454)
(u'cat', 1.2876820724517808)
(u'interested', 1.6931471805599454)
(u'in', 1.6931471805599454)

@kinkajou,不,TF 和 IDF 不一样,但它们属于同一个算法——TF-IDF,即词频逆文档频率

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM