sklearn:TFIDF Transformer:如何获取文档中给定单词的tf-idf值

时间:2015-12-24 07:43:56

标签: python scikit-learn

我使用 sklean 使用命令

计算文档中术语的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是形状为scipy.sparse的{​​{1}}矩阵。

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

3 个答案:

答案 0 :(得分:47)

您可以使用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

答案 1 :(得分:5)

这是带有熊猫库的Python 3中另一个更简单的解决方案

from sklearn.feature_extraction.text import TfidfVectorizer
import pandas as pd

vect = TfidfVectorizer()
tfidf_matrix = vect.fit_transform(documents)
df = pd.DataFrame(tfidf_matrix.toarray(), columns = vect.get_feature_names())
print(df)

答案 2 :(得分:0)

查找句子中每个单词的tfidf分数有助于完成下游任务,例如搜索和语义匹配。

我们可以得到字典,其中单词作为关键字,tfidf_score作为值。

from sklearn.feature_extraction.text import TfidfVectorizer

tfidf = TfidfVectorizer(min_df=3)
tfidf.fit(list(subject_sentences.values()))
feature_names = tfidf.get_feature_names()

现在我们可以像这样编写转换逻辑

def get_ifidf_for_words(text):
    tfidf_matrix= tfidf.transform([text]).todense()
    feature_index = tfidf_matrix[0,:].nonzero()[1]
    tfidf_scores = zip([feature_names[i] for i in feature_index], [tfidf_matrix[0, x] for x in feature_index])
    return dict(tfidf_scores)

例如输入

text = "increase post character limit"
get_ifidf_for_words(text)

输出应为

{
'character': 0.5478868741621505,
'increase': 0.5487092618866405,
'limit': 0.5329156819959756,
'post': 0.33873144956352985
}