【问题标题】:Finding the indices of all points corresponding to a particular centroid using kmeans clustering使用 kmeans 聚类查找与特定质心相对应的所有点的索引
【发布时间】: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


【解决方案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]

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

【讨论】:

    【解决方案2】:

    你已经有了...

    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] 包含什么。

    【讨论】:

    • 我不是在寻找正在绘制的值(或坐标)。我正在寻找一种方法来获取集群 [1] 和集群 [0] 中的标签
    猜你喜欢
    • 2021-10-01
    • 2016-11-16
    • 2018-08-12
    • 2011-05-22
    • 2015-03-06
    • 2020-05-03
    • 2013-04-23
    • 2020-09-10
    • 2020-05-13
    相关资源
    最近更新 更多