首页 > 解决方案 > TfidfVectorizer 中“max_features”的用途是什么

问题描述

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

标签: scikit-learntfidfvectorizer

解决方案


如果您想要具有最高 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])

推荐阅读