我正在尝试学习如何使用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 …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种方法,根据to_tree返回的ClusterNode来获取树状图中集群点的坐标。
使用 scipy 根据以下数据构建树状图:
X = data
Y = pdist(X)
Z = linkage(Y)
dend = dendrogram(Z)
rootnode, nodesList = to_tree(Z, rd=True)
Run Code Online (Sandbox Code Playgroud)
我想做的是构建一个函数,get_coords(somClusterNode)该函数将返回(x, y)指定图中节点位置的元组。
感谢这个答案,我设法弄清楚如何从树状图返回值中获取位置,例如:
i, d = list(zip(dend['icoord'], dend['dcoord']))[-1]
x = 0.5 * sum(i[1:3])
y = d[1]
plt.plot(x, y, 'ro')
Run Code Online (Sandbox Code Playgroud)
但我可以找出nodesList 排序和icoord/dcoord排序之间的关系,以便将一个映射到另一个。
你知道我可以在哪里寻找吗?
感谢您的帮助 !
我正在使用Python的fastcluster包来计算大量观测值上的分层聚类过程的链接矩阵。
到目前为止,fastcluster 的方法表现良好,它能够对一组观测值进行聚类,这比使用相同内存量进行计算的情况要linkage_vector()大得多。scipy.linkage()
完成此操作后,我现在想要检查聚类结果并计算相对于原始数据的共表相关系数。通常的过程是首先计算共表距离矩阵,然后检查与原始数据的相关性。使用 scipy 的cophenet()方法,它看起来像这样:
import fastcluster as fc
import numpy as np
from scipy.cluster.hierarchy import cophenet
X = np.random.random((1000,10)) # Original data (1000 observations)
Z = fc.linkage_vector(X) # Clustering
orign_dists = fc.pdist(X) # Matrix of original distances between observations
cophe_dists = cophenet(Z) # Matrix of cophenetic distances between observations
# What I really want at the end of the day is
corr_coef = np.corrcoef(orign_dists, cophe_dists)[0,1]
Run Code Online (Sandbox Code Playgroud)
然而,当观察集非常大时,这不起作用(只需将 1000 替换为 …
我在 Python 3 中做了一个凝聚层次聚类实验,我发现scipy.cluster.hierarchy.cut_tree()没有为某些输入链接矩阵返回请求的聚类数。所以,现在我知道有在一个bug cut_tree()函数(如描述在这里)。
但是,我需要能够获得平面聚类,并k为我的数据点分配不同的标签。您知道k从任意输入链接矩阵中获得带有标签的平面聚类的算法Z吗?我的问题归结为:如何cut_tree()在没有错误的情况下从头开始计算什么?
您可以使用此数据集测试您的代码。
from scipy.cluster.hierarchy import linkage, is_valid_linkage
from scipy.spatial.distance import pdist
## Load dataset
X = np.load("dataset.npy")
## Hierarchical clustering
dists = pdist(X)
Z = linkage(dists, method='centroid', metric='euclidean')
print(is_valid_linkage(Z))
## Now let's say we want the flat cluster assignement with 10 clusters.
# If cut_tree() was working we would do
from scipy.cluster.hierarchy import cut_tree
cut = cut_tree(Z, 10)
Run Code Online (Sandbox Code Playgroud)
旁注:另一种方法也许可以是使用 …
我正在尝试使用 scipy.hierarchy.cluster 模块对某些文本进行分层聚类。我做了以下工作:
l = linkage(model.wv.syn0, method='complete', metric='cosine')
den = dendrogram(
l,
leaf_rotation=0.,
leaf_font_size=16.,
orientation='left',
leaf_label_func=lambda v: str(model.wv.index2word[v])
Run Code Online (Sandbox Code Playgroud)
dendrogram 函数返回一个包含树的表示的字典,其中:
den['ivl'] 是与叶子对应的标签列表:
['politics', 'protest', 'characterfirstvo', 'machine', 'writing', 'learning', 'healthcare', 'climate', 'of', 'rights', 'activism', 'resistance', 'apk', 'week', 'challenge', 'water', 'obamacare', 'colorado', 'change', 'voiceovers', '52', 'acting', 'android']
Run Code Online (Sandbox Code Playgroud)
den['leaves'] 是每个叶子在叶子从左到右遍历中的位置列表:[0, 18, 5, 6, 2, 7, 12, 16, 21, 20, 22, 3, 10, 14, 15, 19, 11, 1, 17, 4, 13, 8, 9]
我知道 scipy 的to_tree()方法通过返回对根节点(一个 ClusterNode 对象)的引用,将由链接矩阵表示的层次聚类转换为树对象 - 但我不确定这个根节点如何对应我的叶子/标签。例如,get_id() …
我有一个相当大的数据集(1841000*32 矩阵),我希望运行分层聚类算法。sklearn.cluster 中的 AgglomerativeClustering 类和 FeatureAgglomeration 类均给出以下错误。
---------------------------------------------------------------------------
MemoryError Traceback (most recent call last)
<ipython-input-10-85ab7b694cf1> in <module>()
1
2
----> 3 mat_red = manifold.SpectralEmbedding(n_components=2).fit_transform(mat)
4 clustering.fit(mat_red,y = None)
~/anaconda3/lib/python3.6/site-packages/sklearn/manifold/spectral_embedding_.py in fit_transform(self, X, y)
525 X_new : array-like, shape (n_samples, n_components)
526 """
--> 527 self.fit(X)
528 return self.embedding_
~/anaconda3/lib/python3.6/site-packages/sklearn/manifold/spectral_embedding_.py in fit(self, X, y)
498 "name or a callable. Got: %s") % self.affinity)
499
--> 500 affinity_matrix = self._get_affinity_matrix(X)
501 self.embedding_ = spectral_embedding(affinity_matrix,
502 n_components=self.n_components,
~/anaconda3/lib/python3.6/site-packages/sklearn/manifold/spectral_embedding_.py in _get_affinity_matrix(self, X, Y)
450 …Run Code Online (Sandbox Code Playgroud) python hierarchical-clustering python-3.x scikit-learn opencv3.0
我正在使用seaborn.clustermap 中的分层聚类来对我的数据进行聚类。这可以很好地可视化热图中的集群。但是,现在我想提取分配给不同集群的所有行值。
这是我的数据的样子:
import pandas as pd
# load DataFrame
df = pd.read_csv('expression_data.txt', sep='\t', index_col=0)
df
Run Code Online (Sandbox Code Playgroud)
log_HU1 log_HU2
EEF1A1 13.439499 13.746856
HSPA8 13.169191 12.983910
FTH1 13.861164 13.511200
PABPC1 12.142340 11.885885
TFRC 11.261368 10.433607
RPL26 13.837205 13.934710
NPM1 12.381585 11.956855
RPS4X 13.359880 12.588574
EEF2 11.076926 11.379336
RPS11 13.212654 13.915813
RPS2 12.910164 13.009184
RPL11 13.498649 13.453234
CA1 9.060244 13.152061
RPS3 11.243343 11.431791
YBX1 12.135316 12.100374
ACTB 11.592359 12.108637
RPL4 12.168588 12.184330
HSP90AA1 10.776370 10.550427
HSP90AB1 11.200892 11.457365
NCL 11.366145 11.060236
Run Code Online (Sandbox Code Playgroud)
然后我使用seaborn执行聚类,如下所示:
fig …Run Code Online (Sandbox Code Playgroud) 我有一个矩阵数据,并希望用热图可视化它.行是物种,所以我想在行旁边显示系统发育树,并根据树重新排列热图的行.我知道heatmapR中的函数可以创建层次聚类热图,但是如何在图中使用我的系统发育聚类而不是默认创建的距离聚类?
我想提取树状图或群集的节点的层次结构。
例如,在下一个示例中:
library(dendextend)
dend15 <- c(1:5) %>% dist %>% hclust(method = "average") %>% as.dendrogram
dend15 %>% plot
Run Code Online (Sandbox Code Playgroud)
根据节点在树状图中的位置对其进行分类(请参见下图)
(图摘自dendextend包的教程)
我想获取每个最终叶子的所有节点作为下一个输出:(标签从左到右,从下到上排序)
hierarchical structure
leaf_1: 3-2-1
leaf_2: 4-2-1
leaf_3: 6-5-1
leaf_4: 8-7-5-1
leaf_5: 9-7-5-1
Run Code Online (Sandbox Code Playgroud)
提前致谢,
from scipy.cluster.hierarchy import dendrogram, linkage,fcluster
import numpy as np
import matplotlib.pyplot as plt
# data
np.random.seed(4711) # for repeatability of this tutorial
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, 4]], size=[100,])
b = np.random.multivariate_normal([0, 20], [[3, 1], [1, 4]], size=[50,])
X = np.concatenate((a, b),)
plt.scatter(X[:,0], X[:,1])
Run Code Online (Sandbox Code Playgroud)
# fit clusters
Z = linkage(X, method='ward', metric='euclidean', preserve_input=True)
# plot dendrogram
Run Code Online (Sandbox Code Playgroud)
max_d = 50
clusters = fcluster(Z, max_d, criterion='distance')
# now if I have new data
a = np.random.multivariate_normal([10, 0], [[3, 1], [1, …Run Code Online (Sandbox Code Playgroud) python cluster-analysis hierarchical-clustering scipy data-science
python ×7
scipy ×6
dendrogram ×3
numpy ×3
r ×2
data-science ×1
dendextend ×1
heatmap ×1
linkage ×1
opencv3.0 ×1
pandas ×1
plot ×1
python-3.x ×1
scikit-learn ×1
seaborn ×1
treenode ×1