簡體   English   中英

在Python中使用Kmeans后確定集群的大小

[英]Determining the size of cluster after Kmeans in Python

所以我已經成功找到了python中kmeans算法所需的最佳簇數,但現在我如何才能找到在python中應用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM