草庐IT

python - sklearn : TFIDF Transformer : How to get tf-idf values of given words in document

coder 2023-05-25 原文

我使用 sklearn 使用以下命令计算文档的 TFIDF(词频逆文档频率)值:

from sklearn.feature_extraction.text import CountVectorizer
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(documents)
from sklearn.feature_extraction.text import TfidfTransformer
tf_transformer = TfidfTransformer(use_idf=False).fit(X_train_counts)
X_train_tf = tf_transformer.transform(X_train_counts)

X_train_tf 是形状为 (2257, 35788)scipy.sparse 矩阵。

如何获取特定文档中单词的 TF-IDF?更具体地说,如何获取给定文档中具有最大 TF-IDF 值的单词?

最佳答案

您可以使用来自 sklean 的 TfidfVectorizer

from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from scipy.sparse.csr import csr_matrix #need this if you want to save tfidf_matrix

tf = TfidfVectorizer(input='filename', analyzer='word', ngram_range=(1,6),
                     min_df = 0, stop_words = 'english', sublinear_tf=True)
tfidf_matrix =  tf.fit_transform(corpus)

上面的tfidf_matix有语料库中所有文档的TF-IDF值。这是一个大的稀疏矩阵。现在,

feature_names = tf.get_feature_names()

这会为您提供所有标记或 n-gram 或单词的列表。 对于语料库中的第一个文档,

doc = 0
feature_index = tfidf_matrix[doc,:].nonzero()[1]
tfidf_scores = zip(feature_index, [tfidf_matrix[doc, x] for x in feature_index])

让我们打印出来,

for w, s in [(feature_names[i], s) for (i, s) in tfidf_scores]:
  print w, s

关于python - sklearn : TFIDF Transformer : How to get tf-idf values of given words in document,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34449127/

有关python - sklearn : TFIDF Transformer : How to get tf-idf values of given words in document的更多相关文章

随机推荐