You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何匹配scipy linkage()与dendrogram()的输出对应关系?

匹配SciPy层次聚类Z与树状图P的索引对应关系

我需要用以下代码输出的Z和P从头绘制树状图:

Z = scipy.cluster.hierarchy.linkage(...)
P = scipy.cluster.hierarchy.dendrogram(Z, ..., no_plot=True)

要实现这个需求,必须将P["icoord"]/P["dcoord"]中的坐标索引(存储聚类连线的绘制坐标)与Z中的对应索引(存储聚类组成信息)相互匹配。但两者的聚类位置顺序通常并不对应,下方代码输出可证明这一点。

核心问题:如何实现两者的索引匹配? 我需要一个映射函数Z_i = f(P_coords_i)或其逆函数P_coords_i = g(Z_i),以便遍历其中一方时,能便捷访问另一方的对应元素。

以下代码生成26个带字母标记的随机点,打印Z每行对应的聚类字母,以及P中dcoord为0的节点(叶节点),以此证明顺序不匹配:例如Z的第一个元素对应聚类"iu",但P["icoord"]/P["dcoord"]的第一组点对应绘制"jy"的聚类,"iu"的聚类则在后续位置出现。

import numpy as np
from scipy.cluster import hierarchy
from scipy.spatial import distance
import string

# 生成随机数据
np.random.seed(1)
data = np.random.multivariate_normal([0,0],[[5, 0], [0, 1]], 26)
letters = list(string.ascii_lowercase)
X = distance.pdist(data)

# 生成聚类结果和树状图数据
Z = hierarchy.linkage(X)
P = hierarchy.dendrogram(Z, labels=letters, no_plot=True)

# 打印Z的聚类顺序
print("Z:")
clusters = letters.copy()
for c1, c2, _, _ in Z:
    clusters.append(clusters[int(c1)]+clusters[int(c2)])
    print(clusters[-1])

# 打印P中dcoord为0的节点对应的聚类
print("\nP:")
def lookup(y, x):
    return "?" if y else P["ivl"][int((x-5)/10)]

for ((x1,x2,x3,x4),(y1,y2,y3,y4)) in zip(P["icoord"], P["dcoord"]):
     print(lookup(y1, x1)+lookup(y4, x4))

输出结果

------Z:
iu
ez
niu
jy
ad
pr
bq
prbq
wniu
gwniu
ezgwniu
hm
ojy
prbqezgwniu
ks
ojyprbqezgwniu
vks
ojyprbqezgwniuvks
lhm
adlhm
fadlhm
cfadlhm
tcfadlhm
ojyprbqezgwniuvkstcfadlhm
xojyprbqezgwniuvkstcfadlhm

------P:
jy
o?
pr
bq
??
ez
iu
n?
w?
g?
??
??
??
ks
v?
??
ad
hm
l?
??
f?
c?
t?
??
x?

内容的提问来源于stack exchange,提问作者nicolaskruchten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:48:22