【问题标题】:How to get centroids from SciPy's hierarchical agglomerative clustering?如何从 SciPy 的层次凝聚聚类中获取质心?
【发布时间】:2012-03-10 20:42:38
【问题描述】:

我正在使用 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 质心?

【问题讨论】:

  • 那么最后发生了什么?你解决问题了吗?怎么样?
  • 我实际上最终使用了 scikit-learn。
  • 请问 scikit 中的哪个函数?
  • 查看Ward函数。
  • 感谢您的跟进。 :)

标签: python numpy scipy hierarchical-clustering


【解决方案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])

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

【讨论】:

    【解决方案2】:

    一个可能的解决方案是一个函数,它返回一个像kmeans 中的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)
    

    【讨论】:

      猜你喜欢
      • 2014-06-28
      • 2019-10-20
      • 2016-09-06
      • 2021-10-04
      • 2021-07-25
      • 2015-11-20
      • 2021-07-21
      • 2017-10-24
      • 2020-11-30
      相关资源
      最近更新 更多