如何使用k均值绘制推文数据集的聚类



我有一个包含推文的数据集,在预处理推文后,我尝试对它们进行聚类:

# output the result to a text file.
clusters = df.groupby('cluster')    
for cluster in clusters.groups:
f = open('cluster'+str(cluster)+ '.csv', 'w') # create csv file
data = clusters.get_group(cluster)[['id','Tweets']] # get id and tweets columns
f.write(data.to_csv(index_label='id')) # set index to id
f.close()

print("Cluster centroids: n")
order_centroids = model.cluster_centers_.argsort()[:, ::-1]
terms = vectorizer.get_feature_names()
for i in range(k):
print("Cluster %d:" % i)
for j in order_centroids[i, :10]: #print out 10 feature terms of each cluster
print (' %s' % terms[j])
print('------------')

因此,它将我的推文分为6组。如何将它们作为一个整体绘制在2D中?

首先,如果您使用Kmeans聚类算法,您总是手动指定聚类的数量,所以您可以简单地将其设置为2。

但是,如果你以某种方式(肘部方法、轮廓分数或其他什么(决定6个聚类比2个更好,你应该对你的特征使用一些降维(sklearn的PCA、TSNE等(,然后用聚类对应的点颜色对它们进行散点绘制。这看起来像这样:

from sklear.decomposition import PCA
import matplotlib.pyplot as plt
pca = PCA(n_components=2, svd_solver='full')
X_decomposed = pca.fit_transform(X)
plt.scatter(X_decomposed[0], X_decomposed[1], c=clustering)

最新更新