python - Scikit Learn K-means Clustering & TfidfVectorizer:如何将具有最高 tf-idf 分数的前 n 项传递给 k-means
问题描述
我正在基于 TFIDF 矢量化器对文本数据进行聚类。代码工作正常。它将整个 TFIDF 矢量化器输出作为 K-Means 聚类的输入并生成散点图。相反,我想只发送基于 TF-IDF 分数的前 n 项作为 k-means 聚类的输入。有没有办法做到这一点?
vect = TfidfVectorizer(ngram_range=(1,3),stop_words='english')
tfidf_matrix = vect.fit_transform(df_doc_wholetext['csv_text'])
'''create k-means model with custom config '''
clustering_model = KMeans(
n_clusters=num_clusters,
max_iter=max_iterations,
precompute_distances="auto",
n_jobs=-1
)
labels = clustering_model.fit_predict(tfidf_matrix)
x = tfidf_matrix.todense()
reduced_data = PCA(n_components=pca_num_components).fit_transform(x)
fig, ax = plt.subplots()
for index, instance in enumerate(reduced_data):
pca_comp_1, pca_comp_2 = reduced_data[index]
color = labels_color_map[labels[index]]
ax.scatter(pca_comp_1,pca_comp_2, c = color)
plt.show()
解决方案
在 TfidfVectorizer 中使用 max_features 来考虑前 n 个特征
vect = TfidfVectorizer(ngram_range=(1,3),stop_words='english', max_features=n)
根据 scikit-learn 的文档,max_features 采用 int 或 None 的值(默认值=None)。如果不是 None,TfidfVectorizer 会构建一个词汇表,它只考虑在整个语料库中按词频排序的最高 max_features。
这是链接
推荐阅读
- javascript - 为什么我在使用 Array concat 时不断收到 TypeScript 错误“没有重载匹配此调用”?
- microservices - 为什么大多数无状态微服务的图表在服务内部都有数据库,而有状态微服务有外部数据库?
- java - SpringBoot 找不到 IntelliJ
- java - IntelliJ - 方法引用可能会改变语义
- sql-server - 从 SQL Server 数据库生成 REST API
- javascript - 如何使用限制方法?电报机器人
- git - 如何将旧版本存储库中的 zip 文件中的代码与最新版本合并?
- pusher - Lighthouse Graphql 订阅身份验证返回 403(subscriberByChannel() 返回空)
- python - 谷歌 colab 中的 Pandas 分析错误
- java - java.lang.IllegalStateException:在easymock的记录状态中不允许调用verify