Python层次聚类、距离矩阵和紧凑距离矩阵

3 投票
1 回答
2152 浏览
提问于 2025-04-16 16:01

我正在使用一个叫做 hcluster 的模块来从一个距离矩阵计算出一个树状图。我的距离矩阵是一个数组的数组,生成方式如下:

import hcluster
import numpy as np

mols = (..a list of molecules)
distMatrix = np.zeros((10, 10))
  for i in range(0,10):       
    for j in range(0,10):
      sim = OETanimoto(mols[i],mols[j]) # a function to calculate similarity between molecules
      distMatrix[i][j] = 1 - sim

然后我用命令 distVec = hcluster.squareform(distMatrix) 把这个矩阵转换成一个压缩向量,并用 vecLink = hcluster.linkage(distVec) 来计算连接矩阵。

这一切都运行得很好,但如果我直接用距离矩阵来计算连接矩阵,使用 matLink = hcluster.linkage(distMatrix),我得到的连接矩阵就会不同(节点之间的距离大很多,结构也稍微有点不同)。

现在我不确定这是因为 hcluster 只适用于压缩向量,还是我在这个过程中犯了错误。

谢谢你的帮助!

1 个回答

2

我做了一个和你类似的随机例子,结果遇到了同样的问题。在文档说明里确实提到:

在压缩的距离矩阵 y 上执行层次/聚合聚类。y 必须是一个大小为 :math:{n \choose 2} 的向量,其中 n 是在距离矩阵中配对的原始观测值的数量。

不过,我快速看了一下代码,似乎它的设计是为了同时支持向量和矩阵的格式。在 hierachy.py 文件中,有一个根据矩阵形状的切换。不过,关键的信息在函数 linkage 的文档说明里:

   - Q : ndarray
       A condensed or redundant distance matrix. A condensed
       distance matrix is a flat array containing the upper
       triangular of the distance matrix. This is the form that
       ``pdist`` returns. Alternatively, a collection of
       :math:`m` observation vectors in n dimensions may be passed as
       a :math:`m` by :math:`n` array.

所以我觉得这个接口不允许传入距离矩阵。相反,它认为你传入的是 m 个 n 维的观测向量。这可能就是结果不同的原因吧?

这样说合理吗?

如果不行的话,看看代码本身,我相信你能调试出来,找出为什么你的例子会不同。

谢谢!

马特

撰写回答