Python中的层次聚类问题

10 投票
2 回答
3861 浏览
提问于 2025-04-15 23:21

我正在对一个二维矩阵进行层次聚类,使用的是相关距离度量(也就是1减去皮尔逊相关系数)。我的代码如下(数据存储在一个叫“data”的变量里):

from hcluster import *

Y = pdist(data, 'correlation')
cluster_type = 'average'
Z = linkage(Y, cluster_type)
dendrogram(Z)

我遇到的错误是:

ValueError: Linkage 'Z' contains negative distances. 

这个错误的原因是什么呢?我使用的“data”矩阵其实就是:

[[  156.651968  2345.168618]
 [  158.089968  2032.840106]
 [  207.996413  2786.779081]
 [  151.885804  2286.70533 ]
 [  154.33665   1967.74431 ]
 [  150.060182  1931.991169]
 [  133.800787  1978.539644]
 [  112.743217  1478.903191]
 [  125.388905  1422.3247  ]]

我不明白为什么在计算1减去皮尔逊相关系数时,pdist会产生负数。有没有什么想法呢?

谢谢。

2 个回答

3

如果你遇到了这个错误:

KeyError: -428

而你的代码大概是这样的:

import matplotlib.pyplot as plt
import matplotlib as mpl

%matplotlib inline 
from scipy.cluster.hierarchy import ward, dendrogram

linkage_matrix = ward(dist) #define the linkage_matrix using ward clustering pre-computed distances
fig, ax = plt.subplots(figsize=(35, 20),dpi=400) # set size
ax = dendrogram(linkage_matrix, orientation="right",labels=queries);

这通常是因为查询的索引不匹配导致的。

你可能需要更新成:

ax = dendrogram(linkage_matrix, orientation="right",labels=list(queries));
5

这里有一些有趣的浮点数问题。如果你查看pdist的结果,会发现里面有一些非常小的负数(比如-2.22044605e-16)。其实这些数应该是零。如果你想处理这些小负数,可以使用numpy的clip函数。

撰写回答