Python:Scipy 的树状图不起作用

Python: Dendogram with Scipy doesn´t work

我想用scipy的树状图。 我有以下数据:

我有一个包含七种不同含义的列表。例如:

Y = [71.407452200146807, 0, 33.700136456196823, 1112.3757110973756, 31.594949722819372, 34.823881975554166, 28.36368420190157]

每个均值是为不同的用户计算的。例如:

X = ["user1", "user2", "user3", "user4", "user5", "user6", "user7"]

我的目标是借助树状图显示上述数据。

我尝试了以下方法:

Y = [71.407452200146807, 0, 33.700136456196823, 1112.3757110973756, 31.594949722819372, 34.823881975554166, 28.36368420190157]
X = ["user1", "user2", "user3", "user4", "user5", "user6", "user7"]

# Attempt with matrix
#X = np.concatenate((X, Y),)
#Z = linkage(X)

Z = linkage(Y)
# Plot the dendogram with the results above
dendrogram(Z, leaf_rotation=45., leaf_font_size=12. , show_contracted=True)
plt.style.use("seaborn-whitegrid")
plt.title("Dendogram to find clusters")
plt.ylabel("Distance")
plt.show()

但是它说:

ValueError: Length n of condensed distance matrix 'y' must be a binomial coefficient, i.e.there must be a k such that (k \choose 2)=n)!

我已经尝试将我的数据转换为矩阵。有:

# Attempt with matrix
#X = np.concatenate((X, Y),)
#Z = linkage(X)

但这也行不通!

有什么建议吗?

谢谢 :-)

因此您在 Y len(Y) = 7.

中使用了 7 个观测值

但是根据 Linkage 的文档,观察的数量 len(Y) 应该是这样的。

{n \choose 2} = len(Y)

这意味着

1/2 * (n -1) * n = len(Y)

因此 Y 的长度应使 n 为有效整数。

linkage is either an n x m array, representing n points in m-dimensional space, or a one-dimensional array containing the condensed distance matrix 的第一个参数。这是两个截然不同的意思!第一个是原始数据,即 观察 。第二种格式假设您已经计算了观测值之间的所有距离,并且您将这些距离提供给 linkage,而不是原始点。

您似乎想要第一种情况(原始数据),其中 m = 1。因此您必须将输入重塑为形状 (n, 1)。

替换为:

Z = linkage(Y)

与:

Z = linkage(np.reshape(Y, (len(Y), 1)))