How to get flat clustering corresponding to color clusters in the dendrogram created by scipy

前端 未结 4 1012
时光说笑
时光说笑 2020-12-03 00:03

Using the code posted here, I created a nice hierarchical clustering:

\"scipy

Let\'s say t

4条回答
  •  广开言路
    2020-12-03 00:14

    I wrote some code to decondense the linkage matrix. It returns a dictionary containing the indexes of labels that are grouped by each agglomeration step. I've only tried it out on the results of the complete linkage clusters. The keys of the dict start at len(labels)+1 because initially, each label is treated as its own cluster. This may answer your question.

    import pandas as pd
    import numpy as np
    from scipy.cluster.hierarchy import linkage
    
    np.random.seed(123)
    labels = ['ID_0','ID_1','ID_2','ID_3','ID_4']
    
    X = np.corrcoef(np.random.random_sample([5,3])*10)
    row_clusters = linkage(x_corr, method='complete')    
    
    def extract_levels(row_clusters, labels):
        clusters = {}
        for row in xrange(row_clusters.shape[0]):
            cluster_n = row + len(labels)
            # which clusters / labels are present in this row
            glob1, glob2 = row_clusters[row, 0], row_clusters[row, 1]
    
            # if this is a cluster, pull the cluster
            this_clust = []
            for glob in [glob1, glob2]:
                if glob > (len(labels)-1):
                    this_clust += clusters[glob]
                # if it isn't, add the label to this cluster
                else:
                    this_clust.append(glob)
    
            clusters[cluster_n] = this_clust
        return clusters
    

    Returns:

    {5: [0.0, 2.0],
     6: [3.0, 4.0],
     7: [1.0, 0.0, 2.0],
     8: [3.0, 4.0, 1.0, 0.0, 2.0]}
    

提交回复
热议问题