Python 在距离高度从SciPy切割树状图/聚类树

Python 在距离高度从SciPy切割树状图/聚类树,python,numpy,scipy,hierarchical-clustering,dendrogram,Python,Numpy,Scipy,Hierarchical Clustering,Dendrogram,我正在尝试学习如何使用SciPy在Python中使用dendrogram。我想得到集群,并能够可视化它们;我听说层次聚类和树状图是最好的方法 如何在特定距离“切割”树木? 在本例中,我只想在距离1.6 我查阅了一篇关于的教程,但这家伙用**kwargs做了一些非常令人困惑的包装函数(他调用他的阈值max_d) 下面是我的代码和情节;为了再现性,我尽可能地对其进行注释: from __future__ import print_function import matplotlib.pyplot

我正在尝试学习如何使用
SciPy
Python
中使用
dendrogram
。我想得到集群,并能够可视化它们;我听说
层次聚类
树状图
是最好的方法

如何在特定距离“切割”树木?

在本例中,我只想在距离
1.6

我查阅了一篇关于的教程,但这家伙用
**kwargs
做了一些非常令人困惑的包装函数(他调用他的阈值
max_d

下面是我的代码和情节;为了再现性,我尽可能地对其进行注释:

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:

color_threshold
是我一直在寻找的方法。当
调色板
对于生成的集群数量来说太小时,它实际上没有帮助。将下一步迁移到“如果有人可以提供帮助”

对于较大的调色板,这应该可以:

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.

把所有这些放在你的代码前面,它应该会起作用。

。@SaulloCastro谢谢你。是的,这肯定有关系。一个有趣的方法是水平移动,只移动树木。看到实际图形是如何绘制的也很酷。