我正在使用SciPy的分层凝聚聚类方法对特征的m x n矩阵进行聚类,但在聚类完成后,我似乎找不出如何从得到的聚类中获得质心。下面是我的代码:
Y = distance.pdist(features)
Z = hierarchy.linkage(Y, method = "average", metric = "euclidean")
T = hierarchy.fcluster(Z, 100, criterion = "maxclust")
我使用我的特征矩阵,计算它们之间的欧几里德距离,然后将它们传递给层次聚类方法。从那里,我创建了扁平集群,最多有100个集群
现在,基于扁平簇T,我如何获得代表每个扁平簇的1 x n质心?
发布于 2013-11-12 01:46:59
一种可能的解决方案是一个函数,它像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)
发布于 2012-06-30 20:55:15
您可以这样做(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])
这将为您提供一个字典,其中簇编号作为关键字,特定簇的质心作为值。
https://stackoverflow.com/questions/9362304
复制相似问题