Skip to main content
 首页 » 编程设计

python之如何使用 matplotlib 绘制 Kmeans 文本聚类结果

2025年05月04日23daizhj

我有以下代码用 scikit learn 对一些示例文本进行聚类。

train = ["is this good?", "this is bad", "some other text here", "i am hero", "blue jeans", "red carpet", "red dog", "blue sweater", "red hat", "kitty blue"] 
 
vect = TfidfVectorizer() 
X = vect.fit_transform(train) 
clf = KMeans(n_clusters=3) 
clf.fit(X) 
centroids = clf.cluster_centers_ 
 
plt.scatter(centroids[:, 0], centroids[:, 1], marker='x', s=80, linewidths=5) 
plt.show() 

我想不通的是如何绘制聚类结果。 X 是一个 csr_matrix。我想要的是要绘制的每个结果的 (x, y) 坐标。

我

请您参考如下方法:

您的 tf-idf 矩阵最终为 3 x 17,因此您需要进行某种投影或降维以获得二维质心。您有多种选择;这是一个 t-SNE 的例子:

import matplotlib.pyplot as plt 
from sklearn.cluster import KMeans 
from sklearn.feature_extraction.text import TfidfVectorizer 
from sklearn.manifold import TSNE 
 
train = ["is this good?", "this is bad", "some other text here", "i am hero", "blue jeans", "red carpet", "red dog", 
     "blue sweater", "red hat", "kitty blue"] 
 
vect = TfidfVectorizer()   
X = vect.fit_transform(train) 
random_state = 1 
clf = KMeans(n_clusters=3, random_state = random_state) 
data = clf.fit(X) 
centroids = clf.cluster_centers_ 
 
tsne_init = 'pca'  # could also be 'random' 
tsne_perplexity = 20.0 
tsne_early_exaggeration = 4.0 
tsne_learning_rate = 1000 
model = TSNE(n_components=2, random_state=random_state, init=tsne_init, perplexity=tsne_perplexity, 
         early_exaggeration=tsne_early_exaggeration, learning_rate=tsne_learning_rate) 
 
transformed_centroids = model.fit_transform(centroids) 
print transformed_centroids 
plt.scatter(transformed_centroids[:, 0], transformed_centroids[:, 1], marker='x') 
plt.show() 

在您的示例中,如果您使用 PCA 来初始化您的 t-SNE,您将获得间距很大的质心;如果您使用随机初始化,您将得到微小的质心和无趣的图片。