Scikit Learn TfidfVectorizer:如何获得具有最高tf-idf分数的前n个术语

Abt*_*Pst 28 python nlp nltk tf-idf scikit-learn

我正在研究关键字提取问题.考虑一般情况

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])
Run Code Online (Sandbox Code Playgroud)

这给了我

  (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
Run Code Online (Sandbox Code Playgroud)

这很好.对于任何新文档,有没有办法获得最高tfidf得分的前n项?

hum*_*ume 31

你必须做一些歌曲和舞蹈,以使矩阵成为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]
Run Code Online (Sandbox Code Playgroud)

这给了我:

array([u'fruit', u'travellers', u'jupiter'], 
  dtype='<U13')
Run Code Online (Sandbox Code Playgroud)

这个argsort电话真的是有用的,这里是它的文档.我们必须这样做,[::-1]因为argsort只支持从小到大的排序.我们调用flatten将尺寸减小到1d,以便排序的索引可用于索引1d特征数组.请注意,包含调用flatten仅在您一次测试一个文档时才有效.

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

  • 我根本没有研究过这一点,但是将 tfidf.get_feature_names() 转换为 numpy.array 使用的内存比默认的 Python 列表要多得多。当我在 get_feature_names() 上调用 numpy.array 时,我的 300mb TFIDF 模型在 RAM 中变成了 4+ Gb,而仅使用 feature_array = tfidf.get_feature_names() 就可以正常工作并且使用很少的 RAM。 (2认同)

Ven*_*lam 11

使用稀疏矩阵本身的解决方案(没有.toarray())!

import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer

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')]
Run Code Online (Sandbox Code Playgroud)

  • 它还返回重复的单词,当我尝试再次使用这些前 n 个单词作为 tfidfvectorizer 中的词汇表时,它会抛出错误,因为词汇表中存在重复的单词。我如何获得前 n 个独特的单词? (2认同)