我是Python新手,我需要实现一个集群算法。为此,我需要计算给定输入数据之间的距离。
考虑以下输入数据-
[[1,2,8],
[7,4,2],
[9,1,7],
[0,1,5],
[6,4,3]]
我希望在这里实现的是,我想计算[1,2,8]到所有其他点的距离,并找到距离最小的点。
我还要重复这一点。
我试图用FOR循环来实现这一点,但我确信SciPy/NumPy必须有一个能够帮助我高效实现这一结果的函数。
我上网查了一下,但“pdist”命令无法完成我的工作。
有人能指引我吗?
短暂性脑缺血发作
Tags:
这里有一种方法使用^{} -
样本运行-
运行时测试
其他工作方法-
带
10,000
点的计时-进一步提升性能
有一个^{} 包(免责声明:我是它的作者),其中包含各种计算欧几里德距离的方法,这些方法比
SciPy's cdist
更有效,特别是对于大型数组。因此,利用它,我们会有一个更具表现力的,像这样-
时间安排-
将
np.linalg.norm
与广播结合使用(numpy outer subtraction),可以执行以下操作:a[:,None]
在a
中插入一个新轴,a - a[:,None]
然后将由于广播而进行逐行减法。np.linalg.norm
计算最后一个轴上的np.sqrt(np.sum(np.square(...)))
:例如,元素
[0,1]
,[0,2]
对应于:分别是。
我建议使用
pdist
和squareform
fromscipy.spatial.distance
考虑以下点数组:
如果要显示点
[1,2,8]
与其他点之间的所有距离:如果要显示点
[1,2,8]
与最近点之间的最短距离:[0]
是第一个点的索引([1,2,8]
)[1]
是第二个最小值的索引(以避免零)如果要显示距
[1,2,8]
最近的点的索引:相关问题 更多 >
编程相关推荐