【问题标题】:What is the use of 'max_features' in TfidfVectorizerTfidfVectorizer 中“max_features”的用途是什么
【发布时间】:2018-12-14 10:55:48
【问题描述】:

我从中了解到的是,如果 max_feature = n;这意味着它是根据 Tf-Idf 值选择前 n 个 Feature。我浏览了 scikit-learn 上的 TfidfVectorizer 文档,但没有正确理解。

【问题讨论】:

  • 不,它根据计数(语料库中的词频)选择前 n 个特征,而不是 tfidf
  • 我想根据 tfidf 值选择整个语料库中的前 n 个特征
  • Tfidf 将取决于每个文档的单词。是否要使用 idf 值对其进行排序?
  • 不,我想要每行中基于 'tf-idf' 值的前 n 个单词。

标签: scikit-learn tfidfvectorizer


【解决方案1】:

如果您想要具有最高 tfidf 值的逐行单词,那么您需要从 Vectorizer 访问转换后的 tf-idf 矩阵,逐行(逐个文档)访问它,然后对值进行排序以获得这些值。

类似这样的:

# TfidfVectorizer will by default output a sparse matrix
tfidf_data = tfidf_vectorizer.fit_transform(text_data).tocsr()
vocab = np.array(tfidf_vectorizer.get_feature_names())

# Replace this with the number of top words you want to get in each row
top_n_words = 5

# Loop all the docs present
for i in range(tfidf_data.shape[0]):
    doc = tfidf_data.getrow(i).toarray().ravel()
    sorted_index = np.argsort(doc)[::-1][:top_n_words]
    print(sorted_index)
    for word, tfidf in zip(vocab[sorted_index], doc[sorted_index]):
        print("%s - %f" %(word, tfidf))

如果可以使用pandas,那么逻辑就变得简单了:

for i in range(tfidf_data.shape[0]):
    doc_data = pd.DataFrame({'Tfidf':tfidf_data.getrow(i).toarray().ravel(),
                             'Word': vocab})
    doc_data.sort_values(by='Tfidf', ascending=False, inplace=True)
    print(doc_data.iloc[:top_n_words])

【讨论】:

  • doc_data = pd.DataFrame({'Tfidf':tfidf_data.getrow(i).toarray().ravel(), 'Word': vocab}) 。这给出了错误,“系列”对象没有属性“getrow”
  • @Dheerajkhanna 您是否已经将 tfidf 数据转换为数据框或系列?
  • 是的,我已经将 tfidf 数据转换为数据框,然后我使用 Selectkbest 来获得前 n 个特征。
猜你喜欢
  • 2019-03-06
  • 2012-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 2011-12-17
  • 2010-11-21
相关资源
最近更新 更多