694

我在 3D 中有两点:

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

我想计算距离:

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

使用 NumPy 或使用 Python 的最佳方法是什么?我有:

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

23 回答 23

1173

使用numpy.linalg.norm

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

您可以在数据挖掘简介中找到这背后的理论

这是因为欧几里得距离l2 norm ,并且ord参数的默认值为numpy.linalg.norm2。

在此处输入图像描述

于 2009-09-09T20:12:50.387 回答
222

SciPy 中有一个功能。它被称为欧几里得

例子:

from scipy.spatial import distance
a = (1, 2, 3)
b = (4, 5, 6)
dst = distance.euclidean(a, b)
于 2014-02-24T11:32:29.257 回答
159

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

第一个建议是组织您的数据,使数组具有维度(3, n)(并且显然是 C 连续的)。如果加法发生在连续的第一维,事情会更快,如果你使用sqrt-sumwith axis=0linalg.normwithaxis=0

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

这是最快的变体。(这实际上也适用于一排。)

您在第二个轴上总结的变体axis=1, 都慢得多。

在此处输入图像描述


重现情节的代码:

import numpy
import perfplot
from scipy.spatial import distance


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


def linalg_norm_T(data):
    a, b = data[1]
    return numpy.linalg.norm(a - b, axis=0)


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


def sqrt_sum_T(data):
    a, b = data[1]
    return numpy.sqrt(numpy.sum((a - b) ** 2, axis=0))


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


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


def sqrt_einsum_T(data):
    a, b = data[1]
    a_min_b = a - b
    return numpy.sqrt(numpy.einsum("ij,ij->j", a_min_b, a_min_b))


def setup(n):
    a = numpy.random.rand(n, 3)
    b = numpy.random.rand(n, 3)
    out0 = numpy.array([a, b])
    out1 = numpy.array([a.T, b.T])
    return out0, out1


b = perfplot.bench(
    setup=setup,
    n_range=[2 ** k for k in range(22)],
    kernels=[
        linalg_norm,
        linalg_norm_T,
        scipy_distance,
        sqrt_sum,
        sqrt_sum_T,
        sqrt_einsum,
        sqrt_einsum_T,
    ],
    xlabel="len(x), len(y)",
)
b.save("norm.png")
于 2017-12-12T14:46:25.077 回答
54

我想用各种性能说明来解释简单的答案。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))
于 2017-11-28T22:54:12.557 回答
39

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

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)
于 2009-09-09T19:56:36.423 回答
21

开始Python 3.8math模块直接提供dist函数,它返回两点之间的欧几里德距离(以元组或坐标列表的形式给出):

from math import dist

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

如果您正在使用列表:

dist([1, 2, 6], [-2, 3, 2]) # 5.0990195135927845
于 2019-01-15T10:13:47.100 回答
14

可以像下面这样完成。我不知道它有多快,但它没有使用 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)))
于 2012-10-31T10:33:48.733 回答
12

一个不错的单行:

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

但是,如果速度是一个问题,我建议您在您的机器上进行试验。我发现在我的机器上将mathsqrt**正方形的运算符一起使用比单线 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 秒快得多。

为了获得和之间可测量的差异fastest_calc_distmath_calc_dist我必须达到TOTAL_LOCATIONS6000。然后fastest_calc_dist需要约 50 秒,而math_calc_dist需要约 60 秒。

你也可以尝试一下numpy.sqrtnumpy.square尽管两者都比math我机器上的替代品慢。

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

于 2010-11-12T21:40:53.507 回答
10

我在 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)
于 2014-01-06T04:46:53.100 回答
9

您可以只减去向量,然后减去内积。

按照你的例子,

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

tmp = a - b
sum_squared = numpy.dot(tmp.T, tmp)
result = numpy.sqrt(sum_squared)
于 2011-09-10T19:08:12.743 回答
8

我喜欢np.dot(点积):

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

distance = (np.dot(a-b,a-b))**.5
于 2016-09-02T22:14:11.440 回答
6

拥有ab按照您的定义,您还可以使用:

distance = np.sqrt(np.sum((a-b)**2))
于 2016-12-28T15:48:41.497 回答
6

使用 Python 3.8,这非常容易。

https://docs.python.org/3/library/math.html#math.dist

math.dist(p, q)

返回两点 p 和 q 之间的欧几里得距离,每个点都作为坐标序列(或可迭代)给出。这两个点必须具有相同的尺寸。

大致相当于:

sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))

于 2019-12-05T12:27:37.493 回答
5

