当前位置: 首页 > 面试题库 >

Scikit学习TfidfVectorizer:如何获得tf-idf得分最高的前n个词

慕容宇
2023-03-14
问题内容

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

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个术语?


问题答案:

您必须做一点点的歌舞才能将矩阵转换为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仅当您一次测试一个文档时,包含to的调用才起作用。

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



 类似资料:
  • 问题内容: 我有下表 在这里,我有一个“学生”表,我想 从该学生表中获取从每个学科获得满分的学生的姓名,例如以下输出。 问题答案: 您可以使用ROW_NUMBER函数仅返回每个主题的“最佳”行: SQL小提琴 MS SQL Server 2008架构设置 : 查询1 : 结果 :

  • 我有下表 在这里,我有一个“学生”表,我想 从学生表中获取每个科目的最大分数的学生的姓名,如以下输出。

  • 问题内容: 假设我有这样的pandas DataFrame: 我想获得一个新的DataFrame,其中每个ID的前2个记录如下: 我可以对分组依据中的记录进行编号: 但是,有没有更有效/更优雅的方法来做到这一点?还有一种更优雅的方法来对每个组中的数字进行记录(例如SQL窗口函数row_number())。 问题答案: 你试过了吗 Ouput生成: (请记住,根据数据,你可能需要先进行订购/排序)

  • 我正在使用Javascript(ES6)/FacebookReact,并尝试获得大小不同的数组的前3个元素。我想做与Linq take(n)等价的操作。 在我的Jsx文件中,我有以下内容: 然后我尝试了前3个项目 这不起作用,因为地图没有一个设置的函数。 你能帮忙吗?

  • TF-IDF TF-IDF(Term Frequency and Inverse Document Frequency),是一种用于信息检索与数据挖掘的常用加权技术。它的主要思想是:如果某个词或短语在一篇文章中出现的频率(term frequency)高,并且在其他文章中很少出现,则认为此词或者短语具有很好的类别区分能力,适合用来分类。 计算公式是TF * IDF 而这里的: scikit-lea