16

我正在使用 SciPy 的分层凝聚聚类方法来聚类特征的 amxn 矩阵,但是在聚类完成后,我似乎无法弄清楚如何从生成的聚类中获取质心。下面是我的代码:

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

我正在使用我的特征矩阵,计算它们之间的欧几里德距离,然后将它们传递给层次聚类方法。从那里,我正在创建平面集群,最多 100 个集群

现在,基于平面簇 T,我如何获得代表每个平面簇的 1 xn 质心?

4

2 回答 2

3

一个可能的解决方案是一个函数,它返回一个像kmeansinscipy.cluster.vq一样具有质心的码本。您唯一需要的是将分区作为具有平面簇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)
于 2013-11-11T17:46:58.840 回答
1

你可以做这样的事情(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])

这将为您提供一个字典,其中簇号作为键,特定簇的质心作为值。

于 2012-06-30T12:55:14.733 回答