bundles / scipy 1.17.1 / scipy / cluster / hierarchy / to_tree
function
scipy.cluster.hierarchy:to_tree
Signature
def to_tree ( Z , rd = False ) Summary
Convert a linkage matrix into an easy-to-use tree object.
Extended Summary
The reference to the root ClusterNode object is returned (by default).
Each ClusterNode object has a left, right, dist, id, and count attribute. The left and right attributes point to ClusterNode objects that were combined to generate the cluster. If both are None then the ClusterNode object is a leaf node, its count must be 1, and its distance is meaningless but set to 0.
Note: This function is provided for the convenience of the library user. ClusterNodes are not used as input to any of the functions in this library.
Parameters
Z: ndarrayThe linkage matrix in proper form (see the
linkagefunction documentation).rd: bool, optionalWhen False (default), a reference to the root ClusterNode object is returned. Otherwise, a tuple
(r, d)is returned.ris a reference to the root node whiledis a list of ClusterNode objects - one per original entry in the linkage matrix plus entries for all clustering steps. If a cluster id is less than the number of samplesnin the data that the linkage matrix describes, then it corresponds to a singleton cluster (leaf node). Seelinkagefor more information on the assignment of cluster ids to clusters.
Returns
tree: ClusterNode or tuple (ClusterNode, list of ClusterNode)If
rdis False, a ClusterNode. Ifrdis True, a list of length2*n - 1, withnthe number of samples. See the description ofrdabove for more details.
Notes
Array API Standard Support
to_tree has experimental support for Python Array API Standard compatible backends in addition to NumPy. Please consider testing these features by setting an environment variable SCIPY_ARRAY_API=1 and providing CuPy, PyTorch, JAX, or Dask arrays as array arguments. The following combinations of backend and device (or other capability) are supported.
==================== ==================== ==================== Library CPU GPU ==================== ==================== ==================== NumPy ✅ n/a CuPy n/a ✅ PyTorch ✅ ✅ JAX ⚠️ no JIT ⚠️ no JIT Dask ⚠️ computes graph n/a ==================== ==================== ====================
See
dev-arrayapifor more information.
Examples
import numpy as np from scipy.cluster import hierarchy rng = np.random.default_rng() x = rng.random((5, 2)) Z = hierarchy.linkage(x) hierarchy.to_tree(Z) rootnode, nodelist = hierarchy.to_tree(Z, rd=True) rootnode len(nodelist)✓
See also
- ClusterNode
- is_valid_linkage
- linkage
Aliases
-
scipy.cluster.hierarchy.to_tree