【问题标题】:problem with hierarchical clustering in PythonPython中的层次聚类问题
【发布时间】:2011-02-25 19:21:32
【问题描述】:

我正在通过相关距离度量(即 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  ]]

我看不出 pdist 在采用 1 - pearson 相关时如何产生负数。对此有什么想法吗?

谢谢。

【问题讨论】:

    标签: python numpy machine-learning scipy hcluster


    【解决方案1】:

    如果你遇到错误

    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));
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 我尝试了以下方法,但没有成功: # 使用 'correlation' Y = clip(Y, 0, 1) 从 pdist 计算 Y 并且我为上面显示的矩阵得到的聚类非常诡异的。知道会发生什么吗?这只发生在“相关”作为 pdist 的参数时。
      • 你可以尝试使用类似 `Y[abs(Y)
      猜你喜欢
      • 1970-01-01
      • 2012-10-10
      • 2016-10-31
      • 2011-01-18
      • 2013-05-08
      • 1970-01-01
      • 2018-10-04
      • 2014-06-28
      • 2021-07-21
      相关资源
      最近更新 更多