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 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
 [1 ,0 ,1, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0 ,0 ,0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 1, 0, 0, 0, 0]] 

我使用scikitlearn的KMeans算法来形成集群,但我需要一种可视化这些集群的方法。 这里是我的k-means代码

cl= KMeans(n_clusters=4)
cl.fit(d)
cen = cl.cluster_centers_
lab=cl.labels_

我知道如何使用matplot绘制简单的图形但我从未习惯过多维。我想绘制d然后绘制cluster_centers(质心) 情节应该是这样的 enter image description here 是否有任何打击可以帮助我完成这项任务?

1 个答案:

答案 0 :(得分:2)

正如@Mahdi所说,你必须使用一些dimensionality reduction才能在二维屏幕上绘制高维空间中的点。 (当然,您将丢失一些信息,但这是不可避免的。)以下是如何使用PCA进行操作的示例(但是,有不同的技术,请查看上面的参考资料)。

from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import matplotlib.pyplot as plt
%matplotlib inline

# d = ... (the same as in the question)

n_clusters = 4
cl= KMeans(n_clusters=n_clusters)
cl.fit(d)
cen = cl.cluster_centers_
lab=cl.labels_

pca = PCA(2)
# reduce dimension to 2

coords = pca.fit_transform(d)

plt.scatter(coords[:, 0], coords[:, 1], 20, c=lab, cmap='spring')
centroids_transformed = pca.transform(cen)
# transform centroids coordinate to new space

plt.scatter(centroids_transformed[:, 0], centroids_transformed[:, 1], 60,
            c=range(n_clusters), cmap='spring', marker='v')
# plot centroids. they are presented in the same order as labels,
# so colors are just range

enter image description here