O.r*_*rka 5 python numpy hierarchical-clustering dendrogram scipy
我正在尝试学习如何使用dendrogramsusing . 我想要获得集群并能够将它们可视化;我听说是最好的办法。PythonSciPyhierarchical clusteringdendrograms
如何以特定距离“砍伐”树木?
我在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
Run Code Online (Sandbox Code Playgroud)
color_threshold是我一直在寻找的方法。color_palette当对于生成的簇的数量而言太小时,它并没有真正的帮助。如果有人可以提供帮助,则将下一步迁移到matplotlib 中用于 SciPy 树状图 (Python) 的更大调色板。
| 归档时间: |
|
| 查看次数: |
6839 次 |
| 最近记录: |