Scikit Learn K-means 聚类和 TfidfVectorizer:如何将 tf-idf 得分最高的前 n 个项传递给 k-means
Scikit Learn K-means Clustering & TfidfVectorizer: How to pass top n terms with highest tf-idf score to k-means
我正在基于 TFIDF 向量化器对文本数据进行聚类。该代码工作正常。它将整个 TFIDF 矢量器输出作为 K-Means 聚类的输入并生成散点图。相反,我只想发送基于 TF-IDF 分数的前 n 项作为 k 均值聚类的输入。有没有办法做到这一点?
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。
这是link
我正在基于 TFIDF 向量化器对文本数据进行聚类。该代码工作正常。它将整个 TFIDF 矢量器输出作为 K-Means 聚类的输入并生成散点图。相反,我只想发送基于 TF-IDF 分数的前 n 项作为 k 均值聚类的输入。有没有办法做到这一点?
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。
这是link