2012-02-20 183 views
9

我正在使用SciPy的层次聚集聚类方法来聚类m×n个要素矩阵,但聚类完成后,我似乎无法弄清楚如何从所得到的聚类中获取质心。下面如下我的代码:如何从SciPy的层次凝聚聚类中获取质心?

Y = distance.pdist(features) 
Z = hierarchy.linkage(Y, method = "average", metric = "euclidean") 
T = hierarchy.fcluster(Z, 100, criterion = "maxclust") 

我以我的特点矩阵,计算它们之间的欧氏距离,然后将它们传递到层次聚类方法。从那里开始,我创建了平面集群,最多有100个集群

现在,基于平面集群T,如何获得表示每个平面集群的1 x n质心?

+1

那么,到底发生了什么?你解决了这个问题吗?怎么样? – 2013-09-24 05:05:28

+0

我实际上最终使用了scikit-learn。 – 2013-09-27 12:42:33

+0

scikit pleasE中的哪个函数? – 2013-09-28 02:21:39

回答

0

你可以做这样的事情(维D =号):

# Sum the vectors in each cluster 
lens = {}  # will contain the lengths for each cluster 
centroids = {} # will contain the centroids of each cluster 
for idx,clno in enumerate(T): 
    centroids.setdefault(clno,np.zeros(D)) 
    centroids[clno] += features[idx,:] 
    lens.setdefault(clno,0) 
    lens[clno] += 1 
# Divide by number of observations in each cluster to get the centroid 
for clno in centroids: 
    centroids[clno] /= float(lens[clno]) 

这将给你一个与簇号作为重点和具体集群的价值重心的字典。

1

一个可能的解决方案是一个函数,该函数返回scipy.cluster.vq中的质心像kmeans那样的码本。你唯一需要的就是分区矢量与平集群part和原始观测X

def to_codebook(X, part): 
    """ 
    Calculates centroids according to flat cluster assignment 

    Parameters 
    ---------- 
    X : array, (n, d) 
     The n original observations with d features 

    part : array, (n) 
     Partition vector. p[n]=c is the cluster assigned to observation n 

    Returns 
    ------- 
    codebook : array, (k, d) 
     Returns a k x d codebook with k centroids 
    """ 
    codebook = [] 

    for i in range(part.min(), part.max()+1): 
     codebook.append(X[part == i].mean(0)) 

    return np.vstack(codebook)