[英]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}
这是另一种使用CountVectorizer
和TfidfTransformer
解决方案,用于查找给定单词的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.