【问题标题】:Fast way to calculate min distance between two numpy arrays of 3D points计算两个 3D 点的 numpy 数组之间最小距离的快速方法
【发布时间】:2020-10-13 21:50:03
【问题描述】:

我想知道是否有一种快速的方法来计算 3D numpy 数组 (A [N,3]) 的所有点与第二个 3D numpy 数组 (B [M,3]) 的所有点之间的欧几里得距离。

然后我应该得到一个数组C,这将是[N, M],从数组A的点到数组B的点的所有距离,然后沿指定轴使用np.min()来获得所有最小距离集合点A 到集合点B

这是我迄今为止完成的实现方式:

distances = np.repeat(9999, len(A))
for i, point in enumerate(A):
  min_distance = np.min(np.sqrt(np.sum(np.square(point - B), axis=1)))
  distances[i] = min_distance

有什么办法可以摆脱 for 循环...?

提前致谢:)

【问题讨论】:

  • from scipy.spatial import distance_matrix; dist_mat = distance_matrix(A,B).

标签: python arrays numpy distance


【解决方案1】:

如果scipy方法不起作用或者你确实有其他原因,这里有一个numpy方法-

import numpy as np


x = np.random.random((200, 3))
y = np.random.random((100,3))

x = x.reshape((-1, 1, 3))                 # [200x1x3]
y = np.expand_dims(y, axis=0)             # [1x100x3]
y = y.repeat(x.shape[0], axis=0)          # [200x100x3]

distance = np.linalg.norm(y-x, axis=2)    # Difference is [200x100x3] and norm results in [200x100]

【讨论】:

    【解决方案2】:
    import numpy as np
    
    # arrays with xyz coordinates of all points 
    a = np.asarray([[xa1,ya1,za1],...,[xan,yan,zan]])
    b = np.asarray([[xb1,yb1,zb1],...,[xbn,ybn,zbn]])
    
    # reshaping to be able to calculate the distance matrix
    a_reshaped = a.reshape(a.shape[0], 1, 3)
    b_reshaped = b.reshape(1, b.shape[0], 3)
    
    """calculation of all distances between all points  - creates a 
    len(a) x len(b) matrix""" 
    distance = np.sqrt(np.sum((a_reshaped - b_reshaped)**2, axis=2))
    

    【讨论】:

    • 虽然这段代码可以回答这个问题,但最好包含一些上下文,解释它是如何工作的以及何时使用它。从长远来看,纯代码的答案没有用处。
    猜你喜欢
    • 2019-02-26
    • 2022-07-21
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    相关资源
    最近更新 更多