在 Python 中确定 Kmeans 后的簇大小

Determining the size of cluster after Kmeans in Python

所以我已经在python中成功找到了kmeans算法所需的最佳簇数,但是现在我如何才能找到在[=16]中应用Kmeans后得到的簇的确切大小=]?

这是一个代码片段

data=np.vstack(zip(simpleassetid_arr,simpleuidarr))
centroids,_ = kmeans(data,round(math.sqrt(len(uidarr)/2)))
idx,_ = vq(data,centroids)

initial = [cluster.vq.kmeans(data,i) for i in range(1,10)]
var=[var for (cent,var) in initial] #to determine the optimal number of k   using elbow test
num_k=int(raw_input("Enter the number of clusters: "))

cent, var = initial[num_k-1]

assignment,cdist = cluster.vq.vq(data,cent)

您可以使用此方法获取簇大小:

print np.bincount(idx)

对于下面的示例,np.bincount(idx) 输出两个元素的数组,例如[ 156 144]

from numpy import vstack,array
import numpy as np
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)

#Print number of elements per cluster
print np.bincount(idx)