scipy.cluster.hierarchy.

median#

scipy.cluster.hierarchy.median(y)[源代码]#

执行中位数/WPGMC 链接。

有关返回结构和算法的更多信息,请参见 linkage

以下是常见的调用约定

  1. Z = median(y)

    对压缩距离矩阵 y 执行中位数/WPGMC 链接。有关返回结构和算法的更多信息,请参见 linkage

  2. Z = median(X)

    对观测矩阵 X 执行中位数/WPGMC 链接,使用欧几里德距离作为距离度量。有关返回结构和算法的更多信息,请参见 linkage

参数:
yndarray

压缩距离矩阵。压缩距离矩阵是包含距离矩阵上三角的平面数组。这是 pdist 返回的形式。或者,可以将 n 维中的 m 个观测向量的集合作为 m x n 数组传递。

返回:
Zndarray

编码为链接矩阵的层级聚类。

参见

linkage

用于高级创建层级聚类。

scipy.spatial.distance.pdist

成对距离度量

注释

median 除了 NumPy 之外,还实验性地支持 Python Array API Standard 兼容后端。 请考虑通过设置环境变量 SCIPY_ARRAY_API=1 并提供 CuPy、PyTorch、JAX 或 Dask 数组作为数组参数来测试这些功能。 支持以下后端和设备(或其他功能)的组合。

CPU

GPU

NumPy

不适用

CuPy

不适用

PyTorch

JAX

Dask

⚠️ 合并块

不适用

有关更多信息,请参见 对数组 API 标准的支持

示例

>>> from scipy.cluster.hierarchy import median, fcluster
>>> from scipy.spatial.distance import pdist

首先,我们需要一个玩具数据集来玩

x x    x x
x        x

x        x
x x    x x
>>> X = [[0, 0], [0, 1], [1, 0],
...      [0, 4], [0, 3], [1, 4],
...      [4, 0], [3, 0], [4, 1],
...      [4, 4], [3, 4], [4, 3]]

然后,我们从这个数据集获得一个压缩距离矩阵

>>> y = pdist(X)

最后,我们可以执行聚类

>>> Z = median(y)
>>> Z
array([[ 0.        ,  1.        ,  1.        ,  2.        ],
       [ 3.        ,  4.        ,  1.        ,  2.        ],
       [ 9.        , 10.        ,  1.        ,  2.        ],
       [ 6.        ,  7.        ,  1.        ,  2.        ],
       [ 2.        , 12.        ,  1.11803399,  3.        ],
       [ 5.        , 13.        ,  1.11803399,  3.        ],
       [ 8.        , 15.        ,  1.11803399,  3.        ],
       [11.        , 14.        ,  1.11803399,  3.        ],
       [18.        , 19.        ,  3.        ,  6.        ],
       [16.        , 17.        ,  3.5       ,  6.        ],
       [20.        , 21.        ,  3.25      , 12.        ]])

链接矩阵 Z 表示一个树状图 - 有关其内容的详细说明,请参见 scipy.cluster.hierarchy.linkage

我们可以使用 scipy.cluster.hierarchy.fcluster 来查看在给定距离阈值的情况下,每个初始点将属于哪个聚类

>>> fcluster(Z, 0.9, criterion='distance')
array([ 7,  8,  9, 10, 11, 12,  1,  2,  3,  4,  5,  6], dtype=int32)
>>> fcluster(Z, 1.1, criterion='distance')
array([5, 5, 6, 7, 7, 8, 1, 1, 2, 3, 3, 4], dtype=int32)
>>> fcluster(Z, 2, criterion='distance')
array([3, 3, 3, 4, 4, 4, 1, 1, 1, 2, 2, 2], dtype=int32)
>>> fcluster(Z, 4, criterion='distance')
array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)

此外,scipy.cluster.hierarchy.dendrogram 可用于生成树状图的绘图。