Python中的层次聚类问题

时间:2010-05-30 22:52:42

标签: python numpy machine-learning scipy hcluster

我正在通过相关距离度量(即1-Pearson相关)对二维矩阵进行分层聚类。我的代码如下(数据在一个名为“data”的变量中):

from hcluster import *

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

我得到的错误是:

ValueError: Linkage 'Z' contains negative distances. 

导致此错误的原因是什么?我使用的矩阵“数据”只是:

[[  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 个答案:

答案 0 :(得分:5)

有一些可爱的浮点问题正在发生。如果你看一下pdist的结果,你会发现它们中的负数非常小(-2.22044605e-16)。基本上,它们应该为零。如果您愿意,可以使用numpy的剪辑功能来处理它。

答案 1 :(得分:0)

如果您遇到错误

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));
相关问题