Scikit学习TfidfVectorizer:如何获得tf-idf得分最高的前n个词
nlp
nltk
python
scikit-learn
5
0

我正在研究关键字提取问题。考虑非常普遍的情况

tfidf = TfidfVectorizer(tokenizer=tokenize, stop_words='english')

t = """Two Travellers, walking in the noonday sun, sought the shade of a widespreading tree to rest. As they lay looking up among the pleasant leaves, they saw that it was a Plane Tree.

"How useless is the Plane!" said one of them. "It bears no fruit whatever, and only serves to litter the ground with leaves."

"Ungrateful creatures!" said a voice from the Plane Tree. "You lie here in my cooling shade, and yet you say I am useless! Thus ungratefully, O Jupiter, do men receive their blessings!"

Our best blessings are often the least appreciated."""

tfs = tfidf.fit_transform(t.split(" "))
str = 'tree cat travellers fruit jupiter'
response = tfidf.transform([str])
feature_names = tfidf.get_feature_names()

for col in response.nonzero()[1]:
    print(feature_names[col], ' - ', response[0, col])

这给了我

  (0, 28)   0.443509712811
  (0, 27)   0.517461475101
  (0, 8)    0.517461475101
  (0, 6)    0.517461475101
tree  -  0.443509712811
travellers  -  0.517461475101
jupiter  -  0.517461475101
fruit  -  0.517461475101

很好对于其中出现的任何新文档,是否有办法获得tfidf得分最高的前n个术语?

参考资料:
Stack Overflow
收藏
评论
共 2 个回答
高赞 时间 活跃

您必须做一点点的歌舞才能将矩阵转换为numpy数组,但这应该可以满足您的需求:

feature_array = np.array(tfidf.get_feature_names())
tfidf_sorting = np.argsort(response.toarray()).flatten()[::-1]

n = 3
top_n = feature_array[tfidf_sorting][:n]

这给了我:

array([u'fruit', u'travellers', u'jupiter'], 
  dtype='<U13')

argsort调用确实是有用的, 这是它的文档 。我们必须执行[::-1]因为argsort仅支持从小到大的排序。我们调用flatten将尺寸减小到1d,以便可以使用排序后的索引来索引1d特征数组。请注意,仅当您一次测试一个文档时,才包括调用flatten

另外,在另一个注释上,您的意思是类似tfs = tfidf.fit_transform(t.split("\n\n"))吗?否则,多行字符串中的每个术语都将被视为“文档”。相反,使用\n\n意味着我们实际上正在查看4个文档(每行一个),这在您考虑tfidf时更有意义。

收藏
评论

解决方案使用稀疏矩阵本身(不带.toarray() )!

tfidf = TfidfVectorizer(stop_words='english')
corpus = [
    'I would like to check this document',
    'How about one more document',
    'Aim is to capture the key words from the corpus',
    'frequency of words in a document is called term frequency'
]

X = tfidf.fit_transform(corpus)
feature_names = np.array(tfidf.get_feature_names())


new_doc = ['can key words in this new document be identified?',
           'idf is the inverse document frequency caculcated for each of the words']
responses = tfidf.transform(new_doc)


def get_top_tf_idf_words(response, top_n=2):
    sorted_nzs = np.argsort(response.data)[:-(top_n+1):-1]
    return feature_names[response.indices[sorted_nzs]]

print([get_top_tf_idf_words(response,2) for response in responses])

#[array(['key', 'words'], dtype='<U9'),
 array(['frequency', 'words'], dtype='<U9')]
收藏
评论
新手导航
  • 社区规范
  • 提出问题
  • 进行投票
  • 个人资料
  • 优化问题
  • 回答问题

关于我们

常见问题

内容许可

联系我们

@2020 AskGo
京ICP备20001863号