用 scipy 找到两个数组的点之间的最短距离

Find shortest distance between points of two arrays with scipy

我有两个数组 centroidsnodes

我需要找到centroids中每个点到nodes

中任意点的最短距离

centroids 的输出如下

array([[12.52512263, 55.78940022],
       [12.52027731, 55.7893347 ],
       [12.51987146, 55.78855611]])
       

nodes 的输出如下

array([[12.5217378, 55.7799275],
       [12.5122589, 55.7811443],
       [12.5241664, 55.7843297],
       [12.5189395, 55.7802709]])

我用下面的代码得到最短距离

shortdist_from_centroid_to_node = np.min(cdist(centroids,nodes))

然而,这是我得到的输出(我应该得到 3 行输出)

Out[131]: 3.0575613850140956e-05

任何人都可以指定这里的问题是什么吗?谢谢。

如果我没记错的话,你的代码说你正在尝试访问 min 值,因此你得到的是一个值。删除 np.min() 尝试:

shortdist_from_centroid_to_node = cdist(centroids,nodes)

当您执行 np.min 时,它 return 二维数组的最小值。 您需要每个质心的最小值。

shortest_distance_to_centroid = [min(x) for x in cdist(centroids,nodes)]

要获得关联索引,一种方法是获取相应值的索引。另一种方法是编写一个自定义的 min() 函数,该函数还 return 索引(因此您只解析列表一次)

[(list(x).index(min(x)), min(x)) for x in cdist(centroids,nodes)]  # the cast list() is needed because numpy array don't have index methods

具有自定义函数的解决方案:

def my_min(x):
       current_min = x[0]
       current_index = [1]

       for i, v in enumerate(x[1:]):
              if v < current_min:
                     current_min = v
                     current_index = i + 1
       return (current_index, current_min)

[my_min(x) for x in cdist(centroids,nodes)]

我猜你需要的只是添加一个名为 axis 的参数,就像这样:

shortdist_from_centroid_to_node = np.min(cdist(centroids,nodes), axis=1)

axis arg的含义可以参考numpy.min。总而言之,你需要每一行的最小值而不是整个矩阵。