从 Python 3.8 开始

从 Python 3.8 开始,该math模块包含函数math.dist().
请参阅此处https://docs.python.org/3.8/library/math.html#math.dist

math.dist(p1, p2)
返回两点 p1 和 p2 之间的欧几里得距离,每个点都作为坐标序列(或可迭代)给出。

import math
print( math.dist( (0,0),   (1,1)   )) # sqrt(2) -> 1.4142
print( math.dist( (0,0,0), (1,1,1) )) # sqrt(3) -> 1.7321
于 2019-10-15T18:21:58.817 回答
5

这是 Python 中欧几里得距离的一些简明代码,给定在 Python 中表示为列表的两个点。

def distance(v1,v2): 
    return sum([(x-y)**2 for (x,y) in zip(v1,v2)])**(0.5)
于 2016-05-17T18:22:33.240 回答
3
import math

dist = math.hypot(math.hypot(xa-xb, ya-yb), za-zb)
于 2018-02-22T16:41:05.227 回答
3

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

 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
于 2017-06-14T11:58:32.627 回答
2

您可以轻松使用公式

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

它实际上只不过是使用毕达哥拉斯定理计算距离,通过将 Δx、Δy 和 Δz 的平方相加并将结果求根。

于 2018-04-19T17:50:09.797 回答
2
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)
于 2018-02-10T06:09:01.000 回答
2

其他答案适用于浮点数,但不能正确计算容易上溢和下溢的整数 dtype 的距离。请注意,即使scipy.distance.euclidean有这个问题:

>>> a1 = np.array([1], dtype='uint8')
>>> a2 = np.array([2], dtype='uint8')
>>> a1 - a2
array([255], dtype=uint8)
>>> np.linalg.norm(a1 - a2)
255.0
>>> from scipy.spatial import distance
>>> distance.euclidean(a1, a2)
255.0

这很常见,因为许多图像库将图像表示为 dtype="uint8" 的 ndarray。这意味着如果您有一个由非常深的灰色像素组成的灰度图像(例如所有像素都有颜色#000001)并且您将它与黑色图像(#000000)进行比较,您最终可以在所有单元格中x-y组成255,注册为这两个图像彼此相距很远。对于无符号整数类型(例如 uint8),您可以安全地将 numpy 中的距离计算为:

np.linalg.norm(np.maximum(x, y) - np.minimum(x, y))

对于有符号整数类型,您可以先转换为浮点数:

np.linalg.norm(x.astype("float") - y.astype("float"))

具体来说,对于图像数据,可以使用 opencv 的 norm 方法:

import cv2
cv2.norm(x, y, cv2.NORM_L2)
于 2020-09-04T21:52:57.747 回答
1
import numpy as np
# any two python array as two points
a = [0, 0]
b = [3, 4]

您首先将列表更改为numpy 数组并执行以下操作print(np.linalg.norm(np.array(a) - np.array(b))):直接来自python列表的第二种方法为:print(np.linalg.norm(np.subtract(a,b)))

于 2020-03-12T02:49:21.877 回答
1

先求两个矩阵的差。然后,使用 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
于 2018-07-26T15:11:18.997 回答
1

使用 NumPy 或使用 Python 的最佳方法是什么?我有:

那么最好的方法将是最安全也是最快的

我建议使用hypot来获得可靠的结果,与编写自己的sqroot计算器相比,下溢和溢出的机会非常少

让我们看看 math.hypot、np.hypot vs vanillanp.sqrt(np.sum((np.array([i, j, k])) ** 2, axis=1))

i, j, k = 1e+200, 1e+200, 1e+200
math.hypot(i, j, k)
# 1.7320508075688773e+200
np.sqrt(np.sum((np.array([i, j, k])) ** 2))
# RuntimeWarning: overflow encountered in square

Speed wise math.hypot 看起来更好

%%timeit
math.hypot(i, j, k)
# 100 ns ± 1.05 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
%%timeit
np.sqrt(np.sum((np.array([i, j, k])) ** 2))
# 6.41 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

下溢

i, j = 1e-200, 1e-200
np.sqrt(i**2+j**2)
# 0.0

溢出

i, j = 1e+200, 1e+200
np.sqrt(i**2+j**2)
# inf

无下溢

i, j = 1e-200, 1e-200
np.hypot(i, j)
# 1.414213562373095e-200

无溢出

i, j = 1e+200, 1e+200
np.hypot(i, j)
# 1.414213562373095e+200

参考

于 2021-09-18T09:51:41.523 回答