gpt4 book ai didi

python - 在距离高度处从 SciPy 切割树状图/聚类树

转载 作者:太空宇宙 更新时间:2023-11-03 12:04:27 25 4
gpt4 key购买 nike

我正在尝试学习如何使用 SciPyPython 中使用 dendrograms 。我想获得集群并能够将它们可视化;我听说 hierarchical clusteringdendrograms 是最好的方法。

我怎样才能在特定距离“砍”树?

在这个例子中,我只想在 1.6 的距离处切割它 enter image description here

我在 https://joernhees.de/blog/2015/08/26/scipy-hierarchical-clustering-and-dendrogram-tutorial/#Inconsistency-Method 上查找了教程但是这个家伙使用 **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 : How to compute cluster assignments from linkage/distance matrices in scipy in Python?

最佳答案

color_threshold 是我一直在寻找的方法。当 color_palette 对于生成的簇数量来说太小时,它并没有真正的帮助。将下一步迁移到 Bigger color-palette in matplotlib for SciPy's dendrogram (Python)如果有人可以提供帮助。

关于python - 在距离高度处从 SciPy 切割树状图/聚类树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36523789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com