首页 > 解决方案 > 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()

标签: pythonscikit-learnk-meanstext-miningtfidfvectorizer

解决方案


在 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。

这是链接


推荐阅读