【问题标题】:Separating Clusters after using SLINK in Python/R在 Python/R 中使用 SLINK 后分离集群
【发布时间】:2020-05-17 21:12:15
【问题描述】:

从研究来看,只有 Single-Linkage Hierarchical Clustering 才能获得最优的聚类。这也称为 SLINK。这些库最初以 C++ 发布,现在以 Python/R 发布。

到目前为止,按照文档中的步骤,我设法想出了:

import pandas as pd
from scipy.cluster.hierarchy import dendrogram, linkage
from scipy.spatial.distance import pdist

## generating random numbers from 20 to 90, and storing them in a dataframe. This is a 1-dimensional data
np.random.seed(1)
df = pd.DataFrame(np.random.randint(20,90,size=(100,1)), columns = list('A'))
df = df.sort_values(by=['A'])
df = df.values
df[:,0].sort()

## getting condensed distance matrix
d = pdist(df_final, metric='euclidean')

## running the SLINK algorithm
Z = linkage(d, 'single')

我知道 Z 是“编码为链接矩阵的层次聚类”(如文档中所述),但我想知道如何返回原始数据集并区分由此结果计算的聚类?

我可以通过 Scikit-Learn 聚类实现聚类结果,但我认为 Scikit-Learn 聚类算法不是最优的,因此我转向了这个 SLINK 算法。如果有人可以帮助我,将不胜感激。

【问题讨论】:

    标签: python r cluster-analysis


    【解决方案1】:

    scipy.cluster.hierarchy.linkage,您可以了解每次迭代是如何形成集群的。

    通常这些信息没那么有用,所以我们可以先看一下聚类:

    import scipy as scipy
    import matplotlib.pyplot as plt
    plt.figure()
    dn =scipy.cluster.hierarchy.dendrogram(Z)
    

    如果我们想得到这三个集群,我们可以这样做:

    labels = scipy.cluster.hierarchy.fcluster(Z,3,'maxclust')
    

    如果你想通过数据点之间的距离得到它:

    scipy.cluster.hierarchy.fcluster(Z,2,'distance')
    

    这与调用 3 个集群的结果大致相同,因为切割此示例数据集的方法并不多。

    如果你看一下你的例子,你可以切割它的下一个点是高度 ~ 1.5,即 16 个簇。因此,如果您尝试执行 scipy.cluster.hierarchy.fcluster(Z,5,'maxclust'),您将获得与 3 个集群相同的结果。如果您有一个更广泛的数据集,它将起作用:

    np.random.seed(111)
    df = np.random.normal(0,1,(50,3))
    
    ## getting condensed distance matrix
    d = pdist(df, metric='euclidean')
    Z = linkage(d, 'single')
    dn = scipy.cluster.hierarchy.dendrogram(Z,above_threshold_color='black',color_threshold=1.1)
    

    然后这个工作:

    scipy.cluster.hierarchy.fcluster(Z,5,'maxclust')
    

    【讨论】:

    • 非常感谢!!但是,您知道如何预先设置簇数吗?例如,我想要 5 个集群而不是 3 个集群。有没有办法做到这一点?
    • 嗨@LucasLe,我编辑了我的答案。这取决于您的数据集是否允许您拥有 5 个集群。请参阅上面我编辑的答案
    • 嗯没问题。让我试着分部分回答,是的,你也可以使用sklearn.cluster.AgglomerativeClustering,方法='single',你指定集群的数量
    • 我认为您必须在这里详细说明最优性。这对我来说非常模糊。如果数据不允许,将集群设置为 5 可能无法保证具有 5 个集群的解决方案。我不知道这是否是您所说的最优性
    • 对我来说,我总是先看树,然后再决定切割或聚类的数量是否有意义。我认为这个问题比来回讨论确定性更重要。任何聚类算法都是一样的,如果数据不能给你一个分辨率,你会有一些不确定性。这就是为什么你总是检查你的集群的稳定性,如果它对下游流程很重要
    猜你喜欢
    • 1970-01-01
    • 2019-11-20
    • 2018-11-07
    • 2019-10-01
    • 2016-11-30
    • 2023-03-06
    • 2013-11-19
    • 2016-06-03
    • 1970-01-01
    相关资源
    最近更新 更多