如何使用 TF-IDF Vector 选择前 1000 个单词?

mer*_*kle 5 tf-idf python-3.x scikit-learn sklearn-pandas tfidfvectorizer

我有一个有 5000 条评论的文档。我对该文档应用了 tf-idf 。这里的sample_data包含5000条评论。我正在对具有一克范围的sample_data应用tf-idf向量化器。现在我想从样本数据中获取具有最高 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)
Run Code Online (Sandbox Code Playgroud)

Viv*_*mar 5

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

做就是了:

tf_idf_vect = TfidfVectorizer(ngram_range=(1,1), max_features=1000)
Run Code Online (Sandbox Code Playgroud)

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

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

  The learned idf vector (global term weights) when use_idf is set to True,  
Run Code Online (Sandbox Code Playgroud)

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

idf = tf_idf_vect.idf_
Run Code Online (Sandbox Code Playgroud)

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

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