scipy.cluster.hierarchy.
single#
- scipy.cluster.hierarchy.single(y)[源代码]#
在凝聚距离矩阵
y
上执行 single/min/nearest 链接。- 参数:
- yndarray
距离矩阵的上三角部分。
pdist
的结果以这种形式返回。
- 返回值:
- Zndarray
链接矩阵。
另请参见
linkage
用于高级层次聚类创建。
scipy.spatial.distance.pdist
成对距离度量
注释
single
除了 NumPy 之外,还对 Python Array API 标准兼容后端提供实验性支持。 请考虑通过设置环境变量SCIPY_ARRAY_API=1
并提供 CuPy、PyTorch、JAX 或 Dask 数组作为数组参数来测试这些功能。 支持以下后端和设备(或其他功能)的组合。库
CPU
GPU
NumPy
✅
n/a
CuPy
n/a
⛔
PyTorch
✅
⛔
JAX
✅
⛔
Dask
⚠️ 合并块
n/a
有关更多信息,请参见 对数组 API 标准的支持 。
示例
>>> from scipy.cluster.hierarchy import single, 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 = single(y) >>> Z array([[ 0., 1., 1., 2.], [ 2., 12., 1., 3.], [ 3., 4., 1., 2.], [ 5., 14., 1., 3.], [ 6., 7., 1., 2.], [ 8., 16., 1., 3.], [ 9., 10., 1., 2.], [11., 18., 1., 3.], [13., 15., 2., 6.], [17., 20., 2., 9.], [19., 21., 2., 12.]])
链接矩阵
Z
表示一个树状图 - 有关其内容的详细解释,请参见scipy.cluster.hierarchy.linkage
。我们可以使用
scipy.cluster.hierarchy.fcluster
来查看在给定的距离阈值下每个初始点将属于哪个群集>>> fcluster(Z, 0.9, criterion='distance') array([ 7, 8, 9, 10, 11, 12, 4, 5, 6, 1, 2, 3], dtype=int32) >>> fcluster(Z, 1, criterion='distance') array([3, 3, 3, 4, 4, 4, 2, 2, 2, 1, 1, 1], dtype=int32) >>> fcluster(Z, 2, criterion='distance') array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
此外,可以使用
scipy.cluster.hierarchy.dendrogram
来生成树状图的绘图。