scipy.cluster.hierarchy.to_tree

scipy.cluster.hierarchy.to_tree(Z, rd=False)[source]

Converts a hierarchical clustering encoded in the matrix Z (by linkage) into an easy-to-use tree object.

The reference r to the root ClusterNode object is returned.

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 : ndarray

The linkage matrix in proper form (see the linkage function documentation).

rd : bool, optional

When False, a reference to the root ClusterNode object is returned. Otherwise, a tuple (r,d) is returned. r is a reference to the root node while d is a dictionary mapping cluster ids to ClusterNode references. If a cluster id is less than n, then it corresponds to a singleton cluster (leaf node). See linkage for more information on the assignment of cluster ids to clusters.

Returns:

L : list

The pre-order traversal.