scikit-learn - TfidfVectorizer 中“max_features”的用途是什么
问题描述
我从中了解到的是,如果 max_feature = n; 这意味着它是根据 Tf-Idf 值选择前 n 个 Feature。我浏览了 scikit-learn 上的 TfidfVectorizer 文档,但没有正确理解。
解决方案
如果您想要具有最高 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])
推荐阅读
- react-native - 使用 props 控制 modal
- google-cast - 需要开发chromecast内置设备的教程
- c# - 是否可以限制ac#winforms应用程序的内存访问
- webpack - style-loader 如何与 css-loader 一起使用?
- c# - 如何使用正则表达式匹配路由部分中的部分url?WebAPI .NET 核心 2.2
- jquery - 在实现 symfony 表单集合示例时,表单没有嵌入原型,以防一次呈现整个表单
- asynchronous - 重启异步协程,不等待其他协程完成
- jquery - 如何在ajax中选择特定对象?
- jquery - 在 django 中,如何在 ajax 中获取详细的错误信息?
- swift - 我可以在 swift 中几乎等于的基础上比较两个字节值吗