首页 > 解决方案 > 如何使用 TF-IDF 向量选择前 1000 个单词?

问题描述

我有一个包含 5000 条评论的文档。我在该文件上应用了 tf-idf。这里sample_data包含 5000 条评论。我在 sample_data 上应用 tf-idf 矢量化器,范围为一克。现在我想从 sample_data 中获取tf-idf 值最高的前 1000 个单词。谁能告诉我如何获得热门词?

from sklearn.feature_extraction.text import TfidfVectorizer
tf_idf_vect = TfidfVectorizer(ngram_range=(1,1))
tf_idf_vect.fit(sample_data)
final_tf_idf = tf_idf_vect.transform(sample_data)

标签: python-3.xscikit-learntf-idfsklearn-pandastfidfvectorizer

解决方案


TF-IDF 值取决于单个文档。max_features您可以使用TfidfVectorizer的参数根据计数 (Tf) 获得前 1000 个术语:

max_features : int 或 None,默认=None

If not None, build a vocabulary that only consider the top
max_features ordered by term frequency across the corpus.

做就是了:

tf_idf_vect = TfidfVectorizer(ngram_range=(1,1), max_features=1000)

您甚至可以使用属性从文档的后拟合(学习)中获取'idf'(全局术语权重) :tf_idf_vectidf_

idf_ :数组,形状 = [n_features],或无

  The learned idf vector (global term weights) when use_idf is set to True,  

调用后执行此操作tf_idf_vect.fit(sample_data)

idf = tf_idf_vect.idf_

然后从中选择前 1000 个,并根据这些选定的特征重新拟合数据。

但是您不能通过“ tf-idf ”获得前 1000 名,因为 tf-idf 是tf单个文档中的一个术语与idf(全局)词汇表的乘积。因此,对于在单个文档中出现 2 次的同一个词,其 tf-idf 是在另一个文档中只出现一次的同一个词的两倍。您如何比较同一术语的不同值。希望这可以说清楚。


推荐阅读