gpt4 book ai didi

linux - fcluster 包中具有余弦相似性度量的层次聚类

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:28:50 28 4
gpt4 key购买 nike

我使用 scipy.cluster.hierarchy 使用“余弦”相似性度量对一组点进行层次聚类。例如,我有:

import scipy.cluster.hierarchy as hac 
import matplotlib.pyplot as plt

Points =
np.array([[ 0. , 0.23508573],
[ 0.00754775 , 0.26717266],
[ 0.00595464 , 0.27775905],
[ 0.01220563 , 0.23622067],
[ 0.00542628 , 0.14185873],
[ 0.03078922 , 0.11273108],
[ 0.06707743 ,-0.1061131 ],
[ 0.04411757 ,-0.10775407],
[ 0.01349434 , 0.00112159],
[ 0.04066034 , 0.11639591],
[ 0. , 0.29046682],
[ 0.07338036 , 0.00609912],
[ 0.01864988 , 0.0316196 ],
[ 0. , 0.07270636],
[ 0. , 0. ]])


z = hac.linkage(Points, metric='cosine', method='complete')
labels = hac.fcluster(z, 0.1, criterion="distance")


plt.scatter(Points[:, 0], Points[:, 1], c=labels.astype(np.float))
plt.show()

由于我使用余弦度量,在某些情况下,两个向量的点积可能为负,或者某些向量的范数可能为零。这意味着 z 输出将包含一些对 fcluster 无效的负数或无限元素(如下所示):

z =
[[ 0.00000000e+00 1.00000000e+01 0.00000000e+00 2.00000000e+00]
[ 1.30000000e+01 1.50000000e+01 0.00000000e+00 3.00000000e+00]
[ 8.00000000e+00 1.10000000e+01 4.26658708e-13 2.00000000e+00]
[ 1.00000000e+00 2.00000000e+00 2.31748880e-05 2.00000000e+00]
[ 3.00000000e+00 4.00000000e+00 8.96700489e-05 2.00000000e+00]
[ 1.60000000e+01 1.80000000e+01 3.98805492e-04 5.00000000e+00]
[ 1.90000000e+01 2.00000000e+01 1.33225099e-03 7.00000000e+00]
[ 5.00000000e+00 9.00000000e+00 2.41120340e-03 2.00000000e+00]
[ 6.00000000e+00 7.00000000e+00 1.52914684e-02 2.00000000e+00]
[ 1.20000000e+01 2.20000000e+01 3.52441432e-02 3.00000000e+00]
[ 2.10000000e+01 2.40000000e+01 1.38662986e-01 1.00000000e+01]
[ 1.70000000e+01 2.30000000e+01 6.99056531e-01 4.00000000e+00]
[ 2.50000000e+01 2.60000000e+01 1.92543748e+00 1.40000000e+01]
[ -1.00000000e+00 2.70000000e+01 inf 1.50000000e+01]]

为了解决这个问题,我检查了 linkage() 函数,我需要在其中检查 _hierarchy.linkage() 方法。我使用 pycharm 文本编辑器,当我要求“链接”源代码时,它在目录中打开了一个名为“_hierarchy.py”的 python 文件,如下所示:

.PyCharm40/system/python_stubs/-1247972723/scipy/cluster/_hierarchy.py  

此 python 文件没有对所有包含的函数进行任何定义。
我想知道修改此函数的正确来源是什么,或者是否有其他方法可以解决此问题。我将不胜感激你的帮助和提示。

最佳答案

您的数据集中有一个零向量 0 0。对于此类数据,余弦距离未定义,因此您使用的距离函数不合适!这是一个无法轻易弥补的定义差距。 inf0 一样不正确。到 0 0 的距离 不能 在没有矛盾的情况下定义。您不得对此类数据使用余弦。

回到您的实际问题:_hierarchy 是一个 Cython 模块。 它不是纯 python,而是编译为 native 代码。你可以很容易地在 Github 上看到源代码:

https://github.com/scipy/scipy/blob/master/scipy/cluster/_hierarchy.pyx

关于linux - fcluster 包中具有余弦相似性度量的层次聚类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30488156/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com