linkage()
的输入可以是一个 n x m 数组,表示在 m 维空间中的 n 个点,或者是包含
压缩 距离矩阵 的一维数组。在您的示例中,
mat
是 3 x 3,因此正在对三个三维点进行聚类。聚类基于这些点之间的距离。
为什么这里的 mat 和 1-mat 产生相同的聚类?
数组
mat
和
1-mat
产生相同的聚类,因为聚类是基于点之间的距离计算的,整个数据集的反射(
-mat
)或平移(
mat+offset
)都不会改变点之间的相对距离。
如何使用树状图注释每个分支上的距离,以便比较节点对之间的距离?
在下面的代码中,我展示了如何使用 dendrogram 返回的数据来标注图表的水平线段,并将其与相应的距离关联起来。与键
icoord
和
dcoord
相关联的值给出了图形中每个三段反向U的x和y坐标。在
augmented_dendrogram
中,使用此数据为树状图中每个水平线段添加距离(即y值)标签。
from scipy.cluster.hierarchy import dendrogram
import matplotlib.pyplot as plt
def augmented_dendrogram(*args, **kwargs):
ddata = dendrogram(*args, **kwargs)
if not kwargs.get('no_plot', False):
for i, d in zip(ddata['icoord'], ddata['dcoord']):
x = 0.5 * sum(i[1:3])
y = d[1]
plt.plot(x, y, 'ro')
plt.annotate("%.3g" % y, (x, y), xytext=(0, -8),
textcoords='offset points',
va='top', ha='center')
return ddata
对于你的
mat
数组,增强型树状图如下所示:
![dendrogram for three points](https://istack.dev59.com/jTvuj.webp)
因此,点'a'和'c'之间相距1.01个单位,而点'b'距离群集['a','c']有1.57个单位。
似乎忽略了show_leaf_counts
标志,有没有一种方法可以打开它以显示每个类中的对象数量?
当不是所有原始数据点都显示为叶节点时,
show_leaf_counts
标志才适用。例如,在
trunc_mode = "lastp"
时,只显示最后的
p
节点。
这是一个包含100个点的例子:
import numpy as np
from scipy.cluster.hierarchy import linkage
import matplotlib.pyplot as plt
from augmented_dendrogram import augmented_dendrogram
np.random.seed(12312)
n = 100
x = np.random.multivariate_normal([0, 0], np.array([[4.0, 2.5], [2.5, 1.4]]),
size=(n,))
plt.figure(1, figsize=(6, 5))
plt.clf()
plt.scatter(x[:, 0], x[:, 1])
plt.axis('equal')
plt.grid(True)
linkage_matrix = linkage(x, "single")
plt.figure(2, figsize=(10, 4))
plt.clf()
plt.subplot(1, 2, 1)
show_leaf_counts = False
ddata = augmented_dendrogram(linkage_matrix,
color_threshold=1,
p=6,
truncate_mode='lastp',
show_leaf_counts=show_leaf_counts,
)
plt.title("show_leaf_counts = %s" % show_leaf_counts)
plt.subplot(1, 2, 2)
show_leaf_counts = True
ddata = augmented_dendrogram(linkage_matrix,
color_threshold=1,
p=6,
truncate_mode='lastp',
show_leaf_counts=show_leaf_counts,
)
plt.title("show_leaf_counts = %s" % show_leaf_counts)
plt.show()
这些是数据集中的点:
![100个点的散点图](https://istack.dev59.com/aDoGF.webp)
当 p=6
和 trunc_mode="lastp"
时,dendrogram
只显示树形图的“顶部”。以下内容展示了 show_leaf_counts
的效果。
![显示 show_leaf_counts 的效果](https://istack.dev59.com/ZsX79.webp)
linkage
接受包含压缩距离矩阵的1-d数组或点的2-d数组。它不接受密集距离矩阵。我会更新我的答案以反映这一点。 - Warren Weckesserlinkage
文档的开发版本:http://scipy.github.io/devdocs/generated/scipy.cluster.hierarchy.linkage.html - Warren Weckesser