【问题标题】:How to count line crosses between horizontal line and tree line dendogram python如何计算水平线和树线树状图python之间的线交叉
【发布时间】:2020-01-16 12:33:58
【问题描述】:

我正在编写程序如何计算层次聚类中的最佳聚类数,聚类数由穿过树垂直线的水平线数定义

如何在树状图中使用 axhline 和树线计算水平线之间的交叉线数? ,这是我的可视化脚本,但我不知道如何计算交叉次数

plt.figure(0)
plt.figure(figsize=(20, 7))
plt.title("Customer Dendograms")
L=shc.linkage(X, method='average')
dend = shc.dendrogram(L)
plt.axhline(c=c,linestyle='--', y=35) 
plt.show()

【问题讨论】:

  • 这不是可以使用 matplotlib 以图形方式解决的问题,因此我删除了该标签。您需要弄清楚linkage 函数返回的链接矩阵 L 的格式,也许很容易从中得到答案。或者,您可以查看dendogram 函数的源代码,该函数使用此信息绘制绘图,它应该知道它绘制的所有线条的坐标。您可以修改该代码,以便它检查绘制的所有垂直线是否越过您感兴趣的级别。

标签: python scipy cluster-analysis hierarchical-clustering


【解决方案1】:

这不完全是我的领域,所以我在这里尝试一下。

linkage matrix Z 中的每一行由以下内容组成:合并集群的 id、两个集群之间的距离和新集群中的元素总数。

假设高度在 Z 矩阵中按升序排列(即没有inversions?)。每次形成一个集群(通过合并两个集群),集群的数量就会减少一个。所以,Z矩阵每一行对应的簇数,等于nbr_of_leaves - idx of the line

np.digitize 函数允许获取给定任意高度的行 ID。那么,给定高度的簇数是nbr_of_leaves - np.digitize(height, Z[:, 2])

这是一个测试示例:

import numpy as np
import matplotlib.pyplot as plt

from scipy.spatial.distance import euclidean
from scipy.cluster.hierarchy import dendrogram, linkage

def get_number_of_clusters(height, Z):
    nbr_of_leaves = Z.shape[0] + 1
    merge_heights = Z[:, 2]
    nbr_of_clusters  = nbr_of_leaves - np.digitize(height, merge_heights)
    return nbr_of_clusters

# data for an example
x = np.array([0, 1, 2, 11, 4.5, 8, 9, 4])
x_2d = x.reshape(-1, 1)
Z = linkage(x_2d, method='single')

#for method = 'single' 
print(get_number_of_clusters(2.1, Z)) # 2
print(get_number_of_clusters(1.5, Z)) # 4
print(get_number_of_clusters(0.5, Z)) # 7

# Dendrogram
plt.figure(figsize=(8, 2))
dendrogram(Z, labels=x);
plt.grid(axis='y'); plt.xlabel('leaves'); plt.ylabel('distances');
plt.show();

【讨论】:

    【解决方案2】:

    它是给定高度的簇数。

    除非您的链接有反转,否则您可以从链接矩阵 L 中轻松读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-30
      • 2011-11-27
      • 2012-01-09
      • 1970-01-01
      • 2011-02-23
      • 1970-01-01
      相关资源
      最近更新 更多