使用 kmeans 聚类查找与特定质心对应的所有点的索引

Finding the indices of all points corresponding to a particular centroid using kmeans clustering

这是 kmeans 聚类的简单实现(聚类中的点标记为 1 到 500):

from pylab import plot,show
from numpy import vstack,array
from numpy.random import rand
from scipy.cluster.vq import kmeans,vq

# data generation
data = vstack((rand(150,2) + array([.5,.5]),rand(150,2)))

# computing K-Means with K = 2 (2 clusters)
centroids,_ = kmeans(data,2)
# assign each sample to a cluster
idx,_ = vq(data,centroids)

#ignore this, just labelling each point in cluster
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
plt.annotate(
    label, 
   xy = (x, y), xytext = (-20, 20),
   textcoords = 'offset points', ha = 'right', va = 'bottom',
   bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
   arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

# some plotting using numpy's logical indexing
plot(data[idx==0,0],data[idx==0,1],'ob',
     data[idx==1,0],data[idx==1,1],'or')
plot(centroids[:,0],centroids[:,1],'sg',markersize=8)
show()

我正在尝试查找每个集群中所有点的索引。

你已经有了...

plot(data[idx==0,0],data[idx==0,1],'ob',
     data[idx==1,0],data[idx==1,1],'or')

猜猜 idx 做了什么,以及 data[idx==0]data[idx==1] 包含什么。

这一行:

idx,_ = vq(data,centroids)

您已经为 data 数组中的每个点(行)生成了一个包含最近质心索引的向量。

您似乎想要所有最接近质心 0、质心 1 等的点的行索引。您可以使用 np.nonzero 找到索引 idx == i 其中 i 是您感兴趣的质心。

例如:

in_0 = np.nonzero(idx == 0)[0]
in_1 = np.nonzero(idx == 1)[0]

在评论中,您还询问了为什么 idx 向量在运行中不同。这是因为如果将整数作为第二个参数传递给 kmeans,则质心位置会随机初始化 (see here)。