【问题标题】:Extracting centroids using k-means clustering in python?在python中使用k-means聚类提取质心?
【发布时间】:2018-04-27 17:03:55
【问题描述】:

我在一个形状为 [1000,] 的一维数组中有一些数据,其中包含 1000 个元素。我对这些数据应用了 k-means 聚类,聚类数为 10。应用 k-means 后,我得到了每个簇的形状为 [1000,] 和形状为 [10,] 的簇标签(id)。标签数组将 0 到 9 之间的值分配给 1000 个元素中的每一个。但是,我希望每个元素都显示其质心而不是其集群 ID。我怎样才能做到这一点?

from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=10)
kmeans.fit(data)   #data is of shape [1000,]
#learn the labels and the means
labels = kmeans.predict(data)  #labels of shape [1000,] with values 0<= i <= 9
centroids  = kmeans.cluster_centers_  #means of shape [10,] 

在上面的代码中,我想要 [1000,] 数组中每个元素的各自质心,而不是其集群 ID。

【问题讨论】:

    标签: python arrays scikit-learn cluster-analysis k-means


    【解决方案1】:

    似乎列表理解会很好用。

    centroid_labels = [centroids[i] for i in labels]
    

    【讨论】:

      【解决方案2】:

      只需使用centroids 数组作为查找表:

      samplesCentroids = centroids[labels]
      

      【讨论】:

        猜你喜欢
        • 2020-02-21
        • 2018-09-19
        • 1970-01-01
        • 2018-05-09
        • 2022-01-23
        • 2021-11-25
        • 2016-05-29
        • 2019-02-03
        • 2018-02-14
        相关资源
        最近更新 更多