【问题标题】:sklearn Hierarchical Agglomerative Clustering using similarity matrixsklearn分层凝聚聚类使用相似矩阵
【发布时间】:2018-04-29 11:43:06
【问题描述】:

给定一个距离矩阵,不同教授之间的相似度:

              prof1     prof2     prof3
       prof1     0        0.8     0.9
       prof2     0.8      0       0.2
       prof3     0.9      0.2     0

我需要对这个数据进行层次聚类,上面的数据是二维矩阵的形式

       data_matrix=[[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]

我尝试检查是否可以使用 sklearn.cluster AgglomerativeClustering 来实现它,但它将所有 3 行视为 3 个单独的向量而不是距离矩阵。可以使用 this 或 scipy.cluster.hierarchy 来完成吗?

【问题讨论】:

    标签: python pandas scikit-learn hierarchical-clustering


    【解决方案1】:

    是的,您可以使用sklearn 来完成。你需要设置:

    • affinity='precomputed',使用距离矩阵
    • linkage='complete' 或 'average',因为默认链接(Ward)仅适用于坐标输入。

    使用预先计算的亲和力,输入矩阵被解释为观察之间的距离矩阵。以下代码

    from sklearn.cluster import AgglomerativeClustering
    data_matrix = [[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]
    model = AgglomerativeClustering(affinity='precomputed', n_clusters=2, linkage='complete').fit(data_matrix)
    print(model.labels_)
    

    将返回标签[1 0 0]:第一个教授进入一个集群,第二个和第三个教授 - 进入另一个。

    【讨论】:

    • 谢谢,现在更有意义了。
    • 来自:scikit-learn.org/stable/modules/generated/…:“如果“预先计算”,则需要距离矩阵(而不是相似度矩阵)作为拟合方法的输入。这是否意味着输入相似度矩阵中的值在传递给模型时应该反转?
    • 不,你不需要逆矩阵,只需做 1-similarity (for all i,j) ;当你形成矩阵时。
    【解决方案2】:

    这里的输入 data_matrix 必须是一个距离矩阵,与给出的相似度矩阵不同,因为两者都与度量完全相反,使用一个代替其他度量会产生相当随意的结果。查看官方文档【如果“预计算”,则需要距离矩阵(而不是相似度矩阵)作为拟合方法的输入。” ]:https://scikit-learn.org/stable/modules/generated/sklearn.cluster.AgglomerativeClustering.html

    作为一种解决方案,可以使用相似度 = 1 - 距离矩阵(假设距离矩阵在 0 和 1 之间进行归一化),然后将其用作输入。

    我已经在几个示例上进行了尝试并验证了相同的结果,因此应该可以完成这项工作。

    【讨论】:

      【解决方案3】:

      你也可以用 scipy.cluster.hierarchy 来做:

      from scipy.cluster.hierarchy import dendrogram, linkage, cut_tree
      from matplotlib import pyplot as plt
      
      # Data
      X =[[0,0.8,0.9],[0.8,0,0.2],[0.9,0.2,0]]
      labels = ['prof1','prof2','prof3']
      
      # Perform clustering, you can choose the method
      # in this case, we use 'ward'
      Z = linkage(X, 'ward')
      
      # Extract the membership to a cluster, either specify the n_clusters
      # or the cut height
      # (similar to sklearn labels)
      print(cut_tree(Z, n_clusters=2))
      
      # Visualize the clustering as a dendogram
      fig = plt.figure(figsize=(25, 10))
      dn = dendrogram(Z, orientation='right', labels=labels)
      plt.show()
      

      这将打印:

      [[0]
       [1]
       [1]]
      

      由于我们指定了 n_cluster 2,这意味着有 2 个集群。 prof1 属于集群 0,prof2 和 prof3 属于集群 1。您还可以指示 cut_height 而不是集群的数量。 树状图如下所示:

      ![两个树状图][1] https://imgur.com/EF0cW4U.png "树状图"

      【讨论】:

        猜你喜欢
        • 2018-04-10
        • 2015-01-07
        • 2016-10-01
        • 2020-01-23
        • 2019-02-05
        • 2023-03-12
        • 2020-11-30
        • 2017-12-03
        相关资源
        最近更新 更多