python中基于合并顺序的分层聚类标签

2024-10-02 00:29:40 发布

您现在位置:Python中文网/ 问答频道 /正文

比方说,我有这种类型的分层集群,如下图所示。为了获得聚类标签,我需要定义适当的阈值距离。例如,如果我把阈值设置为0.32,我可能会得到3个集群,如果我设置为3.5左右,我会从下图中得到2个集群

我不想使用阈值和固定距离,而是希望根据它们的合并顺序获得聚类标签

我想根据它们的合并来定义集群;比如第一次合并,第二次合并等等

例如,这里我想得到集群标签,当它们至少第一次合并时,这将是3个集群

cluster1: p1
cluster2: p3 and p4
cluster3: p2 and p5.

如果我在这里设置,则在至少发生第二次合并时查找集群。 在本例中,我将有两个集群,例如:

cluster1: p1
cluster2 = p3, p4, p2 and p5.

没有scipy内置的方法来提取此类信息。如果没有,是否有任何方法可以从hierarchical clustering中提取此类信息?任何建议都很好

enter image description here

示例案例:

我的想法是,我不想硬编码任何阈值限制来定义集群的数量,而是根据它们的合并顺序找到集群。例如,如果存在p1、p2和p3,并且在一种情况下p1和p2在0.32和另一种情况下落在同一簇中,则会为p1、p2和p3添加更多数据,现在它们可能落在同一簇中,但它们簇的合并距离可能已更改。在这种情况下,p1和p2仍然在同一集群中。因此,这里定义簇的距离阈值是不相关的


Tags: and距离定义顺序情况集群阈值聚类
1条回答
网友
1楼 · 发布于 2024-10-02 00:29:40

scipy.cluster.hierarchy函数生成的链接矩阵有一个额外字段,用于新形成的簇中的观察数:

scipy.cluster.hierarchy.linkage: A (n−1) by 4 matrix Z is returned. At the i-th iteration, clusters with indices Z[i, 0] and Z[i, 1] are combined to form cluster n+i. A cluster with an index less than n corresponds to one of the n original observations. The distance between clusters Z[i, 0] and Z[i, 1] is given by Z[i, 2]. The fourth value Z[i, 3] represents the number of original observations in the newly formed cluster.

我不确定我是否完全遵循了您的示例[1],但您可以使用簇大小来定义切割深度,从而生成簇的平面列表,从而沿着这些线获得一些东西。例如,逻辑可以是“在集群大小仍然为2或更小的最后一次合并时停止”(给出第一个包含3个集群的列表)或“在集群大小为3或更大的第一次合并时停止”(给出第二个包含2个集群的列表)

下面是一个数据集示例,该数据集提供了与绘图中显示的数据集相似的层次聚类,显示了与两个示例匹配的结果:

import numpy as np
from scipy.cluster.hierarchy import single, fcluster
from scipy.spatial.distance import pdist

X = [
    (0, 0, .45), # P1
    (0, .36, 0), # P2
    (0, 0, 0), # P3
    (.3, 0, 0), # P4
    (.31, .36, 0), # P5
]

Z = single(pdist(X))

i1 = np.argwhere(Z[:,3] <= 2)[-1,0]        # => i1 = 1
d1 = Z[i1, 2]                              # => d = 0.31
c1 = fcluster(Z, d1, criterion='distance') # => c1 = [3, 2, 1, 1, 2]
# i.e., three clusters: {P3, P4}, {P2, P5} and {P1}

i2 = np.argwhere(Z[:,3] >= 3)[0,0]         # => i2 = 2
d2 = Z[i2, 2]                              # => d2 = 0.36
c2 = fcluster(Z, d2, criterion='distance') # => c2 = [2, 1, 1, 1, 1]
# i.e., two clusters: {P2, P3, P4, P5} and {P1}

[1]当P3和P4合并时,“至少第一次合并”不会立即发生,只剩下4个集群吗?没有理由期望“第二次合并”总是合并两对:它也可以将单个观测值与一对观测值合并。这就是为什么我建议使用集群大小而不是“N个mergings”。

相关问题 更多 >

    热门问题