3D方面我有两点:

(xa, ya, za)
(xb, yb, zb)

我想计算距离:

dist = sqrt((xa-xb)^2 + (ya-yb)^2 + (za-zb)^2)

使用 NumPy 或一般的 Python 执行此操作的最佳方法是什么?我有:

a = numpy.array((xa ,ya, za))
b = numpy.array((xb, yb, zb))
有帮助吗?

解决方案

使用 numpy.linalg.norm

dist = numpy.linalg.norm(a-b)

其他提示

SciPy中有一个功能。它叫做 Euclidean

示例:

from scipy.spatial import distance
a = (1, 2, 3)
b = (4, 5, 6)
dst = distance.euclidean(a, b)

对于有兴趣一次计算多个距离的人,我使用 perfplot 进行了一些比较(我的一个小项目)。事实证明

a_min_b = a - b
numpy.sqrt(numpy.einsum('ij,ij->i', a_min_b, a_min_b))

计算 a b 中行的距离最快。这实际上只适用于一行!


重现情节的代码:

import matplotlib
import numpy
import perfplot
from scipy.spatial import distance


def linalg_norm(data):
    a, b = data
    return numpy.linalg.norm(a-b, axis=1)


def sqrt_sum(data):
    a, b = data
    return numpy.sqrt(numpy.sum((a-b)**2, axis=1))


def scipy_distance(data):
    a, b = data
    return list(map(distance.euclidean, a, b))


def mpl_dist(data):
    a, b = data
    return list(map(matplotlib.mlab.dist, a, b))


def sqrt_einsum(data):
    a, b = data
    a_min_b = a - b
    return numpy.sqrt(numpy.einsum('ij,ij->i', a_min_b, a_min_b))


perfplot.show(
    setup=lambda n: numpy.random.rand(2, n, 3),
    n_range=[2**k for k in range(20)],
    kernels=[linalg_norm, scipy_distance, mpl_dist, sqrt_sum, sqrt_einsum],
    logx=True,
    logy=True,
    xlabel='len(x), len(y)'
    )

的另一个例子这个问题解决方法

def dist(x,y):   
    return numpy.sqrt(numpy.sum((x-y)**2))

a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))
dist_a_b = dist(a,b)

我想通过各种性能说明来阐述简单的答案。np.linalg.norm 可能会做比你需要的更多的事情:

dist = numpy.linalg.norm(a-b)

首先 - 该函数旨在处理列表并返回所有值,例如比较距离 pA 到点集 sP:

sP = set(points)
pA = point
distances = np.linalg.norm(sP - pA, ord=2, axis=1.)  # 'distances' is a list

记住几件事:

  • Python 函数调用的成本很高。
  • [常规] Python 不缓存名称查找。

所以

def distance(pointA, pointB):
    dist = np.linalg.norm(pointA - pointB)
    return dist

并不像看上去那么无辜。

>>> dis.dis(distance)
  2           0 LOAD_GLOBAL              0 (np)
              2 LOAD_ATTR                1 (linalg)
              4 LOAD_ATTR                2 (norm)
              6 LOAD_FAST                0 (pointA)
              8 LOAD_FAST                1 (pointB)
             10 BINARY_SUBTRACT
             12 CALL_FUNCTION            1
             14 STORE_FAST               2 (dist)

  3          16 LOAD_FAST                2 (dist)
             18 RETURN_VALUE

首先 - 每次我们调用它时,我们都必须对“np”进行全局查找,对“linalg”进行范围查找,对“norm”进行范围查找,而仅仅 呼叫 该函数可以相当于数十条Python指令。

最后,我们浪费了两次操作来存储结果并重新加载它以返回......

改进的第一步:使查找更快,跳过商店

def distance(pointA, pointB, _norm=np.linalg.norm):
    return _norm(pointA - pointB)

我们得到了更加精简的结果:

>>> dis.dis(distance)
  2           0 LOAD_FAST                2 (_norm)
              2 LOAD_FAST                0 (pointA)
              4 LOAD_FAST                1 (pointB)
              6 BINARY_SUBTRACT
              8 CALL_FUNCTION            1
             10 RETURN_VALUE

不过,函数调用的开销仍然需要做一些工作。您需要进行基准测试来确定自己是否可以更好地进行数学计算:

def distance(pointA, pointB):
    return (
        ((pointA.x - pointB.x) ** 2) +
        ((pointA.y - pointB.y) ** 2) +
        ((pointA.z - pointB.z) ** 2)
    ) ** 0.5  # fast sqrt

在某些平台上, **0.5math.sqrt. 。你的旅费可能会改变。

**** 高级性能说明。

为什么要计算距离?如果唯一的目的是展示它,

 print("The target is %.2fm away" % (distance(a, b)))

