scipy.cluster.hierarchy.
average#
- scipy.cluster.hierarchy.average(y)[source]#
对压缩距离矩阵执行平均/UPGMA 链接。
- 参数:
- yndarray
距离矩阵的上三角部分。
pdist
的结果以这种形式返回。
- 返回:
- Zndarray
包含层次聚类的链接矩阵。有关其结构的更多信息,请参见
linkage
。
另见
linkage
用于高级创建层次聚类。
scipy.spatial.distance.pdist
成对距离度量
注意
average
除了 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 average, 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 = average(y) >>> Z array([[ 0. , 1. , 1. , 2. ], [ 3. , 4. , 1. , 2. ], [ 6. , 7. , 1. , 2. ], [ 9. , 10. , 1. , 2. ], [ 2. , 12. , 1.20710678, 3. ], [ 5. , 13. , 1.20710678, 3. ], [ 8. , 14. , 1.20710678, 3. ], [11. , 15. , 1.20710678, 3. ], [16. , 17. , 3.39675184, 6. ], [18. , 19. , 3.39675184, 6. ], [20. , 21. , 4.09206523, 12. ]])
链接矩阵
Z
表示一个树状图 - 有关其内容的详细说明,请参见scipy.cluster.hierarchy.linkage
。我们可以使用
scipy.cluster.hierarchy.fcluster
来查看在给定距离阈值的情况下,每个初始点将属于哪个群集>>> fcluster(Z, 0.9, criterion='distance') array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=int32) >>> fcluster(Z, 1.5, criterion='distance') array([1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4], dtype=int32) >>> fcluster(Z, 4, criterion='distance') array([1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2], dtype=int32) >>> fcluster(Z, 6, criterion='distance') array([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int32)
此外,
scipy.cluster.hierarchy.dendrogram
可用于生成树状图的图。