[英]vectorized / linear algebra distance between points?
Suppose I have an array of points, 假设我有很多点,
import numpy as np
pts = np.random.rand(100,3) # 1000 points, X, Y, Z along second dimension
The naive approach to calculate the distance between each combination of points involves a double for loop and will be excruciatingly slow for large numbers of points, 天真的方法来计算每个点的组合之间的距离涉及一个双for循环,并且对于大量的点将非常慢,
def euclidian_distance(p1, p2):
d = p2 - p1
return np.sqrt(d**2).sum()
out = np.empty((pts.shape[0], pts.shape[0]))
pts_swapped = pts.swapaxes(0,1)
for idx, point in enumerate(pts_swapped):
for idx2, point_inner in enumerate(pts_swapped):
out[idx,idx2] = euclidian_distance(point, point_inner)
How do I vectorize this calculation? 如何向量化此计算?
Take a look at the scipy.spatial.distance.cdist . 看看scipy.spatial.distance.cdist 。 I'm not sure but i assume that scipy optimized this quite a lot.
我不确定,但是我认为scipy对此进行了很多优化。 If you use the pts array for both inputs, I assume you'll get an M x M array with zeros on the diagonal .
如果您对两个输入都使用pts数组,那么我假设您会得到一个M x M数组,对角线为零。 function
功能
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.