【问题标题】:Python get clustered data-Hierachical ClusteringPython获取聚类数据-Hierarchical Clustering
【发布时间】:2014-07-14 09:26:58
【问题描述】:

我使用以下 python 脚本进行层次聚类并打印树状图。请考虑我是数据挖掘的新手。

import numpy as np
import distance
import scipy.cluster.hierarchy
import matplotlib.pyplot as plt
from scipy.cluster.hierarchy import dendrogram, linkage

mat = np.array([[ 0. , 1. , 3.  ,0. ,2.  ,3.  ,1.],
 [ 1. , 0. , 3. , 1.,  1. , 2. , 2.],
 [ 3.,  3. , 0.,  3. , 3.,  3. , 4.],
 [ 0. , 1. , 3.,  0. , 2. , 3.,  1.],
 [ 2. , 1.,  3. , 2.,  0. , 1.,  3.],
 [ 3. , 2.,  3. , 3. , 1. , 0. , 3.],
 [ 1. , 2.,  4. , 1. , 3.,  3. , 0.]])

linkage_matrix = linkage(mat, "single")

dendrogram(linkage_matrix,
           color_threshold=1,
           truncate_mode='lastp',
           distance_sort='ascending')

plt.show()

以下是我得到的树状图。我需要打印集群和属于每个集群的数据吗?

cluster1 4,5
cluster2 ..,..
cluster3 ..,..

【问题讨论】:

    标签: python cluster-analysis hierarchical-clustering dendrogram


    【解决方案1】:

    根据scipy.cluster.hierarchy文档

    (通过运行链接...)返回一个 4 x (n-1) 矩阵 Z。在第 i 次迭代中,索引为 Z[i, 0] 和 Z[i, 1] 的簇组合在一起形成簇 n + i。索引小于 n 的集群对应于 n 个原始观测值之一。簇 Z[i, 0] 和 Z[i, 1] 之间的距离由 Z[i, 2] 给出。第四个值 Z[i, 3] 表示新形成的聚类中原始观测值的数量。

    这意味着,我们可以遍历linkage_matrix 并找到实际的节点组合以形成新的集群。这是一个小的 for 循环来做到这一点

    n = len(mat)
    cluster_dict = dict()
    for i in range(0, 6):
        new_cluster_id = n+i
        old_cluster_id_0 = linkage_matrix[i, 0]
        old_cluster_id_1 = linkage_matrix[i, 1]
        combined_ids = list()
        if old_cluster_id_0 in cluster_dict:
            combined_ids += cluster_dict[old_cluster_id_0]
            del cluster_dict[old_cluster_id_0]
        else:
            combined_ids += [old_cluster_id_0]
        if old_cluster_id_1 in cluster_dict:
            combined_ids += cluster_dict[old_cluster_id_1]
            del cluster_dict[old_cluster_id_1]
        else:
            combined_ids += [old_cluster_id_1]
        cluster_dict[new_cluster_id] = combined_ids
        print cluster_dict
    

    该代码为该集群中包含的节点创建了一个集群 ID 字典。在每次迭代中,它将linakge_matrix[i, 0]linkage_matrix[i, 1]中的两个节点组合成一个新节点。最后,它在每次迭代中打印正在运行的集群。输出是

    {7: [0.0, 3.0]}
    {8: [4.0, 5.0], 7: [0.0, 3.0]}
    {8: [4.0, 5.0], 9: [6.0, 0.0, 3.0]}
    {8: [4.0, 5.0], 10: [1.0, 6.0, 0.0, 3.0]}
    {11: [4.0, 5.0, 1.0, 6.0, 0.0, 3.0]}
    {12: [2.0, 4.0, 5.0, 1.0, 6.0, 0.0, 3.0]}
    

    (集群 id 以 7 开头,原始行的索引为 0 到 6)。请注意,不在字典中的 id 形成自己的集群。例如,行 2.0 在迭代 2 中形成自己的集群。您可以根据您的停止标准提前停止来获得最终的集群集。

    我可以在第 3 次迭代(输出的第 3 行)处停止,然后我的集群将是:

    cluster 8: {4, 5}
    cluster 9: {6, 0, 3}
    cluster 1: {1}
    cluster 2: {2}
    

    【讨论】:

    • 非常感谢,干得好:),我正在努力改进。
    猜你喜欢
    • 2017-06-07
    • 2019-11-22
    • 2014-10-02
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 2019-07-30
    • 2014-01-27
    • 2020-02-23
    相关资源
    最近更新 更多