【发布时间】:2016-05-10 10:46:34
【问题描述】:
这是一个简单的 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()
【问题讨论】:
-
您已经使用
idx, _ = vq(data, centroids)将点分配给集群。idx中的每个元素要么是 0,对应于centroids[0],要么是 1,对应于centroids[1]。这不是你要找的吗? -
我的问题是如何获取质心[0] 和质心[1] 中的项目标签。
-
我不明白你所说的“标签”是什么意思。也许您想要集群 0、集群 1 等中所有元素的索引?在这种情况下,您可以使用
in_0 = np.where(idx == 0)[0]、in_1 = np.where(idx == 1)[0]等。 -
感谢您的回答。
where(idx ==1)每次运行程序时都会给出不同的索引。 (我的场景中有超过 2 个集群)。是不是因为 cluster[0] 每次都不一样?
标签: python numpy scipy cluster-analysis k-means