I am trying to do clustering, so I want to know the leaf information at each node after the clustering. So far, I am able to plot the dendrogram. Attached is the code and picture: enter image description here
import itertools
lst = list(itertools.product([0, 1], repeat=3))
import numpy as np
X=np.array(lst)
import numpy as np
from scipy.cluster.hierarchy import dendrogram, linkage
from matplotlib import pyplot as plt
%matplotlib inline
# generate two clusters: a with 10 points, b with 5:
np.random.seed(1)
#Z = hac.linkage(a, method="single")
Z = linkage(X, 'ward')
# make distances between pairs of children uniform
# (re-scales the horizontal (distance) axis when plotting)
Z[:,2] = np.arange(Z.shape[0])+1
def plot_dendrogram(linkage_matrix, **kwargs):
ddata = dendrogram(linkage_matrix, **kwargs)
idx = 0
for i, d, c in zip(ddata['icoord'], ddata['dcoord'],
ddata['color_list']):
x = 0.5 * sum(i[1:3])
y = d[1]
plt.plot(y, x, 'o', c=c)
plt.annotate(ddata['leaves'][idx], (x, y), xytext=(10,15),
textcoords='offset points', va='top', ha='center')
idx += 1
print(ddata['leaves'][idx-1])
plot_dendrogram(Z, labels=np.arange(X.shape[0]),
truncate_mode='level', show_leaf_counts=False,
orientation='top')`