向前走。但如果您要比较距离、进行范围检查等,我想添加一些有用的性能观察结果。

我们来看两个案例:按距离排序或剔除列表以找到满足范围约束的项目。

# Ultra naive implementations. Hold onto your hat.

def sort_things_by_distance(origin, things):
    return things.sort(key=lambda thing: distance(origin, thing))

def in_range(origin, range, things):
    things_in_range = []
    for thing in things:
        if distance(origin, thing) <= range:
            things_in_range.append(thing)

我们需要记住的第一件事是我们正在使用 毕达哥拉斯 计算距离(dist = sqrt(x^2 + y^2 + z^2))所以我们做了很多 sqrt 来电。数学101:

dist = root ( x^2 + y^2 + z^2 )
:.
dist^2 = x^2 + y^2 + z^2
and
sq(N) < sq(M) iff M > N
and
sq(N) > sq(M) iff N > M
and
sq(N) = sq(M) iff N == M

简而言之:直到我们实际需要以 X 而不是 X^2 为单位的距离时,我们就可以消除计算中最困难的部分。

# Still naive, but much faster.

def distance_sq(left, right):
    """ Returns the square of the distance between left and right. """
    return (
        ((left.x - right.x) ** 2) +
        ((left.y - right.y) ** 2) +
        ((left.z - right.z) ** 2)
    )

def sort_things_by_distance(origin, things):
    return things.sort(key=lambda thing: distance_sq(origin, thing))

def in_range(origin, range, things):
    things_in_range = []

    # Remember that sqrt(N)**2 == N, so if we square
    # range, we don't need to root the distances.
    range_sq = range**2

    for thing in things:
        if distance_sq(origin, thing) <= range_sq:
            things_in_range.append(thing)

太好了,这两个函数不再执行任何昂贵的平方根。这样会快很多。我们还可以通过将 in_range 转换为生成器来改进它:

def in_range(origin, range, things):
    range_sq = range**2
    yield from (thing for thing in things
                if distance_sq(origin, thing) <= range_sq)

如果您正在做以下事情,这尤其有好处:

if any(in_range(origin, max_dist, things)):
    ...

但如果你接下来要做的事情需要一段距离,

for nearby in in_range(origin, walking_distance, hotdog_stands):
    print("%s %.2fm" % (nearby.name, distance(origin, nearby)))

考虑生成元组:

def in_range_with_dist_sq(origin, range, things):
    range_sq = range**2
    for thing in things:
        dist_sq = distance_sq(origin, thing)
        if dist_sq <= range_sq: yield (thing, dist_sq)

如果您要链接范围检查(“查找 X 附近且 Y 的 Nm 范围内的事物”,因为您不必再​​次计算距离),这会特别有用。

但是如果我们要搜索一个非常大的列表呢? things 我们预计其中很多不值得考虑?

其实有一个很简单的优化:

def in_range_all_the_things(origin, range, things):
    range_sq = range**2
    for thing in things:
        dist_sq = (origin.x - thing.x) ** 2
        if dist_sq <= range_sq:
            dist_sq += (origin.y - thing.y) ** 2
            if dist_sq <= range_sq:
                dist_sq += (origin.z - thing.z) ** 2
                if dist_sq <= range_sq:
                    yield thing

这是否有用将取决于“事物”的大小。

def in_range_all_the_things(origin, range, things):
    range_sq = range**2
    if len(things) >= 4096:
        for thing in things:
            dist_sq = (origin.x - thing.x) ** 2
            if dist_sq <= range_sq:
                dist_sq += (origin.y - thing.y) ** 2
                if dist_sq <= range_sq:
                    dist_sq += (origin.z - thing.z) ** 2
                    if dist_sq <= range_sq:
                        yield thing
    elif len(things) > 32:
        for things in things:
            dist_sq = (origin.x - thing.x) ** 2
            if dist_sq <= range_sq:
                dist_sq += (origin.y - thing.y) ** 2 + (origin.z - thing.z) ** 2
                if dist_sq <= range_sq:
                    yield thing
    else:
        ... just calculate distance and range-check it ...

再次考虑生成 dist_sq。我们的热狗示例就变成了:

# Chaining generators
info = in_range_with_dist_sq(origin, walking_distance, hotdog_stands)
info = (stand, dist_sq**0.5 for stand, dist_sq in info)
for stand, dist in info:
    print("%s %.2fm" % (stand, dist))

我在matplotlib.mlab中找到了'dist'函数,但我认为它不够方便。

我在这里发帖仅供参考。

import numpy as np
import matplotlib as plt

a = np.array([1, 2, 3])
b = np.array([2, 3, 4])

