如何在
scipy
/numpy
中的相关矩阵上运行层次聚类?我有一个 100 行 x 9 列的矩阵,我想根据 9 个条件中每个条目的相关性进行分层聚类。我想使用 1-pearson 相关性作为聚类距离。假设我有一个包含 100 x 9 矩阵的 numpy
数组 X
,我该怎么做?
我尝试使用 hcluster,基于此示例:
Y=pdist(X, 'seuclidean')
Z=linkage(Y, 'single')
dendrogram(Z, color_threshold=0)
但是,
pdist
不是我想要的,因为那是欧几里德距离。有什么想法吗?
谢谢。
只需将度量更改为
correlation
即可使第一行变为:
Y=pdist(X, 'correlation')
但是,我相信代码可以简化为:
Z=linkage(X, 'single', 'correlation')
dendrogram(Z, color_threshold=0)
因为联动会为你处理 pdist。
我发现使用 seaborn clustermap(它使用 scipy 进行聚类)执行和可视化层次聚类很有帮助。
import seaborn as sns
from scipy.cluster.hierarchy import dendrogram
from scipy.spatial.distance import pdist, squareform
D = squareform(pdist(X.T, 'correlation'))
h = sns.clustermap(D, cmap='Reds')
您还可以恢复相应的链接矩阵并绘制树状图
Z = h.dendrogram_col.linkage
dendrogram(Z, color_threshold=0)