在 python 中使用 k 均值聚类提取质心?
Extracting centroids using k-means clustering in python?
我在一维数组中有一些数据,形状为 [1000,],其中包含 1000 个元素。我对这个数据应用了 k-means 聚类,聚类数为 10。应用 k-means 后,我得到了每个簇的形状 [1000,] 和形状 [10,] 的质心的簇标签 (id's)。 labels 数组为 1000 个元素中的每一个分配 0 到 9 之间的值。但是,我希望每个元素都显示其质心而不是其簇 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。
只需使用 centroids
数组作为查找 table:
samplesCentroids = centroids[labels]
似乎列表理解会很有效。
centroid_labels = [centroids[i] for i in labels]
我在一维数组中有一些数据,形状为 [1000,],其中包含 1000 个元素。我对这个数据应用了 k-means 聚类,聚类数为 10。应用 k-means 后,我得到了每个簇的形状 [1000,] 和形状 [10,] 的质心的簇标签 (id's)。 labels 数组为 1000 个元素中的每一个分配 0 到 9 之间的值。但是,我希望每个元素都显示其质心而不是其簇 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。
只需使用 centroids
数组作为查找 table:
samplesCentroids = centroids[labels]
似乎列表理解会很有效。
centroid_labels = [centroids[i] for i in labels]