4
votes

I'm trying to learn how to use dendrograms in Python using SciPy . I want to get clusters and be able to visualize them; I heard hierarchical clustering and dendrograms are the best way.

How can I "cut" the tree at a specific distance?

In this example, I just want to cut it at distance 1.6 enter image description here

I looked up a tutorial on https://joernhees.de/blog/2015/08/26/scipy-hierarchical-clustering-and-dendrogram-tutorial/#Inconsistency-Method but the guy did some really confusing wrapper function using **kwargs (he calls his threshold max_d)

Here is my code and plot below; I tried annotating it as best as I could for reproducibility:

from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import dendrogram,linkage,fcluster
from scipy.spatial import distance
np.random.seed(424173239) #43984

#Dims
n,m = 20,7

#DataFrame: rows = Samples, cols = Attributes
attributes = ["a" + str(j) for j in range(m)]
DF_data = pd.DataFrame(np.random.random((n, m)), columns = attributes)

A_dist = distance.cdist(DF_data.as_matrix().T, DF_data.as_matrix().T)

#(i) . Do the labels stay in place from DF_data for me to do this? 
DF_dist = pd.DataFrame(A_dist, index = attributes, columns = attributes)

#Create dendrogram
fig, ax = plt.subplots()
Z = linkage(distance.squareform(DF_dist.as_matrix()), method="average")
D_dendro = dendrogram(Z, labels = attributes, ax=ax) #create dendrogram dictionary
threshold = 1.6 #for hline
ax.axhline(y=threshold, c='k')
plt.show()

#(ii) How can I "cut" the tree by giving it a distance threshold?
#i.e. If I cut at 1.6 it would make (a5 : cluster_1 or not in a cluster), (a2,a3 : cluster_2), (a0,a1 : cluster_3), and (a4,a6 : cluster_4)

#link_1 says use fcluster
#This -> fcluster(Z, t=1.5, criterion='inconsistent', depth=2, R=None, monocrit=None)
#gives me -> array([1, 1, 1, 1, 1, 1, 1], dtype=int32)

print(
     len(set(D_dendro["color_list"])), "^ # of colors from dendrogram",
     len(D_dendro["ivl"]), "^ # of labels",sep="\n")
#3 
#^ # of colors from dendrogram it should be 4 since clearly (a6, a4) and a5 are in different clusers
#7
#^ # of labels

link_1 : How to compute cluster assignments from linkage/distance matrices in scipy in Python?

2
@SaulloCastro thanks for that. Yea, it's definitely related. An interesting way to only trees by going horizontally. Also really cool to see how the actual graph is plotted too.O.rka

2 Answers

0
votes

color_threshold is the method I was looking for. It doesn't really help when the color_palette is too small for the amount of clusters being generated. Migrated the next step to Bigger color-palette in matplotlib for SciPy's dendrogram (Python) if anyone can help.

0
votes

For a bigger color palette this should work:

from scipy.cluster import hierarchy as hc
import matplotlib.cm as cm
import matplotlib.colors as col

#get a color spectrum "gist_ncar" from matplotlib cm. 
#When you have a spectrum it begins with 0 and ends with 1. 
#make tinier steps if you need more than 10 colors

colors = cm.gist_ncar(np.arange(0, 1, 0.1)) 

colorlst=[]# empty list where you will put your colors
for i in range(len(colors)): #get for your color hex instead of rgb
    colorlst.append(col.to_hex(colors[i]))

hc.set_link_color_palette(colorlst) #sets the color to use.

Put all of that infront of your code and it should work