# Distance between a and b
dis = plt.mlab.dist(a, b)

可以像下面那样完成。我不知道它有多快,但它没有使用NumPy。

from math import sqrt
a = (1, 2, 3) # Data point 1
b = (4, 5, 6) # Data point 2
print sqrt(sum( (a - b)**2 for a, b in zip(a, b)))

你可以减去向量然后减去内积。

按照你的例子,

a = numpy.array((xa, ya, za))
b = numpy.array((xb, yb, zb))

tmp = a - b
sum_squared = numpy.dot(tmp.T, tmp)
result sqrt(sum_squared)

代码简单,易于理解。

我喜欢 np.dot (点积):

a = numpy.array((xa,ya,za))
b = numpy.array((xb,yb,zb))

distance = (np.dot(a-b,a-b))**.5

启动 Python 3.8 math 模块直接提供 dist function,返回两点之间的欧氏距离(以坐标元组的形式给出):

from math import dist

dist((1, 2, 6), (-2, 3, 2)) # 5.0990195135927845

如果您正在使用列表而不是元组:

dist(tuple([1, 2, 6]), tuple([-2, 3, 2]))

在您定义 a b 时,您也可以使用:

distance = np.sqrt(np.sum((a-b)**2))

一个不错的单行:

dist = numpy.linalg.norm(a-b)

但是,如果速度是一个问题,我建议您在机器上进行试验。我发现在我的机器上使用 math 库的 sqrt ** 运算符比单行NumPy解决方案快得多

我使用这个简单的程序运行我的测试:

#!/usr/bin/python
import math
import numpy
from random import uniform

def fastest_calc_dist(p1,p2):
    return math.sqrt((p2[0] - p1[0]) ** 2 +
                     (p2[1] - p1[1]) ** 2 +
                     (p2[2] - p1[2]) ** 2)

def math_calc_dist(p1,p2):
    return math.sqrt(math.pow((p2[0] - p1[0]), 2) +
                     math.pow((p2[1] - p1[1]), 2) +
                     math.pow((p2[2] - p1[2]), 2))

def numpy_calc_dist(p1,p2):
    return numpy.linalg.norm(numpy.array(p1)-numpy.array(p2))

TOTAL_LOCATIONS = 1000

p1 = dict()
p2 = dict()
for i in range(0, TOTAL_LOCATIONS):
    p1[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))
    p2[i] = (uniform(0,1000),uniform(0,1000),uniform(0,1000))

total_dist = 0
for i in range(0, TOTAL_LOCATIONS):
    for j in range(0, TOTAL_LOCATIONS):
        dist = fastest_calc_dist(p1[i], p2[j]) #change this line for testing
        total_dist += dist

print total_dist

在我的机器上, math_calc_dist 的运行速度远远快于 numpy_calc_dist 1.5秒 23.5秒

要在 faster_calc_dist math_calc_dist 之间获得可测量的差异,我必须将 TOTAL_LOCATIONS 提升到6000.然后 faster_calc_dist 需要 ~50秒,而 math_calc_dist 需要 ~60秒

您也可以尝试使用 numpy.sqrt numpy.square ,尽管两者都比我机器上的 math 替代品慢。

我的测试是使用Python 2.6.6运行的。

这里有一些关于Python中欧几里德距离的简洁代码,给出了两个用Python表示的列表。

def distance(v1,v2): 
    return sum([(x-y)**2 for (x,y) in zip(v1,v2)])**(0.5)
import numpy as np
from scipy.spatial import distance
input_arr = np.array([[0,3,0],[2,0,0],[0,1,3],[0,1,2],[-1,0,1],[1,1,1]]) 
test_case = np.array([0,0,0])
dst=[]
for i in range(0,6):
    temp = distance.euclidean(test_case,input_arr[i])
    dst.append(temp)
print(dst)
import math

dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)

您可以轻松使用公式

distance = np.sqrt(np.sum(np.square(a-b)))

实际上只是使用毕达哥拉斯定理来计算距离,通过添加&#916; x,&#916; y和&#916; z的平方并生成结果。

计算多维空间的欧几里德距离:

 import math

 x = [1, 2, 6] 
 y = [-2, 3, 2]

 dist = math.sqrt(sum([(xi-yi)**2 for xi,yi in zip(x, y)]))
 5.0990195135927845

首先找出两个矩阵的差异。然后,使用numpy的multiply命令应用元素乘法。之后,找到元素的总和乘以新矩阵。最后,找到求和的平方根。

def findEuclideanDistance(a, b):
    euclidean_distance = a - b
    euclidean_distance = np.sum(np.multiply(euclidean_distance, euclidean_distance))
    euclidean_distance = np.sqrt(euclidean_distance)
    return euclidean_distance
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top