如何使用NumPy计算欧几里得距离?

我在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))

#1楼

可以像下面这样完成。 我不知道它有多快,但是它没有使用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)))

#2楼

此问题解决方法的另一个实例:

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)

#3楼

使用numpy.linalg.norm

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

背后的理论:如数据挖掘导论所述

之所以有效,是因为欧几里得距离l2范数,并且numpy.linalg.norm中ord参数的默认值为2。

在此处输入图片说明


#4楼

我在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)

#5楼

SciPy中有一个功能。 这就是欧几里得语

例:

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

#6楼

这是一些Python中的欧几里得距离的简洁代码,给出了用Python列表表示的两个点。

def distance(v1,v2): 
    return sum([(x-y)**2 for (x,y) in zip(v1,v2)])**(0.5)

#7楼

我喜欢np.dot (点积):

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

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

#8楼

在定义ab同时,还可以使用:

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

#9楼

一个不错的单线:

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_dist1.5秒23.5秒

为了获得fastest_calc_distmath_calc_dist之间的可测量差异,我必须将TOTAL_LOCATIONS为6000。然后, fastest_calc_dist需要约50秒,math_calc_dist需要约60秒

您也可以使用numpy.sqrtnumpy.square实验,尽管它们都比我机器上的math方法慢。

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


#10楼

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

 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

#11楼

我想用各种性能说明来解释简单答案。 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))

#12楼

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

第一个建议是组织数据,使数组具有维度(3, n) (并且显然是C连续的)。 如果在连续的第一维中进行添加,则操作会更快,并且如果将sqrt-sumaxis=0 linalg.norm使用,或者将linalg.normaxis=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


perfplot.save(
    "norm.png",
    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,
    ],
    logx=True,
    logy=True,
    xlabel="len(x), len(y)",
)

#13楼

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)

#14楼

import math

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

#15楼

您可以轻松使用公式

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

实际上,这无非是使用毕达哥拉斯定理来计算距离,方法是将Δx,Δy和Δz的平方相加并取根。


#16楼

首先找到两个矩阵的差。 然后,通过numpy的乘法命令应用逐元素乘法。 然后,找到逐元素相乘的新矩阵的总和。 最后,找到求和的平方根。

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

#17楼

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

from math import dist

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

如果您正在使用列表:

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

#18楼

从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

#19楼

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

按照您的示例,

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)

它是简单的代码,易于理解。

发布了0 篇原创文章 · 获赞 2 · 访问量 5914

猜你喜欢

转载自blog.csdn.net/asdfgh0077/article/details/104069531
今日推荐