使用scipy的层次结构聚类后,无法从fcluster中提取聚类

时间:2018-03-08 18:46:29

标签: numpy machine-learning scipy cluster-analysis hierarchical-clustering

在对我的数据集进行层次结构聚类并使用树状图函数绘制它之后,似乎它是正确的聚类,但是当我调用函数fcluster来提取聚类ID时,我只得到一个聚类ID。 为什么会这样?

我的代码:

    for key, values in use_case_idx.items():
        vectors = []
        labels = []
        for value in values:
            labels.append(value[0])
            vectors.append(value[1])

        try:
            distance_matrix = pdist(vectors, metric='cosine')
            Z = linkage(distance_matrix, 'ward')
            plt.title("Ward")
            dendrogram(Z, labels=labels)
        except:
            continue

        plt.show()

        clusters = fcluster(Z, 10, criterion='distance')
        print(clusters)

因此,输出:

enter image description here

enter image description here

更多示例:https://imgur.com/a/kEfub

这段代码出了什么问题?

注意:每个向量都有50个维度

2 个答案:

答案 0 :(得分:1)

树形图的y轴显示不同节点之间的cophenetic distance。由于您使用的distance条件具有较大的值(远大于共生距离),因此所有元素都会分组到同一个群集中。

尝试使用较小的阈值(例如,您显示的第一个树形图为0.025)。树形图可以作为选择"好"的指南。门槛---虽然"好"是非常主观的。

答案 1 :(得分:0)

如果要将数据聚类为n个不同的聚类,则可以使用条件'maxclust'进行,例如fcluster(data,n,criterion ='maxclust')