距离矩阵的树状图或其他图

Dendrogram or Other Plot from Distance Matrix

我要比较三个矩阵。他们每个人都是5x6。我最初想使用层次聚类来对矩阵进行聚类,以便在给定相似度阈值的情况下将最相似的矩阵分组。

我在python中找不到任何这样的函数,所以我手动实现了距离测量,(p-norm where p=2)。现在我有一个 3x3 距离矩阵(我相信在这种情况下它也是一个相似矩阵)。

我现在正在尝试生成树状图。这是我的代码,这就是错误所在。我 想要 生成一个图(如果可能的话,树状图)来显示最相似的矩阵簇。 Of matrices 0,1,2,0和2是相同的,应该先聚类到一起,1是不同的。

距离矩阵如下所示:

>   0     1    2 
0   0.0    2.0  3.85e-16
1   2.0    0.0  2.0
2 3.85e-16 2.0  0.0

代码:

from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as plt
import numpy as np
from scipy.cluster.hierarchy import linkage
mat = np.array([[0.0, 2.0, 3.8459253727671276e-16], [2.0, 0.0, 2.0], [3.8459253727671276e-16, 2.0, 0.0]])
dist_mat = mat
linkage_matrix = linkage(dist_mat, "single")
dendrogram(linkage_matrix, color_threshold=1, labels=["0", "1", "2"],show_leaf_counts=True)
plt.title=("test")
plt.show()

这是输出:

联动(dist_mat, 'single')是什么意思?我假设输出图看起来像这样,其中 0 和 1 之间的距离为 2.0(例如)。

是否有更好的方法来表示这些数据?是否有一个函数可以接受多个矩阵而不是点,以比较并形成距离矩阵,然后进行聚类?我愿意接受有关如何可视化这些矩阵之间差异的其他建议。

linkage should not be the square distance matrix. It must be the condensed distance matrix. In your case, that would be np.array([2.0, 3.8459253727671276e-16, 2]). You can convert from the square distance matrix to the condensed form using scipy.spatial.distance.squareform

的第一个参数

如果将形状为 (m, n) 的二维数组传递给 linkage,它会将其视为 n 维 [=35] 中 m 个点的数组=] 并计算这些点本身的距离。这就是为什么当您传入平方距离矩阵时没有出现错误,但您得到的绘图不正确。 (这是 linkage 的未记录 "feature"。)

另请注意,由于距离 3.8e-16 非常小,与点 0 和点 2 之间的 link 关联的水平线可能在图中不可见——它位于 x 轴上.

这是您的脚本的修改版本。对于此示例,我已将该微小距离更改为 0.1,因此关联的群集不会被 x 轴遮挡。

import numpy as np

from scipy.cluster.hierarchy import dendrogram, linkage
from scipy.spatial.distance import squareform

import matplotlib.pyplot as plt


mat = np.array([[0.0, 2.0, 0.1], [2.0, 0.0, 2.0], [0.1, 2.0, 0.0]])
dists = squareform(mat)
linkage_matrix = linkage(dists, "single")
dendrogram(linkage_matrix, labels=["0", "1", "2"])
plt.title("test")
plt.show()

这是脚本创建的情节: